bonzo bonzo -4 years ago 141
Android Question

Android Intent Switching Crashes onClick

I'm fairly confused with this one. In my MainActivity.java I have a button that's supposed to go over to another class in another file

RedGreenTest.java


redButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
findViewById(R.id.testRG_button);
Intent i = new Intent(MainActivity.this, RedGreenTest.class);
startActivity(i);
}
});


So the button gets clicked, and bam insta-crash. Debugger tells me that it's
startActivity(i);
no dua. Going into the manifest, I change my
<activity android:name=".MainActivity">
to
<activity android:name=".RedGreenTest">
and the app starts up just fine.

Here is the beginning of my onCreate() class from the
MainActivity.java
file:

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


And my onCreate() in my
RedGreenTest.java
:

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


Running this through the debugger, I'm not getting any errors when the
RedGreenTest.java
file is set in the Manifest.

What fundamental am I just missing from this what-should-be simple intent switch?

Answer Source

You need to have both activities added to the manifest:

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

The reason that the app starts when you change MainActivity to RedGreenTest, is because you are setting the RedGreenTest activity to be the launch activity, which is set by the intent filter.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download