andzrev
andzrev

Reputation: 564

Preserving ListView on subsequent activity launches

The main activity has a "To ListView" button that launches a new activity with a list view. Each time this new activity loads, it calls an AsyncTask() method that retrieves some JSON remotely, parses it, and binds the data to the list view. Then, setContentView() is called (in onPostExecute()) to show the UI. How do I preserve the list view data, or at least the data array (for rebinding) on subsequent launches of that activity so that the ASyncTask() doesn't have to be called every time?

The ASyncTask() should get called only at the beginning (and not until when the application is forcefully terminated), subsequent calls should be done manually by the user perhaps with an onClick() event. I have tried setting a boolean for that purpose, but if so how to display the previous state of the list view when the boolean is false? I have also looked into onResume() and onBackPressed() but they don't seem to be much relevant.

Main.java:

    toListView.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent myIntent = new Intent(getApplicationContext(), ListView.class);
            startActivity(myIntent);
        }
    });

ListView.java:

    public class ListView extends ActionBarActivity {
private static boolean isFirstLaunch = true;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    if (isFirstLaunch) {
        // execute the ASyncTask();
        isFirstLaunch = false;
    }
    // else display previous listview data or last activity state
}// onCreate()

Upvotes: 0

Views: 37

Answers (1)

Marcus
Marcus

Reputation: 6717

For persisting data in your Android application, you have two obvious choices.

  • Using an SQLite database. This alternative is good if you have quite a lot of data to manage, sort and maintain. E.g if your JSON response contains a lot of data, persisting it to a database would be a good solution. Then you would simply query the database instead of executing the AsyncTask repeatedly. Vogella provides an excellent tutorial on this matter.
  • Using SharedPerefences. This alternative is better if you only have a couple of variables to relate to. Storing the data in SharedPreferences relieves you of the work needed to design and implement database support for you application. See the official documentation for a reference.

Upvotes: 1

Related Questions