Diego Fortes
Diego Fortes

Reputation: 207

Android SQLite: Spinner + select sql methods

I have a Spinner which is showing SQLite data. For that I am using this select method:

public List<String> getAllProductsName(int id)
{

    String buildSQL = "SELECT nome FROM " + DatabaseHelper.Produtos.TABELA + " WHERE id =" + id;


    List<String> nomes = new ArrayList<String>();

    SQLiteDatabase db = this.getDatabase();

    Cursor cursor = database.rawQuery(buildSQL, null);

    if (cursor.moveToFirst()) {
        do {
            nomes.add(cursor.getString(0));
        } while (cursor.moveToNext());
    }

    return nomes;
}

The thing is, I am getting only the names but I need the ID as well. I know i could use "SELECT nome, _id FROM ", but how would I return that? Could i possibly return 2 lists (one with IDS and the other one with the Names) in the same method?

Or maybe I should create a new method that show the Names only (when i give the ID as a parameter)? Please help! thanks in advance! :)

Upvotes: 0

Views: 468

Answers (1)

Matej Špil&#225;r
Matej Špil&#225;r

Reputation: 2687

How about something like this ... using and returning HashMap that contains ID as keys and nome as values

public HashMap<Integer,String> getAllProductsName(int id)
    {

        String buildSQL = "SELECT nome,_id FROM " + DatabaseHelper.Produtos.TABELA + " WHERE id =" + id;


        HashMap<Integer,String> idAndNomes = new HashMap<Integer,String>();

        SQLiteDatabase db = this.getDatabase();

        Cursor cursor = database.rawQuery(buildSQL, null);

        if (cursor.moveToFirst()) {
            do {
                idAndNomes.put(cursor.getInt(1), cursor.getString(0)));
            } while (cursor.moveToNext());
        }

        return idAndNomes;
    }

Then you can use:

idAndNomes.keySet() - Returns a set of the keys contained in this map. In our case ID.

idAndNomes.values() - Returns a collection of the values contained in this map. In our case nomes.

Upvotes: 1

Related Questions