簡體   English   中英

錯誤:無法實例化Android中的活動

[英]Error: unable to instantiate activity in android

我正在按照教程創建帶抽屜導航的滑動導航。

Android Manifest.xml

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

    <uses-sdk
        android:minSdkVersion="7"
        android:targetSdkVersion="22" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.aa.slide.MainActivity"
            android:label="@string/app_name"
            android:theme="@style/Theme.MyCompatTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

下面是我的MainActivity.java

package com.aa.slide;

import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

// Adopted from: https://developer.android.com/training/implementing-navigation/nav-drawer.html
public class MainActivity extends ActionBarActivity {

    private String[] mPlanetTitles;
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private CharSequence mTitle;
    private ActionBarDrawerToggle mDrawerToggle;

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

        mTitle = "test";

        mPlanetTitles = new String[]{"one", "two", "three"};
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        // Set the adapter for the list view
        mDrawerList.setAdapter(new ArrayAdapter<String>(this,
                R.layout.drawer_list_item, mPlanetTitles));
        // Set the list's click listener
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        mDrawerToggle = new ActionBarDrawerToggle(
                this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                R.drawable.ic_drawer,  /* nav drawer icon to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description */
                R.string.drawer_close  /* "close drawer" description */
        ) {

            /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
            }

            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mTitle);
            }
        };

        // Set the drawer toggle as the DrawerListener
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Pass the event to ActionBarDrawerToggle, if it returns
        // true, then it has handled the app icon touch event
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle your other action bar items...

        return super.onOptionsItemSelected(item);
    }

    /**
     * Swaps fragments in the main content view
     */
    private void selectItem(int position) {
        Toast.makeText(this, R.string.app_name, Toast.LENGTH_SHORT).show();

        // Highlight the selected item, update the title, and close the drawer
        mDrawerList.setItemChecked(position, true);
        setTitle(mPlanetTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getSupportActionBar().setTitle(mTitle);
    }

    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView parent, View view, int position, long id) {
            selectItem(position);
        }
    }

}

執行上述代碼后,我一直在日志中收到此錯誤

08-14 13:18:18.632: W/dalvikvm(12483): Unable to resolve superclass of Lcom/aa/slide/MainActivity; (11)
08-14 13:18:18.632: W/dalvikvm(12483): Link of class 'Lcom/aa/slide/MainActivity;' failed
08-14 13:18:18.632: D/AndroidRuntime(12483): Shutting down VM
08-14 13:18:18.632: W/dalvikvm(12483): threadid=1: thread exiting with uncaught exception (group=0x4113c2a0)
08-14 13:18:18.637: E/AndroidRuntime(12483): FATAL EXCEPTION: main
08-14 13:18:18.637: E/AndroidRuntime(12483): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.aa.slide/com.aa.slide.MainActivity}: java.lang.ClassNotFoundException: com.aa.slide.MainActivity
08-14 13:18:18.637: E/AndroidRuntime(12483):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2034)
08-14 13:18:18.637: E/AndroidRuntime(12483):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
08-14 13:18:18.637: E/AndroidRuntime(12483):    at android.app.ActivityThread.access$700(ActivityThread.java:140)
08-14 13:18:18.637: E/AndroidRuntime(12483):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
08-14 13:18:18.637: E/AndroidRuntime(12483):    at android.os.Handler.dispatchMessage(Handler.java:99)
08-14 13:18:18.637: E/AndroidRuntime(12483):    at android.os.Looper.loop(Looper.java:137)
08-14 13:18:18.637: E/AndroidRuntime(12483):    at android.app.ActivityThread.main(ActivityThread.java:4921)
08-14 13:18:18.637: E/AndroidRuntime(12483):    at java.lang.reflect.Method.invokeNative(Native Method)
08-14 13:18:18.637: E/AndroidRuntime(12483):    at java.lang.reflect.Method.invoke(Method.java:511)
08-14 13:18:18.637: E/AndroidRuntime(12483):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
08-14 13:18:18.637: E/AndroidRuntime(12483):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
08-14 13:18:18.637: E/AndroidRuntime(12483):    at dalvik.system.NativeStart.main(Native Method)
08-14 13:18:18.637: E/AndroidRuntime(12483): Caused by: java.lang.ClassNotFoundException: com.aa.slide.MainActivity
08-14 13:18:18.637: E/AndroidRuntime(12483):    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
08-14 13:18:18.637: E/AndroidRuntime(12483):    at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
08-14 13:18:18.637: E/AndroidRuntime(12483):    at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
08-14 13:18:18.637: E/AndroidRuntime(12483):    at android.app.Instrumentation.newActivity(Instrumentation.java:1068)
08-14 13:18:18.637: E/AndroidRuntime(12483):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2025)
08-14 13:18:18.637: E/AndroidRuntime(12483):    ... 11 more

更新這是我的build.gradle

 apply plugin: 'android'

dependencies {

    compile fileTree(dir: 'libs', include: '*.jar')
    compile 'com.Android.support:appcompat-v7:21.0.+'
}

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }

        // Move the tests to tests/java, tests/res, etc...
        instrumentTest.setRoot('tests')

        // Move the build types to build-types/<type>
        // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
        // This moves them out of them default location under src/<type>/... which would
        // conflict with src/ being used by the main source set.
        // Adding new build types or product flavors should be accompanied
        // by a similar customization.
        debug.setRoot('build-types/debug')
        release.setRoot('build-types/release')
    }
}

請問如何解決無法實例化活動的問題? 謝謝

拋出什么異常

java.lang.ClassNotFoundException:com.aa.slide.MainActivity

當類加載器在類路徑中找不到所需的類時,將發生ClassNotFoundException 因此,基本上,您應該檢查您的類路徑並將該類添加到類路徑中。

重建並清理您的項目。請檢查此SO答案。 為您提供信息,自版本22.1.0起,不推薦使用ActionBarActivity類。 您應該使用AppCompatActivityActvity 希望對您有幫助。

確保這在您的gradle文件中:

dependencies {
    compile 'com.android.support:appcompat-v7:21.0.0'
}

問題是dalvikVM無法找到import android.support.v7.app.ActionBarActivity; 這是您MainActivity的超類

您可以在以下位置看到此內容:

08-14 13:18:18.632: W/dalvikvm(12483): Unable to resolve superclass of Lcom/aa/slide/MainActivity; (11)

在清單文件中嘗試以下操作:

 **android:name=".MainActivity"**

 <activity
        android:name="com.aa.slide.MainActivity"
        android:label="@string/app_name"
        android:theme="@style/Theme.MyCompatTheme">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM