Update BD after entering record

0

I use the following code to insert a record in sqlite:

    public void InsereSenha(String Nome, String Senha, String Dica, String Anotacao) {
    String sql = "INSERT INTO Senha (Nome, Senha, Dica, Anotacao) VALUES (?, ?, ?, ?)";
    try
    {
        database.execSQL(sql, new String[]{Nome, Senha, Dica, Anotacao});
    }
    catch (Exception ex)
    {

    }

}

It inserts the record, but when giving the select to get all the records of this table and show in listview , the new record does not appear, which I just registered. How to give a "refresh" in the bd to get the new registry?

Edit 1:

The adapter that should display the records I just inserted:

        final DatabaseAccess databaseAccess = DatabaseAccess.getInstance(this);
    databaseAccess.open();
    List<Senha> senhas = databaseAccess.getSenha();
    databaseAccess.close();

    CustomAdapter adapter = new CustomAdapter(getApplicationContext(), senhas);

    Lista.setAdapter(adapter);

Edit 2:

Based on Márcio Oliveira's response, I re-engineered the code. This is how it works:

public class MainActivity extends AppCompatActivity {

ListView Lista;
List<Senha> senhas;
CustomAdapter adapter;
final DatabaseAccess databaseAccess = DatabaseAccess.getInstance(this);


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Lista = (ListView)findViewById(R.id.Lista_Senhas);

    databaseAccess.open();
    senhas = databaseAccess.getSenha();
    databaseAccess.close();

    if (adapter == null) {
        adapter = new CustomAdapter(getApplicationContext(), senhas);
    }else {
        adapter.notifyDataSetChanged();
    }

    Lista.setAdapter(adapter);

}

}

    
asked by anonymous 11.07.2017 / 20:57

1 answer

2

In the database you do not need to do anything. As you've implemented, just reload your list of passwords ( List<Senha> senhas ) and notify the adapter that the list has been updated with a adapter.notifyDataSetChanged() .

Consider using a CursorLoader / CursorAdapter in the listview to access the database directly instead of loading data every time into an array. Depending on the amount of data, you can leave the interface slow or crash.

    
11.07.2017 / 21:46