活动之间保存状态 [英] Saving state between activities

查看:96
本文介绍了活动之间保存状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为firstActivity.java,secondActivity.java 2活动。 当我点击firstActivity一个按钮,我打电话secondActivity。但当我返回从secondActivity的基础上,我需要跳过这是在它的onCreate()方法进行firstactivity一些步骤的结果。 虽然我来自secondActivity我用包把我给作为输入意向数据传回,我访问的第一活动的onCreate()数据。 但是,当我开始活动应用程序崩溃显示为NullPointerException异常在我第二次访问活动的数据线。我想原因是当应用程序启动的第一次也不会有在捆绑让我得到空指针exception.so任何值,任何人都可以帮助我在设法解决这个问题?

I have 2 activities named firstActivity.java,secondActivity.java. When I click a button in firstActivity, I am calling secondActivity .But when I return back from secondActivity ,based on the result I need to skip some steps in firstactivity which are performed in its onCreate() method. While coming back from secondActivity I used Bundle to put data which I gave as input to Intent, I accessed that data in onCreate() of first activity . But while I started activity application was crashing showing as NullPointerException in the line where I am accessing data of 2nd activity. the reason I think is when the application is launched for the first time there will not be any values in Bundle so I am getting nullpointer exception.so, can anyone help me in sorting out this issue?

在此先感谢,

推荐答案

您必须实现的onSaveInstanceState(捆绑savedInstanceState),并节省您想保存到一个捆绑值。实施onRestoreInstanceState(包savedInstanceState)恢复捆绑,并重新设置数据:

You have to implement the onSaveInstanceState(Bundle savedInstanceState) and save the values you would like to save into a Bundle. Implement onRestoreInstanceState(Bundle savedInstanceState) to recover the Bundle and set the data again:

public class MyActivity extends Activity {
    /** The boolean I'll save in a bundle when a state change happens */
    private boolean mMyBoolean;

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        savedInstanceState.putBoolean("MyBoolean", mMyBoolean);
        // ... save more data
        super.onSaveInstanceState(savedInstanceState);
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        mMyBoolean = savedInstanceState.getBoolean("MyBoolean");
        // ... recover more data
    }
}

在这里你可以找到有关国家处理使用文档:<一href="http://developer.android.com/reference/android/app/Activity.html">http://developer.android.com/reference/android/app/Activity.html

只要搜索的文档茨艾伦方法:P

Just search for thos methods in the docs :P

这篇关于活动之间保存状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆