简体   繁体   English

将Intent传递给函数将引发NullPointerException

[英]pass Intent to function throws NullPointerException

In an Android I would like to pass an Intent Object to a function, but consistently get a NullPointerException. 在Android中,我想将Intent对象传递给函数,但始终获得NullPointerException。

I could not find any source citing that this is not possible. 我找不到任何消息来源援引这是不可能的。

basically I have this: 基本上我有这个:

 public Intent intent;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    intent = getIntent();
    int check = elsewhere.chk_intent(intent); //<=THROWS ERROR

     }

chk_intent() performs some functions on data transmitted with the intent, especieally if some extra fields are present. chk_intent()对按意图传输的数据执行某些功能,特别是如果存在一些额外的字段。

I tried to move getIntent() into this function, but this is not allowed. 我试图将getIntent()移到此函数中,但这是不允许的。

Any help would be much appreciated 任何帮助将非常感激

Is this activity called by another activity? 该活动是否被另一个活动调用? The intent will not be null only if previous activity supplies an intent to the current activity: 仅当先前活动向当前活动提供意图时,该意图才会为空:

// previous activity
Intent intent = new Intent(FirstActivity.class, SecondActivity.class);
int value = 10;
intent.putIntExtra("key", value);
startActivity(intent);

// use this if want to return data 
//startActivityForResult(intent);

If this activity is the starting (main) activity or it is not called by any previous activity, then getIntent() is null, you need to initialize your own new Intent object. 如果此活动是开始(主)活动或之前的任何活动未调用,则getIntent()为null,则需要初始化自己的new Intent对象。

// current activity in onCreate() method
if(getIntent() == null) {
    Intent intent = new Intent();
    int check = elsewhere.chk_intent(intent);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM