Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't android intent work the first time?

I have an android app with two activites, MainActivity is the start screen of the app which has a button which starts an intent to go to CameraActivity, the code to do this is:

startButton = findViewById(R.id.button_start);
startButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent i = new Intent(getApplicationContext(), CameraActivity.class);
        startActivity(i);
    }
});

However when I start the app and begin on MainActivity and click on startButton, the app sends me directly back to MainActivity again. After this, on the second attempt of clicking startButton on the re-created MainActivity, I am redirected to CameraActivity.

In the logs, I can see that, on the first click of startButton, it attempts to open CameraActivity but falls back to MainActivity and on the second attempt, it opens CameraActivity successfully.

The logs for the first attempt of clicking startButton is here and the second attempt is here.

like image 892
kabeersvohra Avatar asked Nov 18 '25 04:11

kabeersvohra


2 Answers

Maybe you have some problems with second activity which is CameraActivity.java? Maybe that's why it is opens only after second try (after crash or smth.). Add after startActivity(i); method call finish(); and look what will happen. Double check your CameraActivity.java and Manifest.xml

Also why do you use getApplicationContext() in new Intent(getApplicationContext(), ...);? If you are call it in Activity you should use ActivityName.this

like image 148
ardiien Avatar answered Nov 19 '25 19:11

ardiien


Considering startButton in your MainActivity, try putting 'MainActivity.this' instead of 'getApplicationContext()'

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

Secondly, make sure there is no extra intents in CameraActivity class which is redirecting you to main activity. Kindly remove them if any and finish the CameraActivity class instead using following code,

someBackButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        CameraActivity.this.finish();
    }
});
like image 29
Sushant Avatar answered Nov 19 '25 20:11

Sushant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!