我在尝试通过 onFinish() 传递意图时收到 NullPointerException。



我试图做的是使用 CountDownTimer 类中的 onFinish() 方法通过意图传递值。意图的流动是这样的。我的MyCountDownTimer Class保存将传递意图/值的方法。它看起来像这样。我评论了NullPointerException的用武之地。这是我的重试活动中的一个片段。

 /*
  *  Retry Activity
  */
@Override
    public void onClick(View v) {
        if (v.getId()== R.id.retry){
            Bundle extras1 = getIntent().getExtras();
            whichTest = extras1.getInt("whichTest"); //NullPointerException

            if (whichTest == 1){
                Intent intent1 = new Intent(Retry.this, Test1.class);
                startActivity(intent1);
            }
            if (whichTest == 2){
                Intent intent1 = new Intent(Retry.this, Test2.class);
                startActivity(intent1);
            }

这是利用该方法的活动。它被称为测试1

/*
  *  Test1 Activity
  */
//Timer
    textCounter = ((TextView)findViewById(R.id.textCounter));

    myCountDownTimer = new MyCountDownTimer(textCounter, 5000, 1000);
    myCountDownTimer.start();
   textCounter.setText("");
    myCountDownTimer.onTick(5000);

}
@Override
public void onClick(View v) {

            if (textCounter==null){
                myCountDownTimer.onFinish();
    }

此代码片段来自 MyCountDownTimer 类

/*
  *  MyCountDownTimer
  */
 @Override
    public void onFinish() {

        Intent retryIntent = new Intent(textCounter.getContext(), Retry.class);
           if (textCounter.getContext().equals(Test1.class)){
               whichTest = 1;
               retryIntent.putExtra("whichTest",whichTest);
           }
        if (textCounter.getContext().equals(Test2.class)){
            whichTest = 2;
            retryIntent.putExtra("whichTest",whichTest);
        }
        textCounter.getContext().startActivity(retryIntent);

}

如果您想查看更完整的版本,请转到此处 https://gist.github.com/asonofman

这是日志猫

03-16 12:32:39.379    4625-4625/com.dose.apps.brainnoodles E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at com.dose.apps.brainnoodles.Retry.onClick(Retry.java:40)
            at android.view.View.performClick(View.java:4475)
            at android.view.View$PerformClick.run(View.java:18796)
            at android.os.Handler.handleCallback(Handler.java:730)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5455)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
            at dalvik.system.NativeStart.main(Native Method)

很可能是这样:

textCounter.getContext().equals(Test1.class)

将永远返回false.您正在寻找的任何机会:

textCounter.getContext() instanceof Test1

在此之后,您的意图将不会添加任何额外内容,因此:

Bundle extras1 = getIntent().getExtras();

extras1将被null

相关内容

最新更新