简体   繁体   中英

Error: unable to instantiate activity in android

I am following a tutorial to creating a sliding navigation with a drawer navigation.

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>

Below is my 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);
        }
    }

}

Upon Executing the above codes, I keep recieving this error in my log

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

UPDATE this is my 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')
    }
}

Please how can i solve this problem of unable to instantiate activity? Thanks

What exceptions throws

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

ClassNotFoundException occurs when class loader could not find the required class in class path . So , basically you should check your class path and add the class in the classpath.

Rebuild and Clean up your Project.Please check This SO Answer. For your information,Since the version 22.1.0, the class ActionBarActivity is deprecated. You should use AppCompatActivity or Actvity . I hope it helps you .

Be sure that this is in your gradle file:

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

The problem is that the dalvikVM can't find import android.support.v7.app.ActionBarActivity; which is the superclass of your MainActivity

You can see this in:

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

Try this in Manifest file:

 **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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM