Reputation: 529
In my activity I want to use the 'onRetainNonConfigurationInstance' method to store some of the data I've loaded in the activity (no views). This should speed up loading and keep a consistent state when the orientation changes.
Since the return argument is a single Object and I want to return two items I've come up with the following solution:
@Override
public Object onRetainNonConfigurationInstance() {
HashMap< String, Object> data = new HashMap<String, Object>();
data.put( "mAdapter", getExpandableListAdapter() );
data.put( "folderList", folderList );
return data;
}
When I collect the data in my onCreate method with:
HashMap<String, Object> savedData = ( HashMap< String, Object> ) getLastNonConfigurationInstance();
I get an unchecked cast warning from the compiler. I assume this is because the compiler cannot determine if the HashMap with the specified types is actually going to be in the Object return by getLastNonConfigurationInstance. I then cast the Objects in the HashMap to the proper datatypes. My question is this:
Is this a safe way to pass multiple pieces of data back to the activity onCreate when I know that the data is going to be returned in the form of a HashMap (because I stored it there)?
I think I can suppress the warning with @SuppressWarnings("unchecked") but I want to be sure that my code is valid.
Kind regards, Ivo
Upvotes: 1
Views: 1147
Reputation: 28932
Why use a hashmap instead of a simple struct-like holding class when you know the comprehensive set of contents at compile time?
Also, beware passing anything that holds a reference to a Context/Activity between activity instances like this. Chances are that adapter you're passing holds a Context reference so that it can get a LayoutInflater to inflate item views. This will have two negative effects:
This is why the method is called "non-configuration instance." It is only correct to return objects that are not influenced by configuration. In the case of something like an adapter that holds a context, pass the data that the adapter accesses rather than the adapter itself and create a new adapter in the new activity instance.
Upvotes: 2