Grab database ID when selecting option in spinner?

Asked

Viewed 1,693 times

1

Usually I get the ID of a selected object/clicked with the onItemClickListener, but it does not work with the Spinner.

I tried that way:

spn.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
   @Override
   public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
       test1 = position;
       test2 = (int) id;
       test3 = view.getId();
   }

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

Also unsuccessfully, it returns me only the position of the items within the spinner, and not the database ID.

Any idea?

Edit: It’s worth mentioning that this is all inside one onItemClickListener of a Custom List View, and the Spinner is in a Custom Dialog the part.

1 answer

1


You can use the method getSelectedItem to get the value of a selected item.

Create the following class Spinnerobject:

public class SpinnerObject {

    private  int databaseId;
    private String databaseValue;

    public SpinnerObject ( int databaseId , String databaseValue ) {
        this.databaseId = databaseId;
        this.databaseValue = databaseValue;
    }

    public int getId () {
        return databaseId;
    }

    public String getValue () {
        return databaseValue;
    }

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

}

Now you will have to create the list as follows:

public List < SpinnerObject> getAllLabels(){
    List < SpinnerObject > labels = new ArrayList < SpinnerObject > ();
    // Seleciona todas as consultas
    String selectQuery = "SELECT  * FROM " + TABLE_LABELS;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // Loop através de todas as linhas e adicionando à lista
    if ( cursor.moveToFirst () ) {
        do {
            labels.add ( new SpinnerObject ( cursor.getString(0) , cursor.getString(1) ) );
        } while (cursor.moveToNext());
    }

    // Fecha conexão
    cursor.close();
    db.close();

    return labels;
}

Now that you have the list of objects with the values and the ids, you load the Spinner as follows:

private void loadSpinnerDataHama() {
    // database handler
    DatabaseSpinner db = new DatabaseSpinner(getApplicationContext()); 
    List <SpinnerObject> lables = db.getAllLabels();
    // Criando adaptador para o spinner
    ArrayAdapter<SpinnerObject> dataAdapter = new ArrayAdapter<SpinnerObject>(this,
    android.R.layout.simple_spinner_item, lables);
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    // Anexando adaptador de dados para o spinner
    spn.setAdapter(dataAdapter);
}

The spinner display values, although they have their ids (from the database) as well.

To recover the ID of the selected item:

int itemId = Integer.parseInt(((SpinnerObject) spn.getSelectedItem()).getId());

Reference

  • Hello good friend! Thank you for your time and reply. He’s returning me to String with the product name, I needed the ID, you know if I can get the ID through this method?

  • Again, thanks for the help, but it’s still not working. I’m getting this error: java.lang.Classcastexception: java.lang.String cannot be cast to android.os.Message E also did not show the option . getId(); here, only getData();

  • Unfortunately no, it returns only the product name, not the database ID. This is one of the most difficult problems I have found on android! EDIT: I have not seen your last post, I will test again!

  • What would Spinnerobject be? I don’t have that class, if I create it what I should put inside it?

  • I’m getting this mistake yet: java.lang.Classcastexception: java.lang.String cannot be cast to spinnerobject.Spinnerobject :(

  • Why is it being so hard? Will it be an android bug? will it be if I upgrade android studio that to? xd

  • @Diegofortes It is not bug no :D... I edited the answer and put in full the following steps.

  • Man, thanks for everything but unfortunately it still won’t. It’s giving me a big headache already this, I’ll have to see later calmly... I did all the steps and also checked the reference, but it doesn’t work at all. The problem now is that everything appears empty in Spinner, doesn’t show my entries; and, if it wasn’t enough, it still doesn’t show the ID. XD has to have some easier way or I’m doing mt wrong

  • Man, I figured out why it’s not working.... When I call my SQL function I’m just calling a column, the Name column, then it’s impossible to return the ID. Everything you posted is fine, but there is a much simpler way, this: http://stackoverflow.com/questions/20822515/how-to-get-the-id-of-selected-item-in-a-spinner Thank you very much for all your help!!!!

Show 4 more comments

Browser other questions tagged

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