无法在onSaveInstanceState中捆绑数据

时间:2015-01-06 20:39:34

标签: java android bundle scope instance-variables

我试图保存以下数据:

 @Override
    public void setMessageDetailsExpanded(MessageHeaderItem i, boolean expanded,
            int heightBefore) {
        mDiff = (expanded ? 1 : -1) * Math.abs(i.getHeight() - heightBefore);
        String mHeaderItem = i.toString();
        final boolean  mDetailsExpanded = expanded;
        int mHeightBefore = heightBefore;
    }

在上面设置断点时,我会看到我想要捆绑的数据:

mMessageHeaderItem = com.android.mail.browse.ConversationViewAdapter$MessageHeaderItem@425a6f40

detailsExpanded = true 

heightBefore = 229

然而,当在onSaveInstanceState上设置断点时 - 看来我的输出不包含上面的数据?!

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    outState.putFloat(BUNDLE_KEY_WEBVIEW_Y_PERCENT, calculateScrollYPercent());
    outState.putBoolean(getTag(), mDetailsExpanded);
    outState.putInt(getTag(),  height);
    outState.putString(getTag(), mHeaderItem);

}


Im not sure why but for some reason when debugging the code above it contains the following: 



 mDetailsExpanded = False

    height = 0 

    mHeaderItem = null 

我知道我忽略了一些小事 - 但我似乎无法弄清楚为什么我没有在setMessageDetailsExpanded的{​​{1}}中保存数据onSavedInstanceState

完整来源:

http://pastebin.com/Larzbwzh

2 个答案:

答案 0 :(得分:3)

第一个问题:您需要声明要用作类变量的变量

public class MyClass {
     private int x;
     private String y;
     ....

然后您可以在其他功能中正确访问它们。

第二个问题:在捆绑包中保存所需的变量后调用super

outState.putString("myString", y);
super.onSaveInstanceState(outState) 

答案 1 :(得分:1)

看起来你的变量mHeaderItem,mDetailsExpanded,mHeightBefore在setMessageDetailsExpanded中是本地的/重新定义的。因此,在onSaveInstanceState中看不到指定的值。