I'm developing an Android app for a school project and i have the following problem. I have a MainActivity
with a Button
and a SecondActivity
. When I click on the button in the MainActivity
it have to open the SecondActivity
. I tested it on my two 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 on the button it correctly opens the SecondActivity.
The problem is when i add a controller class and try to start the 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);
}
}
And I change the MainActivity
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 on my zenfone2 crashes when i click on the button. Where is the problem? if it's not correct, why works on s9+?
Thank you