开发者

recovering activity state with getLastNonConfigurationInstance generates an unchecked cast warning

In my activity I want to use the 'onRetainNonConfigurationIns开发者_StackOverflowtance' 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


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:

  • Activities can be big, and hanging on to a reference to one that has been destroyed will keep the garbage collector from collecting it. (This is the sort of thing people mean when they talk about leaking contexts or activities.)
  • Contexts carry configuration info like screen orientation and theme. If you reuse an old context for something like inflating layouts after a configuration change, you'll end up using the wrong configuration data. If you've used the resource system to provide different layouts for portrait and landscape modes, for example, this won't work properly.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜