Fill spinner with Sqlite data

Asked

Viewed 1,243 times

1

I have an application with Sqlite, I make a select to return the values of a field and save it in a variable.
I wanted to use these values in a spinner, but it is not getting in the list but all values in one item.

Sqlite query to bring all records from the Title column:

    Cursor c=db.rawQuery("SELECT * FROM Credenciais",null);
    StringBuffer buffer = new StringBuffer();
    while (c.moveToNext())
    {
        buffer.append(c.getString(c.getColumnIndex("Titulo")));
    }
    String lista = buffer.toString();

I tried in buffer.append to concatenate quotation marks and comma to stay the same way if I entered the information manually ex: {"test", "teste2", "teste3"}.... didn’t work either.

My spinner is this way:

    String[] Credenciais = new String[] {lista};

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_conteudo);

    Spinner spin = (Spinner) findViewById(R.id.spn_lista_conteudo);
    spin.setOnItemSelectedListener(this);


    ArrayAdapter aa = new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, Credenciais);
    aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    spin.setAdapter(aa);
}

When I run the application instead of the drop down stay

test

teste2

teste3

is staying in the same line : test teste2 teste3

If anyone can help me...

1 answer

3

The method setAdapter() receives an Array that must contain the items that Spinner must list. Each item in that array must correspond to a row in the table Credentials.

What you’re doing is building, through append(), a string with the contents of all lines. The Array is built(new String[] {lista};) just with this string, getting everything in a single item.

What you should do is build the Array by scrolling through the Cursor.
State a method for this purpose:

public ArrayList<String> getCredenciais(){
    ArrayList<String> credenciais = new ArrayList<String>();
    Cursor cursor = db.rawQuery("SELECT * FROM Credenciais",null);
    if(cursor != null && cursor.moveToFirst()){
        do{
            credenciais.add(cursor.getString(cursor.getColumnIndex("Titulo")));
        }while(cursor.moveToNext());
    }
    return credenciais;
}

Use it like this to create Spinner:

Spinner spin = (Spinner) findViewById(R.id.spn_lista_conteudo);
...
...

ArrayList<String> credenciais = getCredenciais();
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, credenciais);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

spin.setAdapter(adapter);

Note: I’ve changed the way I navigate Cursor to one that I think is more appropriate.

  • Thank you very much. I needed to change a part and adapt in the code, but your concept helped me a lot and now it’s working.

Browser other questions tagged

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