1

I have an Activity suppose Activity_A which calls Activity_B that Without showing anything goes to Activity_C using startActivityforResult().

These work as expected, user Doesn't see Activity_b and if Activity_c returns the correct return_code Activity_B works according to the code but if the user presses the back button it goes to an empty Activity_B (Since the information is returned from Activity_C) and then to Activity_A what I want is that if Back Button is pressed it goes to Activity_A otherwise work as it is working now. I used Intent to go to Activity_A using the Flag FLAG_ACTIVITY_REORDER_TO_FRONT but then it just moves Activity_B to the next position in Activity List.

There are multiple Activities before Activity_A, so using the Flag to clear top will not help.

I tried making an Activity variable which will call finish(), onBackPressed() but it just returns with an error null pointer

Code on Activity_C

@Override
public void onBackPressed(){
    Intent intent = new Intent(getApplicationContext(),GalleryPreview.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    bg_edit1 abc = new bg_edit1();
    startActivityIfNeeded(intent,0);
    abc.t1.finish();
//  Intent i = new Intent("finish_activity");
//  sendBroadcast(i);
    finish();

}

Code On Activity_B

Using Broadcast Receiver( I think my implementation of broadcast receiver is wrong or it is not working )

BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals("finish_activity")) {
                finish();
            }
        }
    };


registerReceiver(broadcastReceiver, new IntentFilter("finish_activity"));
unregisterReceiver(broadcastReceiver);

error i got when trying Activity/AppCompatActivity method

void androidx.appcompat.app.AppCompatActivity.finish()' on a null object reference 
Akshit Sharma
  • 63
  • 1
  • 1
  • 8

1 Answers1

1

You don't need to finish another Activity. That's the wrong approach. To return directly to A from C when the back button is pressed, do this in C:

@Override
public void onBackPressed(){
    Intent intent = new Intent(this,GalleryPreview.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                    Intent.FLAG_ACTIVITY_SINGLE_TOP);
    startActivity(intent);
}

By adding CLEAR_TOP flag will automatically remove activity B from the stack. By adding SINGLE_TOP flag ensures that the existing instance of A will be used, and not a new instance of A.

You also do not need the BroadcastReceiver in activity B.

David Wasser
  • 93,459
  • 16
  • 209
  • 274