如何使用 java nullpointerexception 处理 getIntent() 方法 [英] how to handle a getIntent() method with java nullpointerexception

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

问题描述

我的应用程序中有 2 个 Activity,Activity1Activity2.当应用程序启动时,Acitivity1 被调用.单击 Activity1 中的按钮应该你到 Activity2.

I have 2 activities in my application, Activity1 and Activity2.When the app launches Acitivity1 is the the one that is called.Clicking on a button in Activity1 should take you to Activity2.

在 Acivity2 中,完成了一些数据处理,然后我使用这样的意图将数据发送回 Activity1:

In Acivity2,some data processing is done then i send back data to Activity1 using an intent like this:

Intent in=new Intent(getApplicationContext(), Activity1.class);
  in.putExtra("data", data);
    startActivity(in);

然后回到 Activity1 获取意图数据:

Then getting back to Activity1 i obtain the intent data:

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity1);

    String data =(getIntent().getExtras().getString("data"));

这里的问题是应用程序第一次启动时会检查意图数据,但它不存在,所以我得到了 nullpointerexception 错误.当 Activity2 是上一个类时,我如何确保它检查意图数据?

The problem here is that the first time the app launches it checks for the intent data and it does not exist so i get the nullpointerexception error.how can i make sure it checks for the intent data when Activity2 is the previous class?

推荐答案

您可以使用以下方法检查 Intent 是否存在:

You can check if the intent is existing using:

getIntent().hasExtra("data");

这将返回一个布尔值.

另外,如果oyu想返回一些数据给第一个活动,你应该用startActivityForResult

Also if oyu want to return some datas to the first activity, your should start the second one with startActivityForResult

这篇关于如何使用 java nullpointerexception 处理 getIntent() 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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