Shawnzey Shawnzey - 3 months ago 13
Android Question

Run a method every time an activity is shown

I have an if statement checking if there are any rows in a sqlite database. If there are rows existing in the database it enables some buttons, if not it will disable the buttons.

like so

DBHandler dbHandler = new DBHandler(this, null, null, 1);
SQLiteDatabase db = dbHandler.getWritableDatabase();
String count = "SELECT count(*) FROM clients";
Cursor mcursor = db.rawQuery(count, null);
mcursor.moveToFirst();
int icount = mcursor.getInt(0);
if(icount == 0)
{
btnViewClient.setEnabled(false);
btnViewAppt.setEnabled(false);
btnAddAppt.setEnabled(false);
btnViewBill.setEnabled(false);
btnAddBill.setEnabled(false);
}
else
{
btnViewClient.setEnabled(true);
btnViewAppt.setEnabled(true);
btnAddAppt.setEnabled(true);
btnViewBill.setEnabled(true);
btnAddBill.setEnabled(true);
}


that is in my onCreate method.

So now if the user adds a row into the sqlite database and hits the back button returning to the main menu. How can I run this code again and enable the buttons? I need to run this code every time the activity is shown, but I don't want to finish the activity because then you can't use the back button to return to it.

Answer Source

You might want to learn a bit more about Activity Lifecycle.

Particularly, you need to use onResume method - it will be called every time your app will return to your Activity.

So just put your code above to this method.