9

我正在尝试进入 Android 编程,因为我从书中得到了一些示例。在这些示例中,要求输入以下代码:

public class ExemploCicloVida extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        Log.i(TAG, getClassName() + " onCreate() called on: " + icicle);

        TextView t = new TextView(this);
        t.setText("Exemplo de ciclo de vida de uma Activity.\nConsulte os logs no LogCat");
        setContentView(t);
    }
}

我想知道为什么 Bundle 对象在这种情况下总是为空。

4

5 回答 5

16

如果没有先前保存的状态,则捆绑包将为空。

这在ActivityAPI 文档中有所提及。

于 2011-11-13T03:05:51.623 回答
10

就我而言,原因是特定活动没有在清单文件中声明主题。

要解决此问题,请打开 AndroidManifest.xml,单击 Application,在 Application Nodes 中选择崩溃的活动,然后在 Attributes 的 Theme 字段中添加主题。在我的情况下,它是

@style/Theme.AppCompat.Light.DarkActionBar

但您可以从其他活动中复制主题。

PS:我知道这是一个老问题的答案,但我在寻找修复程序时偶然发现了它,但没有找到有效的解决方案,所以这可能对其他人有所帮助。

于 2014-02-05T21:03:30.650 回答
2

运行此代码并按 Ctrl+F11 旋转屏幕。捆绑包不会为空。

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    if (savedInstanceState != null) {
        Toast.makeText(this, savedInstanceState.getString("s"),
                Toast.LENGTH_LONG).show();
    }
}

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

    outState.putString("s", "hello");
}

onSaveInstanceState(Bundle)将被调用。然后,活动对象被创建,onCreated(Bundle)并将被调用非空Bundle savedInstanceState

于 2011-11-13T03:28:29.850 回答
0

我猜你想阅读进入你活动的参数。使用这个功能:

protected String getStringExtra(Bundle savedInstanceState, String id) {
String l;
l = (savedInstanceState == null) ? null : (String) savedInstanceState
            .getSerializable(id);
if (l == null) {
    Bundle extras = getIntent().getExtras();
    l = extras != null ? extras.getString(id) : null;
}
return l;
}
于 2014-05-14T04:58:34.043 回答
0

首先,Dave 是对的——如果没有以前保存的状态——就像应用程序刚刚创建/启动一样,就不会有状态。但是,由于您的评论看起来像是在处理生命周期示例,因此我还提供以下内容:

当从保存在 onSaveInstanceState 中的包中获取内容时,您将通过在查找包的内容之前调用 onCreate 的父级来覆盖这段代码中该包的内容。用你的超级电话切换你的日志,它应该可以正常工作:

 @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        Log.i(TAG, getClassName() + " onCreate() called on: " + icicle);

在那一长串覆盖中的某个时刻,捆绑包被设置为空

于 2020-08-12T18:54:36.693 回答