GVKun编程网logo

android – 获取java.lang.RuntimeException:通过Maven运行Robolectric时存根(获取maven项目根路径)

26

对于android–获取java.lang.RuntimeException:通过Maven运行Robolectric时存根感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解获取maven项目

对于android – 获取java.lang.RuntimeException:通过Maven运行Robolectric时存根感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解获取maven项目根路径,并且为您提供关于Android FATAL EXCEPTION MAIN:java.lang.RuntimeException:无法启动活动ComponentInfo、Android java.lang.RuntimeException:无法实例化活动ComponentInfo … java.lang.NullPointerException、Android Robolectric – ContentProvider中queryBuilder.query()中的RuntimeException / InstantiationException、android – java.lang.RuntimeException无法实例化服务:java.lang.NullPointerException的宝贵知识。

本文目录一览:

android – 获取java.lang.RuntimeException:通过Maven运行Robolectric时存根(获取maven项目根路径)

android – 获取java.lang.RuntimeException:通过Maven运行Robolectric时存根(获取maven项目根路径)

好吧,我有一个奇怪的错误.当我通过IntelliJ运行我的测试时,它没有任何问题.但是如果我使用sure-fire插件或’mvn clean test’命令运行它,我会得到以下异常:
shouldLoadMoreDataOnScrollBeyondTheThreshold(br.com.cybereagle.androidwidgets.listener.endlessscrollListenerTest)  Time elapsed: 2.73 sec  <<< ERROR!
java.lang.RuntimeException: Stub!
    at junit.framework.Assert.assertTrue(Assert.java:6)
    at br.com.cybereagle.androidwidgets.listener.endlessscrollListenerTest.shouldLoadMoreDataOnScrollBeyondTheThreshold(endlessscrollListenerTest.java:36)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:616)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
    at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:246)
    at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
    at org.junit.runners.BlockJUnit4ClassRunner.runchild(BlockJUnit4ClassRunner.java:71)
    at org.junit.runners.BlockJUnit4ClassRunner.runchild(BlockJUnit4ClassRunner.java:49)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runchildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:181)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:59)
    at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:120)
    at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:103)
    at org.apache.maven.surefire.Surefire.run(Surefire.java:169)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:616)
    at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:350)
    at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1021)

这是我的测试:

@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class endlessscrollListenerTest {

    private ListView listView;
    private endlessscrollListener endlessscrollListener;

    @Before
    public void setUp() throws Exception {
        listView = mock(ListView.class);

        when(listView.getHeaderViewsCount()).thenReturn(0);
        when(listView.getFooterViewsCount()).thenReturn(0);


        endlessscrollListener = spy(new TestendlessscrollListener(5));
    }

    @Test
    public void shouldLoadMoreDataOnScrollBeyondTheThreshold() {
        doReturn(true).when(endlessscrollListener).hasMoreDataToLoad();

        assertTrue(endlessscrollListener.isLoading());

        endlessscrollListener.onScroll(listView,2,5,20);

        assertFalse(endlessscrollListener.isLoading());

        endlessscrollListener.onScroll(listView,15,20);

        assertTrue(endlessscrollListener.isLoading());


        endlessscrollListener.onScroll(listView,21,40);

        assertFalse(endlessscrollListener.isLoading());

        endlessscrollListener.onScroll(listView,35,40);

        assertTrue(endlessscrollListener.isLoading());

        endlessscrollListener.onScroll(listView,38,60);

        assertFalse(endlessscrollListener.isLoading());

        doReturn(false).when(endlessscrollListener).hasMoreDataToLoad();

        endlessscrollListener.onScroll(listView,55,60);

        assertFalse(endlessscrollListener.isLoading());


        verify(endlessscrollListener,atMost(6)).hasMoreDataToLoad();
        verify(endlessscrollListener,times(1)).loadMoreData(1);
        verify(endlessscrollListener,times(1)).loadMoreData(2);
        verify(endlessscrollListener,never()).loadMoreData(3);
    }

    private static class TestendlessscrollListener extends endlessscrollListener {

        private TestendlessscrollListener(int visibleThreshold) {
            super(visibleThreshold);
        }

        @Override
        protected boolean hasMoreDataToLoad() {
            return false;
        }

        @Override
        protected void loadMoreData(int page) {

        }
    }
}

错误发生在第一个assertTrue中:

assertTrue(endlessscrollListener.isLoading());

最奇怪的是,根据stacktrace,它发生在assertTrue方法中.

这些是我的maven依赖项:

<dependencies>
    <dependency>
        <groupId>android</groupId>
        <artifactId>android</artifactId>
        <version>${android.version}</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>com.google.android</groupId>
        <artifactId>support-v4</artifactId>
        <version>${support.v4.version}</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>com.google.android</groupId>
        <artifactId>support-v7-appcompat</artifactId>
        <version>${support.v7.version}</version>
        <scope>provided</scope>
        <type>jar</type>
    </dependency>

    <dependency>
        <groupId>org.robolectric</groupId>
        <artifactId>robolectric</artifactId>
        <version>${robolectric.version}</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-core</artifactId>
        <version>1.2</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.8.2</version>
        <scope>test</scope>
    </dependency>
</dependencies>

正如我所说,它在IntelliJ内部工作.

另一个细节是我有另一个项目生成一个JAR,通常使用来自IntelliJ和Maven的Robolectric.

知道发生了什么事吗?

解决方法

好吧,我的问题是我从错误的包导入:
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;

我改成了:

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

现在它按预期工作了.我不知道为什么它在IntelliJ中工作.

Android FATAL EXCEPTION MAIN:java.lang.RuntimeException:无法启动活动ComponentInfo

Android FATAL EXCEPTION MAIN:java.lang.RuntimeException:无法启动活动ComponentInfo

我是编程android的nubie,我知道这里有4m是很多页面为我的问题打乱解决方案,但现在我输了2天仍然没有得到解决方案.请帮我!

首先是我的错误:

01-02 11:08:27.314: D/AndroidRuntime(1045): Shutting down VM
01-02 11:08:27.314: W/dalvikvm(1045): threadid=1: thread exiting with uncaught exception (group=0x409e61f8)
01-02 11:08:27.324: E/AndroidRuntime(1045): FATAL EXCEPTION: main
01-02 11:08:27.324: E/AndroidRuntime(1045): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.wifiscan/com.example.wifiscan.activity_wifi_scan}: java.lang.classNotFoundException: com.example.wifiscan.activity_wifi_scan
01-02 11:08:27.324: E/AndroidRuntime(1045):     at android.app.ActivityThread.performlaunchActivity(ActivityThread.java:1880)
01-02 11:08:27.324: E/AndroidRuntime(1045):     at  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
01-02 11:08:27.324: E/AndroidRuntime(1045):     at android.app.ActivityThread.access$600(ActivityThread.java:123)
01-02 11:08:27.324: E/AndroidRuntime(1045):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
01-02 11:08:27.324: E/AndroidRuntime(1045):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-02 11:08:27.324: E/AndroidRuntime(1045):     at android.os.Looper.loop(Looper.java:137)
01-02 11:08:27.324: E/AndroidRuntime(1045):     at android.app.ActivityThread.main(ActivityThread.java:4424)
01-02 11:08:27.324: E/AndroidRuntime(1045):     at java.lang.reflect.Method.invokeNative(Native Method)
01-02 11:08:27.324: E/AndroidRuntime(1045):     at java.lang.reflect.Method.invoke(Method.java:511)
01-02 11:08:27.324: E/AndroidRuntime(1045):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-02 11:08:27.324: E/AndroidRuntime(1045):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-02 11:08:27.324: E/AndroidRuntime(1045):     at dalvik.system.NativeStart.main(Native Method)
01-02 11:08:27.324: E/AndroidRuntime(1045): Caused by: java.lang.classNotFoundException: com.example.wifiscan.activity_wifi_scan
01-02 11:08:27.324: E/AndroidRuntime(1045):     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
01-02 11:08:27.324: E/AndroidRuntime(1045):     at java.lang.classLoader.loadClass(ClassLoader.java:501)
01-02 11:08:27.324: E/AndroidRuntime(1045):     at java.lang.classLoader.loadClass(ClassLoader.java:461)
01-02 11:08:27.324: E/AndroidRuntime(1045):     at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
01-02 11:08:27.324: E/AndroidRuntime(1045):     at android.app.ActivityThread.performlaunchActivity(ActivityThread.java:1871)
01-02 11:08:27.324: E/AndroidRuntime(1045):     ... 11 more

我的WifiScan:

 public class WifiScan extends Activity implements OnClickListener {      
     WifiManager wifi;       
     ListView lv;
     TextView textStatus;
     Button buttonScan;
     int size = 0;
     List<ScanResult> results;

     String ITEM_KEY = "key";
     ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
     SimpleAdapter adapter;

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

         buttonScan = (Button) findViewById(R.id.scan);
         buttonScan.setonClickListener(this);
         lv = (ListView)findViewById(R.id.list);

         wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
         if (wifi.isWifiEnabled() == false)
         {
             Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
             wifi.setWifiEnabled(true);
         }   
         wifi.startScan(); //js dopisal
      //   this.adapter = new SimpleAdapter(WiFiDemo.this, arraylist, R.layout.row, new String[] { ITEM_KEY }, new int[] { R.id.list_value });
         lv.setAdapter(this.adapter);

              registerReceiver(new broadcastReceiver()
         {
             @Override
             public void onReceive(Context c, Intent intent) 
             {
                results = wifi.getScanResults();
                size = results.size();
             }
         }, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));                    
     }

     public void onClick(View view) 
     {
         arraylist.clear();          
         wifi.startScan();

              Toast.makeText(this, "Scanning...." + size, Toast.LENGTH_SHORT).show();
         try 
         {
             size = size - 1;
             while (size >= 0) 
             {   
                 HashMap<String, String> item = new HashMap<String, String>();                       
                 item.put(ITEM_KEY, results.get(size).SSID + "  " + results.get(size).capabilities);

                 arraylist.add(item);     
                size--;
                 adapter.notifyDataSetChanged();                 
             } 
         }
         catch (Exception e)
         { }         
     }    
 }

我的activity_wifi_scan.xml文件:

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/TableLayout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context=".WifiScan" >

    <Button    
        android:id="@+id/scan"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="scan"
        android:text="SCAN" />

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</TableLayout>

和我的AndroidManifest文件:

<?xml version="1.0" encoding="utf-8"?>
      <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.example.wifiscan"
     android:versionCode="1"
          android:versionName="1.0" >

        <uses-premission android:name="android.permission.ACCESS_WIFI_STATE"/>
         <uses-permission android:name="android.permission.WAKE_LOCK"/>
        <uses-permission android:name="android.permission.INTERNET"/>
     <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
     <uses-permission android:name="android.permission.INTERNET"></uses-permission>
     <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
     <uses-permission android:name="android.permission.READ_PHONE_STATE"> </uses-permission>
     <uses-permission android:name="android.permission.INTERNET"> </uses-permission>

     <uses-sdk
          android:minSdkVersion="8"
         android:targetSdkVersion="17" />

     <application
         android:allowBackup="true"
         android:icon="@drawable/ic_launcher"
         android:label="@string/app_name"
         android:theme="@style/AppTheme" >

     <activity android:name=".activity_wifi_scan">
         <intent-filter>
                 <action android:name="android.intent.action.MAIN"></action>
                 <category android:name="android.intent.category.LAUNCHER"></category>
                 <data />
         </intent-filter>
     </activity>

     <receiver android:name=".activity_wifi_scan">
         <intent-filter>
             <action android:name="android.intent.action.MAIN" />
             <category android:name="android.intent.category.LAUNCHER"/>
            <action android:name="android.net.wifi.WIFI_STATE_CHANGED"/>
         </intent-filter>
     </receiver>        
     </application>
 </manifest>

解决方法:

您的活动名称是WifiScan但您已将其声明为.activity_wifi_scan更改它并重试.

更改<活动>要素:

<activity android:name=".WifiScan">
         <intent-filter>
                 <action android:name="android.intent.action.MAIN"></action>
                 <category android:name="android.intent.category.LAUNCHER"></category>
                 <data />
         </intent-filter>
     </activity>

Android java.lang.RuntimeException:无法实例化活动ComponentInfo … java.lang.NullPointerException

Android java.lang.RuntimeException:无法实例化活动ComponentInfo … java.lang.NullPointerException

出于某种原因,每次尝试启动我的应用程序时,我都会出现以下错误:

Unable to instantiate activity ComponentInfo{com.example.lifeahead/com.example.lifeahead.MainActivity}:java.lang.NullPointerException

我检查了清单文件,并添加了所有活动.

我启动应用程序时使用的唯一方法是:

private void logIn(){
    Button logIn = (Button) findViewById(R.id.login);
    logIn.setonClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // Todo Auto-generated method stub
            Intent loginIntent = new Intent(MainActivity.this, HomeActivity.class);
            loginIntent.putExtra("cmUN", cmUN);
            loginIntent.putExtra("cmPW", cmPW);
            startActivity(loginIntent);
        }
    });
}

这是onCreate:

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

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }

    logIn();
}

完整日志:

Ë

/AndroidRuntime(1607): FATAL EXCEPTION: main
E/AndroidRuntime(1607): Process: com.example.lifeahead, PID: 1607
E/AndroidRuntime(1607): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.lifeahead/com.example.lifeahead.MainActivity}: java.lang.NullPointerException
E/AndroidRuntime(1607):     at android.app.ActivityThread.performlaunchActivity(ActivityThread.java:2121)
E/AndroidRuntime(1607):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
E/AndroidRuntime(1607):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
E/AndroidRuntime(1607):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
E/AndroidRuntime(1607):     at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime(1607):     at android.os.Looper.loop(Looper.java:136)
E/AndroidRuntime(1607):     at android.app.ActivityThread.main(ActivityThread.java:5017)
E/AndroidRuntime(1607):     at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(1607):     at java.lang.reflect.Method.invoke(Method.java:515)
E/AndroidRuntime(1607):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
E/AndroidRuntime(1607):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
E/AndroidRuntime(1607):     at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(1607): Caused by: java.lang.NullPointerException
E/AndroidRuntime(1607):     at android.app.Activity.findViewById(Activity.java:1884)
E/AndroidRuntime(1607):     at com.example.lifeahead.MainActivity.<init>(MainActivity.java:22)
E/AndroidRuntime(1607):     at java.lang.class.newInstanceImpl(Native Method)
E/AndroidRuntime(1607):     at java.lang.class.newInstance(Class.java:1208)
E/AndroidRuntime(1607):     at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
E/AndroidRuntime(1607):     at android.app.ActivityThread.performlaunchActivity(ActivityThread.java:2112)
E/AndroidRuntime(1607):     ... 11 more

我感谢所有帮助!

解决方法:

stacktrace告诉你

  Button logIn = (Button) findViewById(R.id.login);

findViewById返回的对象为null,因为您拥有的唯一方法是logIn(). findViewById返回null的唯一原因是因为您正在查找不属于当前活动的视图层次结构的视图

Android Robolectric – ContentProvider中queryBuilder.query()中的RuntimeException / InstantiationException

Android Robolectric – ContentProvider中queryBuilder.query()中的RuntimeException / InstantiationException

我在ContentProvider上进行了大约十次测试,只使用了sqlite; all pass保存在Content Provider的query()方法中通过queryBuilder.query()的两个.

正在测试的方法在实际应用中起作用!

这是API 17 r2和RoboLectric:
robolectric-2.0-α-3-20130417.013705-46-罐与 – dependencies.jar

@Override
public Cursor query(Uri uri,String[] projection,String selection,String[] selectionArgs,String sortOrder) {
    Log.d(Constants.TAG,"MyContentProvider.query()");
    switch(matcher.match(uri)) {
    case ITEM: // OK
        selection = "_id = ?";
        selectionArgs = new String[]{ Long.toString(ContentUris.parseId(uri)) };
    case ITEMS: // OK
        break;
    default:
        throw new IllegalArgumentException("Did not recognize URI " + uri);
    }
    // build the query with sqliteQueryBuilder
    sqliteQueryBuilder qBuilder = new sqliteQueryBuilder();
    qBuilder.setTables(TABLE_NAME);

    // query the database and get result in cursor
    final sqliteDatabase db = mDatabase.getReadableDatabase();
    Cursor resultCursor = qBuilder.query(db,// Line 112 in trace
            projection,selection,selectionArgs,null,sortOrder,null);
    resultCursor.setNotificationUri(getContext().getContentResolver(),uri);
    return resultCursor;
}

这是追溯:

java.lang.RuntimeException: java.lang.InstantiationException
    at org.robolectric.bytecode.ShadowWrangler.createShadowFor(ShadowWrangler.java:300)
    at org.robolectric.bytecode.ShadowWrangler.initializing(ShadowWrangler.java:74)
    at org.robolectric.bytecode.RobolectricInternals.initializing(RobolectricInternals.java:90)
    at android.database.sqlite.sqliteQuery.$$robo$init(sqliteQuery.java)
    at android.database.sqlite.sqliteClosable.<init>(sqliteClosable.java:26)
    at android.database.sqlite.sqliteProgram.<init>(sqliteProgram.java:41)
    at android.database.sqlite.sqliteQuery.<init>(sqliteQuery.java:37)
    at android.database.sqlite.sqliteDirectCursorDriver.query(sqliteDirectCursorDriver.java:44)
    at android.database.sqlite.sqliteDatabase.rawQueryWithFactory(sqliteDatabase.java:1314)
    at android.database.sqlite.sqliteQueryBuilder.query(sqliteQueryBuilder.java:400)
    at android.database.sqlite.sqliteQueryBuilder.query(sqliteQueryBuilder.java:333)
    at com.example.readingsprovider.ReadingsContentProvider.query(ReadingsContentProvider.java:112)
    at com.example.readingsprovider.test.ContentProviderTest.testUpdateMultipleWithoutWhere(ContentProviderTest.java:110)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:267)
    at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
    at org.junit.runners.BlockJUnit4ClassRunner.runchild(BlockJUnit4ClassRunner.java:71)
    at org.junit.runners.BlockJUnit4ClassRunner.runchild(BlockJUnit4ClassRunner.java:49)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runchildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:202)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.InstantiationException
    at sun.reflect.InstantiationExceptionConstructorAccessorImpl.newInstance(InstantiationExceptionConstructorAccessorImpl.java:30)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at java.lang.class.newInstance0(Class.java:357)
    at java.lang.class.newInstance(Class.java:310)
    at org.robolectric.bytecode.ShadowWrangler.createShadowFor(ShadowWrangler.java:293)
    at org.robolectric.bytecode.ShadowWrangler.initializing(ShadowWrangler.java:74)
    at org.robolectric.bytecode.RobolectricInternals.initializing(RobolectricInternals.java:90)
    at android.database.sqlite.sqliteQuery.$$robo$init(sqliteQuery.java)
    at android.database.sqlite.sqliteClosable.<init>(sqliteClosable.java:26)
    at android.database.sqlite.sqliteProgram.<init>(sqliteProgram.java:41)
    at android.database.sqlite.sqliteQuery.<init>(sqliteQuery.java:37)
    at android.database.sqlite.sqliteDirectCursorDriver.$$robo$$sqliteDirectCursorDriver_7ac1_query(sqliteDirectCursorDriver.java:44)
    at android.database.sqlite.sqliteDirectCursorDriver.query(sqliteDirectCursorDriver.java)
    at android.database.sqlite.sqliteDatabase.$$robo$$sqliteDatabase_ab15_rawQueryWithFactory(sqliteDatabase.java:1314)
    at android.database.sqlite.sqliteDatabase.rawQueryWithFactory(sqliteDatabase.java)
    at android.database.sqlite.sqliteQueryBuilder.$$robo$$sqliteQueryBuilder_ba4d_query(sqliteQueryBuilder.java:400)
    at android.database.sqlite.sqliteQueryBuilder.query(sqliteQueryBuilder.java)
    at android.database.sqlite.sqliteQueryBuilder.$$robo$$sqliteQueryBuilder_ba4d_query(sqliteQueryBuilder.java:333)
    at android.database.sqlite.sqliteQueryBuilder.query(sqliteQueryBuilder.java)
    at com.example.readingsprovider.ReadingsContentProvider.query(ReadingsContentProvider.java:112)
    at com.example.readingsprovider.test.ContentProviderTest.testUpdateMultipleWithoutWhere(ContentProviderTest.java:110)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    ... 21 more

可以告诉我这是否是Robolectric的限制,还是我的不好?非常感谢!

附:如果Reflection API将失败的类名放在InstantiationException消息中,难道不是梦幻般的吗?

解决方法

我的项目有同样的问题,终于能够用一些谷歌搜索和U Avalos的前一个答案来解决它

1.创建自定义sqliteShadow

@Implements(value = sqliteDatabase.class,inheritImplementationMethods = true)
public class CustomsqliteShadow extends ShadowsqliteDatabase {

    @Implementation
    public Cursor rawQueryWithFactory (sqliteDatabase.CursorFactory cursorFactory,String sql,String editTable,CancellationSignal cancellationSignal) {
      return rawQueryWithFactory(cursorFactory,sql,editTable);
    }
}

2.将@Config注释添加到测试中

要使用自定义阴影类,可以在robolectric2中使用@Config注释

@RunWith(RobolectricTestRunner.class)
@Config( shadows = {CustomsqliteShadow.class})
public class ContentProviderTest {

参考

http://robolectric.blogspot.co.at/2013/05/configuring-robolectric-20.html

android – java.lang.RuntimeException无法实例化服务:java.lang.NullPointerException

android – java.lang.RuntimeException无法实例化服务:java.lang.NullPointerException

我试图创建一个启动服务的活动(在新线程中).它包含一个带有两个editText和一个名为Send的按钮的布局.关键是当我执行MainActivity时,它会抛出:
06-15 22:32:13.312: E/AndroidRuntime(643): FATAL EXCEPTION: main
06-15 22:32:13.312: E/AndroidRuntime(643): java.lang.RuntimeException: Unable to instantiate service hikoki.services.NotificationsService: java.lang.NullPointerException
06-15 22:32:13.312: E/AndroidRuntime(643):  at android.app.ActivityThread.handleCreateService(ActivityThread.java:2237)
06-15 22:32:13.312: E/AndroidRuntime(643):  at android.app.ActivityThread.access$1600(ActivityThread.java:123)
06-15 22:32:13.312: E/AndroidRuntime(643):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1201)
06-15 22:32:13.312: E/AndroidRuntime(643):  at android.os.Handler.dispatchMessage(Handler.java:99)
06-15 22:32:13.312: E/AndroidRuntime(643):  at android.os.Looper.loop(Looper.java:137)
06-15 22:32:13.312: E/AndroidRuntime(643):  at android.app.ActivityThread.main(ActivityThread.java:4424)
06-15 22:32:13.312: E/AndroidRuntime(643):  at java.lang.reflect.Method.invokeNative(Native Method)
06-15 22:32:13.312: E/AndroidRuntime(643):  at java.lang.reflect.Method.invoke(Method.java:511)
06-15 22:32:13.312: E/AndroidRuntime(643):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
06-15 22:32:13.312: E/AndroidRuntime(643):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
06-15 22:32:13.312: E/AndroidRuntime(643):  at dalvik.system.NativeStart.main(Native Method)
06-15 22:32:13.312: E/AndroidRuntime(643): Caused by: java.lang.NullPointerException
06-15 22:32:13.312: E/AndroidRuntime(643):  at android.content.Contextwrapper.getSystemService(Contextwrapper.java:386)
06-15 22:32:13.312: E/AndroidRuntime(643):  at hikoki.services.NotificationsService.<init>(NotificationsService.java:35)
06-15 22:32:13.312: E/AndroidRuntime(643):  at java.lang.class.newInstanceImpl(Native Method)
06-15 22:32:13.312: E/AndroidRuntime(643):  at java.lang.class.newInstance(Class.java:1319)
06-15 22:32:13.312: E/AndroidRuntime(643):  at android.app.ActivityThread.handleCreateService(ActivityThread.java:2234)
06-15 22:32:13.312: E/AndroidRuntime(643):  ... 10 more

主要活动的代码是这样的:

public class MainActivity extends Activity {
    private String TAG = getClass().getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Thread t= new Thread(){
            public void run(){
                Intent intent=new Intent(getContext(),NotificationsService.class);
                //Intent intent=new Intent("hikoki.services.NotificationsService");
                Log.d(TAG,"sending notificationsService");
                startService(intent);
            }
        };
        t.start();
    }

    protected Context getContext() {    
        return this;
    }
}

NotificationsService代码在这里:

public class NotificationsService extends IntentService{
    private static  int TIME_INTERVAL_MILIS=5000;
    private static final int REFRESH=10;
    private  notificationmanager noteManager;
    private static List<FlightStatusNote> flights= new ArrayList<FlightStatusNote>();

    public NotificationsService(){
        super("NotificationsService"); 
        noteManager= notificationmanager)getSystemService(Context.NOTIFICATION_SERVICE)
    }
}

AndroidManifest是这样的:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="hikoki.services"
    android:versionCode="1"
    android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="15"
    android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="hikoki.services.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <service android:name=".FlightStatusService"></service>
    <service android:enabled="true" android:name=".NotificationsService"></service>
</application>

</manifest>

解决方法

您不能从初始化程序(如您原来的那样)或构造函数(就像您现在一样)调用getSystemService().请覆盖onCreate(),并在那里调用getSystemService().

基本上,直到调用onCreate()(或者更准确地说,直到你从onCreate()调用super.onCreate()之后),服务上的继承方法还没有准备好供您使用.

今天关于android – 获取java.lang.RuntimeException:通过Maven运行Robolectric时存根获取maven项目根路径的分享就到这里,希望大家有所收获,若想了解更多关于Android FATAL EXCEPTION MAIN:java.lang.RuntimeException:无法启动活动ComponentInfo、Android java.lang.RuntimeException:无法实例化活动ComponentInfo … java.lang.NullPointerException、Android Robolectric – ContentProvider中queryBuilder.query()中的RuntimeException / InstantiationException、android – java.lang.RuntimeException无法实例化服务:java.lang.NullPointerException等相关知识,可以在本站进行查询。

本文标签: