Search code examples
javaandroidsqliteandroid-sqliteandroid-spinner

How to use item selected from spinner


I have a spinner. I populated it with data(of one column) from a database table. Now when a user select an item from spinner. I want a function in database which returns corresponding primary key of the selected item. In my main activity that primary key should be stored in a variable. How can I do this.

This is my code in main activity:

if(spinner.getSelectedItem() != null){
    spinner_text = (String) spinner.getSelectedItem();
    try {
        substation_number = myDB.spinnerResult(spinner_text);
    } catch (NumberFormatException e) {
        Toast.makeText(getApplicationContext(), "Please select an item", Toast.LENGTH_SHORT).show();
    }
}

This is my function in database:

public int spinnerResult(String item_name){
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery("Select substationNo from " + TABLE_NAME + " where item_name = ?", new String[]{item_name});
    return Integer.parseInt(String.valueOf(cursor));
}

Solution

  • The cursor you get by rawQuery() should return at most 1 row (if item_name is unique in the table) with 1 column.
    You must check with moveToFirst() if the item_name you passed exists in the table and then extract the value of substationNo from the cursor:

    public int spinnerResult(String item_name){
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery("Select substationNo from " + TABLE_NAME + " where item_name = ?", new String[]{item_name});
        int result = 0; // you may change this
        if (cursor.moveToFirst()) result = cursor.getInt(0);
        cursor.close();
        db.close();
        return result;
    }
    

    If the item_name you passed does not exist in the table the function returns 0 which you may change to -1 if you want and you can check it to verify that the item_name was found.