开发者

getLastNonConfigurationInstance always returning null

HashMap myMap = (HashMap) getLastNonConfigurationInstance();

myMap is always null. getLastNonConfigurationInstance() returns an object. My map has two k开发者_JS百科eys "symbol" and "name".

public Object onRetainNonConfigurationInstance()
    {
        HashMap myMap = new HashMap();
        myMap.put("symbol", this.symbol);
        final Object data = myMap;
        return data;
    }


I faced the same issue. Looks like calling getLastNonConfigurationInstance() in anything other than onCreate() returns null. I moved the statement to onCreate() method and voila..it returned what I expected it to return.


If getLastNonConfigurationInstance() returns a non-null object, then (HashMap) getLastNonConfigurationInstance() will either return the same object (if that object is a HashMap), or throw a ClassCastException.

The situation that you describe is not possible, not unless you've uncovered a long-hidden bug in Java's cast operator. Hint: you haven't.

Verify that getLastNonConfigurationInstance() is actually returning a non-null object. Verify that myMap is actually null. If you're using a debugger to check those values, try printing them to the console instead. Debuggers can lie to you sometimes, or at least mislead.


You haven't told us in what situation this happens? onRetainNonConfigurationInstance() is called before an Activity's onDestroy() when a configuration change happens.


getLastNonConfigurationInstance() will return reference which was saved in onRetainNonConfigurationInstance() method.

onRetainNonConfigurationInstance() method will be called between onStop and onDestroy is case of any configuration change, here you can save any Object reference.

Activity keeps this reference till onResume call.

Activity.class

final void performResume(boolean followedByPause, String reason) {
    ...
    mLastNonConfigurationInstances = null;       // clearing reference
    ...
    mInstrumentation.callActivityOnResume(this); // onResume
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜