java - 如何在不因 NPE 导致设备崩溃的情况下将变量从一个 Activity 传递到另一个 Activity ?

标签 java android

我的代码中有以下内容,但我的应用程序一直崩溃。

主要 Activity :

 new Intent(context, RetrieveInfoActivity.class).putExtra("Interval",  interval);

检索信息 Activity :

Intent intent = new Intent (context, MainActivity.class);
Long intervalAlarm = intent.getExtras().getLong("Interval"); //I keep getting an NPE here. 

我想我可能知道为什么,因为我在 onCreate() 中执行此操作,它试图在设置警报/从 MainActivity 设置间隔之前获取值。我想知道如何才能让它在未设置间隔/不为空时不获取值?

编辑:

我在我的 onCreate() 中有这个,现在它永远不会被调用,即使它应该被调用。我应该在其他地方设置它吗?

 if (getIntent().getExtras()!= null) {

            intervalAlarm = getIntent().getExtras().getLong("Interval");
            System.out.println("Interval: " + intervalAlarm);
        }

编辑:此方法在异步任务的 doInBackground 中调用!

private void setAlarms() {

            AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(context, AlarmReceiver.class);
            pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

            interval = 900000L;

            try {

            .....

                    new Intent(context, RetrieveInfoActivity.class).putExtra("PendingIntent",  pendingIntent);
                    new Intent(context, RetrieveInfoActivity.class).putExtra("Interval",  interval);
                    //Set Alarm to Repeat
                    manager.setRepeating(AlarmManager.RTC_WAKEUP, timeInMilis, interval, pendingIntent);
                     new Intent(context, Time.class);

                //Instantiates the intent to launch a new activity
                Intent myIntent = new Intent(MainActivity.this, RetrieveInfoActivity.class);
                MainActivity.this.startActivity(myIntent);

            }
            catch(ParseException e) {
                e.printStackTrace();
            }
        }

最佳答案

RetrieveInfoActivity 中你应该使用

long intervalAlarm = getIntent().getExtras().getLong("Interval");

代替

Intent intent = new Intent (context, MainActivity.class);
Long intervalAlarm = intent.getExtras().getLong("Interval");

编辑。

在您的代码中,您应该只创建一个 Intent 并用您想要提供给新 Activity 的信息填充它。例如

Intent intent =new Intent(MainActivity.this, RetrieveInfoActivity.class);
intent.putExtra("PendingIntent", pendingIntent);   
intent.putExtra("Interval", interval);  
MainActivity.this.startActivity(intent); 

关于java - 如何在不因 NPE 导致设备崩溃的情况下将变量从一个 Activity 传递到另一个 Activity ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26848262/

相关文章:

android - 模拟器在运行Helloworld程序时停在开机界面

java - 删除android中的路径

android - 当 Activity 回到前台时,AlertDialog 是不可见的

android - 未能加载模块描述符类 : Didn't find class "com.google.android.gms.dynamite.descriptors.com.google.firebase.auth.ModuleDescriptor"

java - 我同时使用两个库来处理照片(glide 和gravityView)

java - 我应该如何使用 Maven 和 Intellij 构建多组件 Java 项目?

java - 日历 setter 不接受我的更改

java - 为什么流行的框架在内部使用字节码操作?

java - 返回数组困惑...谁可以向我解释以下不起作用的代码?

python - 如何使功能可切换?