views:

111

answers:

2
HashMap myMap = (HashMap) getLastNonConfigurationInstance();

myMap is always null. getLastNonConfigurationInstance() returns an object. My map has two keys "symbol" and "name".

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

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.

Michael Petrotta
I have updated my code to show onRetainNonConfigurationinstance()
Sheehan Alam
@Sheehan - what's the relevance?
Michael Petrotta
I'm not sure why it's returning null.
Sheehan Alam
@Sheehan: are you saying that `onRetainNonConfigurationInstance()` is the same as `getLastNonConfigurationInstance`? Why the different names? Is there a step in the middle there, that could be causing the problem? Review the last paragraph of my answer.
Michael Petrotta
on the android platform, onRetainNonConfigurationInstance() saves some data, and to retrieve that saved data getLastNonConfigurationInstance() is called. The OS handles everything else inbetween.
Sheehan Alam
@Sheehan: then something's going wrong in that middle step. What did you see when you printed the output of `getLastNonConfigurationInstance()`?
Michael Petrotta
@Sheehan: your issue is with the relevant API on the Android platform, not the Java language. I think you'll get better help here if you rewrite your question around that.
Michael Petrotta
Thanks Michael. I will do that.
Sheehan Alam
A: 

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

Romain Guy