Fill spinner with SQLite data [duplicate]

1

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

Query in Sqlite to bring all records in 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 the buffer.append concatenate commas and commas to stay the same way if I entered the information manually eg: {"test", "test2", "test3"} .... also did not work.

My spinner looks like this:

    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 I get

test

test2

test3

is getting on the same line: test test2 test3

If someone can help me ...

    
asked by anonymous 05.03.2017 / 03:49

1 answer

2

The setAdapter() method receives an Array that must contain the items that Spinner should list. Each item in this array must match a line in the Credentials table.

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

What you should do is construct the Array while looping through the Cursor. Declare a method to this effect:

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);

    
05.03.2017 / 14:57