Java – startActivity in java class crashes

startActivity in java class crashes… here is a solution to the problem.

startActivity in java class crashes

I

was developing an Android app for a school project and I ran into the following issue. I have a MainActivity with a Button and a SecondActivity. When I click the button in MainActivity, it has to open SecondActivity. I tested it on two of my devices (Samsung Galaxy S9+ and Asus Zenfone2) :

MainActivity.java

public class MainActivity extends AppCompatActivity {
    Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button=(Button)findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(MainActivity.this,SecondActivity.class)
                startActivity(intent);
            }
        });
}
}

This works fine on both devices, and when I click the button, it opens SecondActivity correctly.

The problem is when I add a Controller class and try to start SecondActivity in it. This is the Controller class:

Controller.java

public class Controller {
    public void open(Context cont){
        Intent intent=new Intent(cont,SecondActivity.class);
        cont.getApplicationContext().startActivity(intent);
     }
  }

Then I changed MainActivity: in this way

public class MainActivity extends AppCompatActivity {
    Button button;
    Controller c;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button=(Button)findViewById(R.id.button2);
        c=new Controller();

button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                c.open(getApplicationContext());
            }
        });
}
}

This works fine on my s9+ while crashing when clicking the button on my zenfone2. What’s the problem? If not, why does it work with s9+?

Thanks

Solution

Starting with Android P, you can’t start an activity using the application context unless you add the Intent.FLAG_ACTIVITY_NEW_TASK flag. Therefore, simply change your Controller and mainactivity to use the mainactivity context instead.

c.open(MainActivity.this);

public void open(Context context) {
    Intent intent = new Intent(context, SecondActivity.class);
    context.startActivity(intent);
}

Or

public void open(Context context) {
    Intent intent = new Intent(context.getApplicationContext(), SecondActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
}

Related Problems and Solutions