简体   繁体   中英

how to use interface to communicate between activity and sqlite databse helper class

I am new to android. Currently I am working on android application which uses sqlitedb as the app user may not have continuous internet connection.

My problem is - There is one ReportActivity which shows all data from sqlite in recyclerview.
There is add option which starts AddReport Activity. When I add that new report to server, I start on Service which fetch data from server and store to sqlite. And return to Report Activity.
Now I wanted to update my data in ReportActivity after sqlite db is updated. I tried using interface but it is giving nullpointer exception .
So how I can use interface in that. I don't want to use broadcast receiver.

You can either use startActivityForResult() and return an intent to trigger refresh/fetch the data again on ReportActivity once you finish() the AddReportActivity :

ReportActivity:

public class ReportActivity extends Activity {

  private static final int REQUEST_ADD_REPORT = 1;
  ...
  private void showAddReport() {
    Intent intent = new Intent(this, AddReportActivity.class);
    startActivityForResult(intent, REQUEST_ADD_REPORT);
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_ADD_REPORT &&
         resultCode == ACTIVITY_OK) {
       // trigger refresh
    }
  }
}

AddReportActivity :

public class AddReportActivity extends Activity {
  ...
  private void addReport() {
     // do some logic on adding the report
     setResult(ACTIVITY_OK);
     finish();
  }
}

Or you can just override onResume() on ReportActivity and move the fetching of data from sqlite in there, so every time the activity resumes, it will always get the updated data.

You can refer to android activity lifecycle on when the onResume() is being called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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