Search code examples
androidandroid-intentandroid-activity

ActivityNotFoundException when opening another activity with Intent


I want to open another Activity from my main Activity with an Intent. This is my main Activity class (MainActivity.java):

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LinearLayout l = new LinearLayout(this);
        Button b = new Button(this);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent goToActivity2 = new Intent(MainActivity.this, Activity2.class);
                MainActivity.this.startActivity(goToActivity2);
            }
        });
        l.addView(b);

        this.setContentView(l);
    }
}

And this is Activity2.java:

public class Activity2 extends Activity {

}

If I run the app I will see the main activity with a gray button. If I click on the button I get an Exception:

android.content.ActivityNotFoundException: Unable to find explicit activity class {com.testing.kaarelp.androidtest2/com.testing.kaarelp.androidtest2.Activity2}; have you declared this activity in your AndroidManifest.xml?

Why am I getting the Exception? Whats wrong here?

------------- edit1 ---------------

okay I declared the other Activity in the manifest like this:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.testing.kaarelp.androidtest2">

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

</manifest>

... and the app works now! Yet I am looking at another working code example right now that has multiple Activity-s that are not declared in the manifest and it still works. What is going on?!

------------- edit2 ---------------

Ahh I figured it out. The code example I was looking at contained multiple Fragment-s, not Activity-s


Solution

  • You must declare the Activity in your AndroidManifest.xml file:

    <activity android:name=".Activity2"/>