eric
eric

Reputation: 4951

How to know if there is an Activity Instance currently living?

Situation:
When quitting a main activity of an android app, I wish to call a method on a living instances of an Activity to make them clear data in arrays (so that the arrays are not already populated when returning to the app).

In MainActivity.java

// ...
@Override
public void onDestroy() {       
   super.onDestroy();
   // call method to clear an array list of its data
   // NullPointerException here if OtherActivity has no current living instance
   OtherActivity.clearAllData();        
}

In OtherActivity.java

// ...
private static ArrayList <String> myStringCollection;
// ...
public static void clearAllData(){
   if(myStringCollection.size() > 0){
     myStringCollection.clear();
     Log.d(TAG, "clearing data in OtherActivity");
   }

}

Question:
How can we know whether OtherActivity has a current living instance so that we can make a safe call to OtherActivity.clearAllData() ?

What the code attempts to do:
After quitting the app and returning to it, some ArrayLists still have old data in them, and as a result the new data (duplicate) gets stacked on top. This code attempts to clear data from the ArrayLists on the onDestroy() of the main activity, so that there will be no old data when returning to the app later.

Upvotes: 0

Views: 153

Answers (1)

Grimmace
Grimmace

Reputation: 4041

Your code is currently using static variables. Static variables are attached to the ClassLoader not the actual instance of the class. This means you don't actually need a valid living instance to do what you are doing above. Just use a check like myStringCollection != null to guarantee that your variable has been initialized and you should be fine.

Note, please clarify if you really do want to access non-static variables.

Upvotes: 2

Related Questions