【问题标题】:Retrieving data from bundles in android从android中的bundle中检索数据
【发布时间】:2011-10-25 23:36:48
【问题描述】:

所以我设法解决了从捆绑包中检索信息的问题,但我不得不做一些我认为很奇怪的事情。我首先尝试的方法是这样的:

public void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
            list = savedInstanceState.getInt("listmenu");
}

这就是我将信息放入包中并调用活动的方式:

Intent myIntent = new Intent(MainActivity.this, NewActivity.class);
            myIntent.putExtra("listmenu", R.menu.listmenu);
            MainActivity.this.startActivity(myIntent);

但这没有用。它只会在第 3 行崩溃,这是我尝试 getInt 的列表(我无法找出确切原因,但它不起作用)。

然后经过一番谷歌搜索后,我尝试了这种方式:

public void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
            Bundle extras = getIntent().getExtras();
            list = extras.getInt("listmenu");
}

在我看来,getIntent().getExtras() 只会返回 savedInstanceState。但如果是这种情况,那么我的第一种方法会奏效。所以我一定误解了 savedInstanceState 是什么,或者 getIntent() 是做什么的,那么有人可以解释一下这两者之间的区别是什么吗?

【问题讨论】:

    标签: android android-intent bundle


    【解决方案1】:

    如果活动被销毁然后重新创建,即配置更改,则将捆绑包传递给 onCreate()。如果您想在重新创建活动时保存数据,则需要覆盖 onSaveInstanceState。此捆绑包将同时传递给 onCreate 和 onRestoreInstanceState。

    您包含的第二个代码块对于读取传递给新启动活动的捆绑包是正确的。这是否澄清了事情?最好的办法是阅读the Activity doc.中每个的描述

    【讨论】:

    • 是的,我认为这可以澄清事情。因此,如果活动已经存在并且正在以某种方式恢复,我只会收到 savedInstanceState 吗?否则我需要使用 getIntent().getExtras()?
    • 不恢复,如果它被销毁并重新创建。如果您想向自己证明这一点,我建议您覆盖所有这些方法并进行日志调用,例如 Log.d("lifecycle", "onCreate()"), Log.d("lifecycle", "onPause ()") 等...
    • 来自于 savedInstanceState 的 javadoc:If the activity is being re-initialized after previously being shut down then this Bundle contains the data it most recently supplied in onSaveInstanceState(Bundle). Note: Otherwise it is null.
    猜你喜欢
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    • 2015-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多