Pass Database values to Spinner

Asked

Viewed 874 times

0

I am searching client values in the database through PHP/MYSQL and I am returning via JSON, and I would like to pass to SPINNER more than 1 argument (idclient + client name)... In this case, I managed to run the SPINNER by passing the "client name" that appears to be selected... How do I pass the "client" also... In this case, I would like to replace the SPINNER ID with the "idclient"... Below is the code that I return the JSON, including in the Adapter...

Below is the code edited with the modifications, full code.

Client class

public class Cliente {

private int mId;
private String mNome;

public Cliente(int id, String nome) {
    mId = id;
    mNome = nome;
}

public int getId() {
    return mId;
}

public String getNome() {
    return mNome;
}

}

Registration Class

public class RegistrarActivity extends AppCompatActivity {

private ImageView botaoVoltar;
private Button botaoRegistrar;
private EditText textoCPF, textoEmail;
private Spinner spinnerCliente;
private Cliente cliente;
private String idcliente;
private ArrayList<Cliente> clientes = new ArrayList<>();
private RequestQueue requestQueue, requestQueue2;
private static final String URL = "http://www.caixinhadosmotoristas.com.br/spinner-cliente.php";
private static final String URLReg = "http://www.caixinhadosmotoristas.com.br/validacao.php?acao=register";
private StringRequest request, request2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_registrar);

    botaoVoltar = (ImageView) findViewById(R.id.botaoVoltarId);
    botaoRegistrar = (Button) findViewById(R.id.botaoRegistrarId);
    textoCPF = (EditText) findViewById(R.id.textoCpfId);
    textoEmail = (EditText) findViewById(R.id.textoEmailId);
    spinnerCliente = (Spinner) findViewById(R.id.spinnerClienteId);

    requestQueue = Volley.newRequestQueue(this);
    requestQueue2 = Volley.newRequestQueue(this);

    RetornaJSONClientes();

    ArrayAdapter arrayAdapter = new ArrayAdapter (this, android.R.layout.simple_spinner_dropdown_item, clientes);
    arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinnerCliente.setAdapter(arrayAdapter);

    spinnerCliente.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            cliente = (Cliente) parent.getItemAtPosition(position);
            idcliente = "1";
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            cliente = null;
        }
    });

    SimpleMaskFormatter mascaraCPF = new SimpleMaskFormatter("NNN.NNN.NNN-NN");
    MaskTextWatcher maskCPF = new MaskTextWatcher(textoCPF, mascaraCPF);
    textoCPF.addTextChangedListener(maskCPF);

    botaoRegistrar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            request2 = new StringRequest(Request.Method.POST, URLReg, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (jsonObject.names().get(0).equals("200")){
                            Toast.makeText(getApplicationContext(), jsonObject.getString("mensagem"), Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(getApplicationContext(), jsonObject.getString("mensagem"), Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }){
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    idcliente = "" + cliente.getId();
                    HashMap<String, String> hashMap = new HashMap<String, String>();
                    hashMap.put("idcliente", idcliente);
                    hashMap.put("nome", cliente.getNome());
                    hashMap.put("cpf2", textoCPF.getText().toString());
                    hashMap.put("email", textoEmail.getText().toString());
                    return hashMap;
                }
            };

            requestQueue2.add(request2);
        }
    });

    botaoVoltar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent voltaLogin = new Intent(RegistrarActivity.this, LoginActivity.class);
            startActivity(voltaLogin);
        }
    });
}

private void RetornaJSONClientes(){
    request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            String jsonString;
            int jsonInt;

            try {
                JSONArray jsonArray = new JSONArray(response);

                for(int i = 0; i < jsonArray.length(); i++){
                    jsonString = jsonArray.getJSONObject(i).getString("nome");
                    jsonInt = jsonArray.getJSONObject(i).getInt("idcliente");

                    clientes.add(new Cliente(jsonInt, jsonString));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });

    requestQueue.add(request);
}

}

  • Hello, I reversed your last edition because the previous question was already solved and you added a new question. It’s okay to create more questions, but click https://answall.com/questions/ask and put your new question there. Consider this topic closed and consider accepting the answer that helped you the most. See more here: https://pt.meta.stackoverflow.com/a/1079/3117

1 answer

2


Create a class Cliente, with the variables id and nome and go storing the json data in a ArrayList<Cliente>

Ex:

public class Cliente {

    private int mId;
    private String mName;

    public Cliente(int id, String name) {
        mId = id;
        mName = name;
    }

    public int getId() {
        return mId;
    }

    public String getName() {
        return mName;
    }

    public String toString() {
        return mName;
    }   
}

ArrayList<Cliente> clientes = new ArrayList<>();
clientes.add(new Cliente(1, "Fulano 1"));
clientes.add(new Cliente(2, "Fulano 2"));

When creating Spinner Adapter, associate with Arraylist above. Ex:

ArrayAdapter spinnerAdapter = new ArrayAdapter(this,
            android.R.layout.simple_spinner_item, clientes);

To access a Spinner client:

Cliente cliente;
Spinner spinner; // Inicialize com o findViewById, setAdapter, etc


spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        cliente = (Cliente) parent.getItemAtPosition(position);
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        cliente = null;
    }
});
  • I made the modifications you put up there, and it’s still going wrong, the spinner initializes normally, only the data passed to it, is with the "link" all... I’ll put an image at the end of the question for you to see how it is...

  • My fault. I edited my answer. Failed to create a toString() method in the class that stores the data to define what will appear in the spinner.

  • My buddy, gave right now, just one more help, in the case of my code above, by clicking the register button, I send the data through a Hashmap<String, String>, as I would send the idcliente also, that in the case is "int"... Is there any way you can help me with that detail? I’ll edit the question with the updated code.

  • 1

    I suggest you go back to the question and create a new one, as your previous question could help other people. The way it is now, it seems my answer has no meaning to the question.

  • Got it, I’ll ask you a new question, sorry, I’m new around here, I’m getting the hang of it.. rs!

  • No stress. We are there to help (when it gives, rs)

  • Marcio, can you help me with this question here? To bumping head and it’s complicated, I’m sending you the link of the question... https://answall.com/questions/223970/enviando-datos-para-banco-mysql-comphp

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.