安卓:仅使用内的onCreate getIntent()? [英] Android: using getIntent() only within onCreate?

查看:675
本文介绍了安卓:仅使用内的onCreate getIntent()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Android的(目标的API 14-16)我有一个 MainActivity NextActivity 。有使用意向,开始没有什么困难 NextActivity 从内部 MainActivity 如果 getIntent()方法被调用的的onCreate()块内的 NextActivity

In Android (targeting APIs 14-16) I have a MainActivity and a NextActivity. There is no difficulty using intents to start NextActivity from within MainActivity if the getIntent() method is called inside the onCreate() block of NextActivity:

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int data = 7;
        ...
        Intent intent = new Intent(this, NextActivity.class);
        intent.putExtra("data", data);
        startActivity(intent);
        }
    }

public class NextActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final int data = this.getIntent().getIntExtra("data", 7);
        ...
        }
    ...
    }

然而,由于该领域数据正在使用一个匿名的(内部)类中的 NextActivity ,我不得不宣布它最后

However, since the field data is being used inside an anonymous ("inner") class in NextActivity, I am compelled to declare it final.

我preFER不申报领域最后,我通常避免这样做,如果我在类的开头声明他们,之前的onCreate()开始。但由于某些原因,应用程序崩溃时 NextActivity 开始后,如果出现 getIntent()语句(不包括最后关键字)之外的onCreate()

I'd prefer not to declare fields final, and I can usually avoid doing so if I declare them at the beginning of the class, before onCreate() begins. But for some reason, the app crashes when NextActivity starts if the getIntent() statement appears (without the final keyword) outside of onCreate().

任何想法,为什么?

推荐答案

您不能 getIntent()的onCreate() - 有在这一点上根本没有意图可用。我相信同样是真正的东西,需要一个上下文

You can't getIntent() before onCreate() -- there's simply no Intent available at that point. I believe the same is true for anything that requires a Context.

您匿名内部类仍可以调用 getIntent(),但是,所以你并不需要在所有的这个声明为一个变量。

Your anonymous inner class can still call getIntent(), however, so you don't need to declare this as a variable at all.

这篇关于安卓:仅使用内的onCreate getIntent()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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