Android listview arrayadapter sqlite

0

I'm trying to fill a listview with data from a sqlite table but I do not know what I'm doing wrong, here's the code if someone can help me, the instruction is at the end in btnconsultar .

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    txtCodigo = (EditText)findViewById(R.id.texto1);
    txtNombre = (EditText)findViewById(R.id.texto2);
    btnInsertar = (Button)findViewById(R.id.Btn1);
    btnConsultar = (Button)findViewById(R.id.Btn2);
    txtResultado = (TextView)findViewById(R.id.txtResultado);
    lista = (ListView) findViewById(R.id.list1);
    //Abrimos la base de datos 'DBUsuarios' en modo escritura
    final UsuariosSQLiteHelper usdbh = new UsuariosSQLiteHelper(this, "DBUsuarios", null, 1);
    db = usdbh.getWritableDatabase();

    btnInsertar.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            //Recuperamos los valores de los campos de texto
            String cod = txtCodigo.getText().toString();
            String nom = txtNombre.getText().toString();

            //Alternativa 1: método sqlExec()
            //String sql = "INSERT INTO Usuarios (codigo,nombre) VALUES ('" + cod + "','" + nom + "') ";
            //db.execSQL(sql);

            //Alternativa 2: método insert()
            ContentValues nuevoRegistro = new ContentValues();
            nuevoRegistro.put("codigo", cod);
            nuevoRegistro.put("nombre", nom);
            db.insert("Usuarios", null, nuevoRegistro);

            //Alternativa 1: método rawQuery()
            Cursor c = db.rawQuery("SELECT codigo, nombre FROM Usuarios", null);

            //Alternativa 2: método delete()
            //String[] campos = new String[] {"codigo", "nombre"};
            //Cursor c = db.query("Usuarios", campos, null, null, null, null, null);

            //Recorremos los resultados para mostrarlos en pantalla
            txtResultado.setText("");
            if (c.moveToFirst()) {
                //Recorremos el cursor hasta que no haya más registros
                do {
                    cod = c.getString(0);
                    nom = c.getString(1);

                    txtResultado.append(" " + cod + "      " + nom + "\n");
                } while(c.moveToNext());
            }
        }
    });

    btnConsultar.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            ArrayList<String> items = new ArrayList<>();
            SQLiteDatabase db= usdbh.getReadableDatabase();
            Cursor fila= db.rawQuery("select * from Usuarios",null);
            if(fila.moveToFirst()){
                do{
                    items.add("codigo: "+fila.getString(0)+"\n"+
                              "nombre: "+fila.getString(1));
                }while (fila.moveToNext());
            }
            ArrayAdapter<String> adaptador = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,items);
            lista.setAdapter(adaptador);
        }
    });
}
    
asked by juan perez 11.09.2018 в 23:18
source

1 answer

1

The problem is that in the initialization of the ArrayAdapter, this context is not working, it must be changed by the name of the class, for example

 ArrayAdapter<String> adaptador = new ArrayAdapter<String>(tuclase.this,android.R.layout.simple_list_item_1,items);

Something to keep in mind is to use notifyDataSetChanged() when you need to notify the list to update with new sql data, so when you upload new things you just call

adaptador.notifyDataSetChanged();

Then the list would be updated with the new data and you would not have to call or reopen your app to load the adapter with the new data.

    
answered by 11.09.2018 / 23:49
source