简体   繁体   English

每次显示活动时运行一种方法

[英]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语句,检查sqlite数据库中是否有任何行。 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. 那是在我的onCreate方法中。

So now if the user adds a row into the sqlite database and hits the back button returning to the main menu. 因此,现在,如果用户在sqlite数据库中添加一行并单击“后退”按钮,则返回到主菜单。 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. 每次显示该活动时,我都需要运行此代码,但是我不想结束该活动,因为那样便无法使用“后退”按钮返回到该活动。

You might want to learn a bit more about Activity Lifecycle . 您可能想了解更多有关Activity Lifecycle的知识

Particularly, you need to use onResume method - it will be called every time your app will return to your Activity . 特别是,您需要使用onResume方法-每次您的应用返回到Activity时都会调用该方法。

So just put your code above to this method. 因此,只需将您的代码放在该方法上即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM