在getActivity()Android中解析NullPointerException

时间:2014-04-02 16:52:33

标签: java android eclipse junit nullpointerexception

我正在尝试通过Eclipse为我的Android应用程序运行JUnit测试,但我一直在获取NullPointerExceptions,因为getActivity()返回null。

我该如何解决这个问题?这是我的班级:

package app.test.views;

import net.app.R;
import app.views.AddUserActivity;
import app.views.CategoryActivity;
import android.content.Intent;
import android.test.ActivityUnitTestCase;
import android.widget.EditText;

public class AddUserActivityTest2 extends ActivityUnitTestCase<AddUserActivity> {
    private Intent startIntent;

    public AddUserActivity myActivity;
    private EditText usernameBox;

    public AddUserActivityTest2() {
    super(AddUserActivity.class);
    }

    @Override
public void setUp() throws Exception {
        super.setUp();
        myActivity = getActivity();
        usernameBox = (EditText) myActivity.findViewById(R.id.inputUsername);
        startIntent = new Intent(Intent.ACTION_MAIN);
    }

    public void testCat0() { assertTrue(0==0); }
}

这是我在JUnit测试中收到的错误。

java.lang.NullPointerException
at app.test.views.AddUserActivityTest2.setUp(AddUserActivityTest2.java:37)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:554)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1701)

以下是logcat的重要部分:

----- begin exception -----
04-02 13:15:36.845: I/TestRunner(2091): java.lang.NullPointerException
04-02 13:15:36.845: I/TestRunner(2091):     at app.test.views.AddUserActivityTest2.setUp(AddUserActivityTest2.java:37)
04-02 13:15:36.845: I/TestRunner(2091):     at junit.framework.TestCase.runBare(TestCase.java:132)
04-02 13:15:36.845: I/TestRunner(2091):     at junit.framework.TestResult$1.protect(TestResult.java:115)
04-02 13:15:36.845: I/TestRunner(2091):     at junit.framework.TestResult.runProtected(TestResult.java:133)
04-02 13:15:36.845: I/TestRunner(2091):     at junit.framework.TestResult.run(TestResult.java:118)
04-02 13:15:36.845: I/TestRunner(2091):     at junit.framework.TestCase.run(TestCase.java:124)
04-02 13:15:36.845: I/TestRunner(2091):     at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191)
04-02 13:15:36.845: I/TestRunner(2091):     at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176)
04-02 13:15:36.845: I/TestRunner(2091):     at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:554)
04-02 13:15:36.845: I/TestRunner(2091):     at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1701)
04-02 13:15:36.845: I/TestRunner(2091): ----- end exception -----

1 个答案:

答案 0 :(得分:2)

在执行startActivity(new Intent(), null, null);之前尝试运行getActivity(),以便创建活动。