1

Hello everybody im new on android and i'm having a problem getting the "id" from my spinner loaded from mysql. the thing is i need an specific "id" depending on which option i selected, the info its loading well but i dont know how to get that id. For example, i selected my client named "Joseph" and its id is "24", how can i get that "24" on a toast or on a textview. i leaving my code here so i hope you can helpme,

On Create -->

    spinnercliente = (Spinner) findViewById(R.id.vencliente);
    clienteList = new ArrayList<ListarClientes>();
    // seleccionar las frutas del spinner
    spinnercliente.setOnItemSelectedListener(this);
    new Getcliente().execute();
}
private void populateSpinner() {
    List<String> lables = new ArrayList<String>();
    for (int i = 0; i < clienteList.size(); i++) {
        lables.add(clienteList.get(i).toString());
    }
    ArrayAdapter<ListarClientes> spinnerAdapter = new ArrayAdapter<ListarClientes>(this, android.R.layout.simple_spinner_item,clienteList);
    spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinnercliente.setAdapter(spinnerAdapter);
}
private class Getcliente extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(RegFacturas.this);
        pDialog.setMessage("Obteniendo Clientes..");
        pDialog.setCancelable(false);
        pDialog.show();
    }
    @Override
    protected Void doInBackground(Void... arg0) {
        ServiceHandler jsonParser = new ServiceHandler();
        String json = jsonParser.makeServiceCall(URL_LISTA_CLIENTE+"?Usuario="+datoNombre, ServiceHandler.GET);
        Log.e("Response: ", "> " + json);
        if (json != null) {
            try {
                JSONObject jsonObj = new JSONObject(json);
                if (jsonObj != null) {
                    JSONArray cliente = jsonObj
                            .getJSONArray("clientes");

                    for (int i = 0; i < cliente.length(); i++) {
                        JSONObject catObj = (JSONObject) cliente.get(i);
                        ListarClientes cat = new ListarClientes(catObj.getInt("id"),
                                catObj.getString("nombre"));
                        clienteList.add(cat);
                    }
                }else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(RegFacturas.this);
                    builder.setMessage("Error al cargar los clientes").setNegativeButton("Aceptar", null).create().show();
                    finishActivity(1);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("JSON Data", "¿No ha recibido ningún dato desde el servidor!");
        }
        return null;
    }
    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        if (pDialog.isShowing())
            pDialog.dismiss();
        populateSpinner();
    }
}
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long id) {
    Toast.makeText(adapterView.getContext(), (String) adapterView.getItemAtPosition(pos), Toast.LENGTH_SHORT).show();
    ListarClientes client = (ListarClientes) adapterView.getItemAtPosition(pos);
    idcli = client.getId();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {    }
}

ListarClienteClass

public class ListarClientes {
private int id;
private String name;
public ListarClientes() {}
public ListarClientes(int id, String name) {
    this.setId(id);
    this.setName(name);
}
public int getId() {return id;}
public void setId(int id) {this.id = id;}
//public String getName() {return name;}
@Override
public String toString(){return name;}
public void setName(String name) {this.name = name;}

}

1 Answers1

0

Instead of using ArrayAdapter<String>, use ArrayAdapter<ListarClientes> and in the class ListarClientes, override the method toString and return name.

Add this method to your class:

@Override
public String toString(){
    return name;
}

Then, instead of passing labels, directly pass clienteList while creating the adapter.

After that you can get an item of type ListarClientes inside the onItemSelected method.

ListarClientes client = (ListarClientes) adapterView.getItemAtPosition(pos);
int id = client.getId(); 
Nabin Bhandari
  • 15,949
  • 6
  • 45
  • 59
  • this is my ListarClientes class, when u said 'override the method toString and return name ' what do i need to change ?, im editing my code so you can see it –  Oct 24 '17 at 02:41
  • as a question ,do i need to override the id as well?, the code its on the question –  Oct 24 '17 at 02:58
  • No you don't need to. You already have the method `getId()`. The method `toString()` should be overridden so that the names will be displayed in the spinner. – Nabin Bhandari Oct 24 '17 at 03:00
  • the app its stopping , so i thing something is misplaced, can you check the code ?, please. I update it –  Oct 24 '17 at 03:13
  • remove the toast. or don't cast it to String – Nabin Bhandari Oct 24 '17 at 03:26