Deleting back stack of activities - java

I have 3 activities: A->B->C
The user starts from activity A. When going to B he can press back and return to A.
But... When user goes to C from B. I wish that A and B will be removed and user will exit the app when clicking back.
I tried:
Intent intent = new Intent(B.this, C.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
but on back it still goes to B. If doing so:
Intent intent = new Intent(VerifyPhoneActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
The user goes back to A, so.. It is not what I need.

Override onBackPressed() in Activity C
#Override
public void onBackPressed() {
finishAffinity();
}
This will cause all Activitys running in the same task to finish. If the user starts the app again by tapping on it in the recent tasks window, Activity A will be shown.

100% working.
try to start Activity C like this.
Intent intent = new Intent(this,ActivityC.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity();

Start B activity with startActivityForResult():
Intent intent = new Intent(A.this, B.class);
startActivityForResult(intent, 100);
and override in class A startActivityForResult():
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 100) {
if (resultCode == 1) {
finish();
}
}
}
Now in B class set the result to be sent back to activity A:
Intent intent = new Intent(VerifyPhoneActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
setResult(1);
finish();

If I understood you right, You could achieve this is using SharedPreferences:
In Your Activity A add this:
public class ActivityA extends AppCompatActivity {
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
if (savedInstanceState == null){
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putBoolean("CloseApp", false);
editor.commit();
}
}
#Override
protected void onResume() {
super.onResume();
boolean finish = prefs.getBoolean("CloseApp", false);
if (finish){
this.finish();
}
}
In Activity B:
public class ActivityB extends AppCompatActivity {
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
}
#Override
protected void onResume() {
super.onResume();
boolean finish = prefs.getBoolean("CloseApp", false);
if (finish){
this.finish();
}
}
And Activity C:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putBoolean("CloseApp", true);
editor.commit();
}
#Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
}
That should work.

you can just write this in Activity C if your application work from JELLY_BEAN to up .
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onBackPressed() {
super.onBackPressed();
finishAffinity();
}
if your app work under JELLY_BEAN you can use this solution :
Activity C :
#Override
public void onBackPressed() {
Intent i = new Intent(C.this,A.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra("BackFromC",true);
startActivity(i);
super.onBackPressed();
}
Activity A in onCreate :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
if(getIntent() != null){
if(getIntent().getBooleanExtra("BackFromC",false)){
finish();
}
}
... your Code
}

Related

onActivityResult not working with onBackPressed?

I have two activities, Activity1.java and Activity2.java. Activity1.java starts Activity2.java and I need Activity2.java to return some data back to Activity1.java when the user presses the back button on the Action Bar. But for some reason, it is not working...
Activity1.java:
public class Activity1 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_1);
Intent intent = new Intent(this, Activity1.class);
int requestCode = 100;
startActivityForResult(intent, requestCode);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
Log.i("TEST", "RequestCode:" + requestCode);
Log.i("TEST", "ResultCode:" + resultCode );
switch (resultCode) {
case RESULT_OK:
Log.i("TEST", data.getStringExtra("MESSAGE"));
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
Activity2.java
public class Activity2 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(this, Activity1.class);
intent.putExtra("MESSAGE", "Hello from Activity 2!");
Log.i("TEST", "Setting result...");
setResult(RESULT_OK, intent);
finish();
super.onBackPressed();
}
}
When I run the app, only "Setting result..." is logged to Logcat. It seems like the onActivityResult override isn't even called. I've tried to change up the request code, result code, and setting the result in the onCreate() method of Activity2, but nothing works.
Could anybody help? Any help would be appreciated!
You are not calling the intent correctly:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_1);
Intent intent = new Intent(this, Activity1.class);
int requestCode = 100;
startActivityForResult(intent, requestCode);
}
should be:
Intent intent = new Intent(this, Activity2.class);
You need to return the result when you press the ActionBar back/home button, but you added the code in the bottom back button.
So, transfer the code in Activity2 to be handled when the ActionBar back button is pressed, so Override onOptionsItemSelected, and the home button has an id of android.R.id.home.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
Intent intent = new Intent(this, Activity1.class);
intent.putExtra("MESSAGE", "Hello from Activity 2!");
Log.i("TEST", "Setting result...");
setResult(RESULT_OK, intent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
There are 3 problems with your code.
1. From Activity1, you start itself not Activity2. Change your code from
Intent intent = new Intent(this, Activity1.class);
to
Intent intent = new Intent(this, Activity2.class);
2. In onBackPressed() of Activity2, no need to declare Activity1 inside the intent, change your code from
Intent intent = new Intent(this, Activity1.class);
to
Intent intent = new Intent();
3. In Activity1, you should check requestCode before process further to make sure the data return from correct activity, because you might start more than one activity.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
Log.i("TEST", "RequestCode:" + requestCode);
Log.i("TEST", "ResultCode:" + resultCode);
if (requestCode == 100) {
switch (resultCode) {
case RESULT_OK:
Log.i("TEST", data.getStringExtra("MESSAGE"));
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}

finish() does not close current activity at first time

I'm trying to develop an app with two activities which they send data to each other. the problem is that I want tofinish(); second activity. when I click on goBackButton_ which I defined in XML_ SecondActivity comes up, when I click on the button again, it comes back to MainActivity as I wanted. why? and How to solve it?why it doesn't work at first time?
public class MainActivity extends AppCompatActivity {
Button button;
int REQUEST_CODE = 1;
#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 v) {
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
intent.putExtra("FirstActivity", "Hello from first activity");
startActivity(intent);
startActivityForResult(intent, REQUEST_CODE);
Log.d("TAG", "onClickListener: done!");
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
Log.d("TAG", "onActivityResult: Entered");
if(requestCode == REQUEST_CODE) {
Log.d("TAG", "onActivityResult: requestCode is OK");
if (resultCode == RESULT_OK) {
Log.d("TAG", "onActivityResult: result is returned OK");
String result = data.getStringExtra("SecondActivity");
Toast.makeText(this, result, Toast.LENGTH_LONG).show();
Log.d("TAG", "onActivityResult: done!");
}
}
}
}
public class SecondActivity extends AppCompatActivity {
TextView textView;
Button goBackButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
goBackButton = (Button) findViewById(R.id.goBackButton);
goBackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("TAG", "onClick: Entered");
Intent returnIntent = getIntent();
returnIntent.putExtra("SecondActivity", "from second Activity");
setResult(RESULT_OK, returnIntent);
Log.d("TAG", "onClick: Message sent");
finish();
Log.d("TAG", "onClick: Activity finished");
//Intent myIntent = new Intent(SecondActivity.this,MainActivity.class);
//startActivity(myIntent);
}
});
textView = (TextView)findViewById(R.id.textView);
Bundle extras = getIntent().getExtras();
if(extras != null){
String string = extras.getString("FirstActivity");
textView.setText(string);
}
}
}
solved
The problem is in your code -
startActivity(intent);
startActivityForResult(intent, REQUEST_CODE);
When you want to do startActivityForResult you don't have to do startActivity as this will first open your second activity without looking for result.
Remove startActivity(intent);
you have added startActivity(intent) as well as startActivityforResult(intent, REQUEST_CODE) which creates double instance of an activity use only startActivityforResult(intent, REQUEST_CODE);
Try remove startActivity(intent);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
intent.putExtra("FirstActivity", "Hello from first activity");
startActivityForResult(intent, REQUEST_CODE);
Log.d("TAG", "onClickListener: done!");
}
});

Sending Zxing scanResult to another activity

I have tried everything and whatever I could to solve this problem. At last I am posting it here to get a solution (New to Android).
I have made an android scanner app and I am using ZXing open source code. The problem is after scan I am trying to send the scan result to another activity but unable to do.
Here is my code:
public class MainActivity extends AppCompatActivity
implements ZXingScannerView.ResultHandler, NavigationView.OnNavigationItemSelectedListener {
private ZXingScannerView mScannerView;
private int CALL_SCANNER_APP;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Scan Button code
public void onClick(View v) {
ZXingScannerView mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
mScannerView.setResultHandler(this);
mScannerView.startCamera();
//startActivityForResult(mScannerView1, CALL_SCANNER_APP);
}
#Override
protected void onPause (){
super.onPause();
mScannerView.stopCamera();
}
#Override
public void handleResult(Result result) {
ResultActivity.tvresult.setText(result.getText());
/*Log.w("handleReuslt", result.getText());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Scan Result");
builder.setMessage(result.getText());
AlertDialog alertDialog = builder.create();
//alertDialog.show();
builder.setPositiveButton("Result", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
}
});
builder.setNegativeButton("OK", null).show();*/
//Resume Scanning
//mScannerView.resumeCameraPreview(this);
}
There is one method which send results from One activity to other activity is scanActivityForResult() but in my case I am not using intent on public void onClick(View v)
So how do I achieve this.
Thanks!
Use Below code into the button click.
Intent intent = new Intent(SelectOptionActivity.this, CaptureActivity.class);
intent.putExtra("SCAN_MODE", "ONE_D_MODE");
intent.putExtra("SCAN_FORMATS", "CODE_39,CODE_93,CODE_128,DATA_MATRIX,ITF,CODABAR,EAN_13,EAN_8,UPC_A,QR_CODE");
intent.setAction(Intents.Scan.ACTION);
startActivityForResult(intent, 1);
And override this method to get result of scanning.
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 1 && resultCode == RESULT_OK) {
final String contents = intent.getStringExtra(Intents.Scan.RESULT);
final String formatName = intent.getStringExtra(Intents.Scan.RESULT_FORMAT);
}
}
in handleDecodeInternally you directly intent the Capture Activity to desired Activity
private void handleDecodeInternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) {
maybeSetClipboard(resultHandler);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (resultHandler.getDefaultButtonID() != null && prefs.getBoolean(PreferencesActivity.KEY_AUTO_OPEN_WEB, false)) {
resultHandler.handleButtonPress(resultHandler.getDefaultButtonID());
return;
}
statusView.setVisibility(View.GONE);
viewfinderView.setVisibility(View.GONE);
resultView.setVisibility(View.GONE);
Intent intent = new Intent(CaptureActivity.this, AfterCaptureActivity.class);
startActivity(intent);
finish();

Remove activities manually from Android app stack

I been working on Android Native App , What i was trying to do is :
Activities - A -> B -> C Then A-> B -> C -> C .
From C Activity if it again point to C then i want to remove C , B from stack manually .
On my back it should move only to A .
I tried finish() but problem is :
Activities - A -> B -> C Then A-> B -> C -> C on finish A -> B -> C required state A-> C .
Is anyone know how to catch all activities in stack and remove specific activities from stack ??
In Activity C, override onBackPressed and add in something like:
#Override
public void onBackPressed() {
if (shouldGoBackToA) { // There are various ways this could be set
Intent intent = new Intent(this, AActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} else {
finish();
}
}
FLAG_ACTIVITY_CLEAR_TOP will cause it to go down the stack to the existing copy of A Activity instead of starting a new one. From the docs:
public static final int FLAG_ACTIVITY_CLEAR_TOP
If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.
While calling intent pass a flag called actvity clear top like this:
Intent newIntent=new Intent(this,MainActivity.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(newIntent);
You can use this :
In A activity while passing to B activity, the intent should be added with a flag FLAG_ACTIVITY_NO_HISTORY like this,
Button b=(Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent newIntent=new Intent(AActivity.this,Bactivty.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(newIntent);
}
});
While moving to CActivity:
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent newIntent = new Intent(Bactivty.this, CActivity.class);
startActivity(newIntent);
}
});
On backpress will take you to AActivity now.
Step 1: Start activty for result A -> B -> C1 -> C2..
Call your Activity with startActivityForResult
Intent intent = new Intent(yourActivity.this, nextActivity.class);
startActivityForResult(intent, 1);
Step 2: In C2 specify that you want to go back to A..
Whenever you are done with your activity write the below code
Intent i = getIntent();
i.putString("Result","GottoA");
setResult(Activity.RESULT_OK, i);
finish();
Step 3: Whenever C2 finishes , previsus stack activit's onActivityResult is called.. so u can check in C1 and B onActivityResult whether you have set any result bck.. and finish accordingly
and impliment the following code in Activity B and c
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Intent i = getIntent();
if (resultCode == RESULT_OK && i.getString("Result","null").equals"GottoA") {
i.putString("Result","GottoA");
setResult(RESULT_OK, i);
finish();
}
}
In Activity C, when back button is pushed start activity A like this:
#Override
public void onBackPressed() {
Intent intent = new Intent(getApplicationContext(), A.class);
intent.putExtra("EXIT", true);
startActivity(intent);
}
Then in Activity A's onCreate() do this
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
}
this complete example may help you...
public class ActivityA extends Activity {
public static final int ID_TEXTVIEW = 0xDEAF1;
public static final int ID_BUTTON = 0xDEAF2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View contentView = getContentView(this);
TextView textView = (TextView) contentView.findViewById(ID_TEXTVIEW);
textView.setText("ActivityA");
setContentView(contentView);
final Button button = (Button) contentView.findViewById(ID_BUTTON);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ActivityA.this, ActivityB.class);
startActivity(intent);
}
});
}
public static View getContentView(Context context) {
LinearLayout layout = new LinearLayout(context);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setGravity(Gravity.CENTER);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.gravity = Gravity.CENTER_HORIZONTAL;
TextView textView = new TextView(context);
textView.setLayoutParams(layoutParams);
textView.setId(ID_TEXTVIEW);
layout.addView(textView);
Button button = new Button(context);
button.setText("Next");
button.setLayoutParams(layoutParams);
button.setId(ID_BUTTON);
layout.addView(button);
return layout;
}
}
public class ActivityB extends Activity {
public static final String ACTION_FINISH = "com.myapp.test2.ACTION_FINISH";
public ActivityB() {
}
private FinishReceiver finishReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View contentView = ActivityA.getContentView(this);
final TextView textView = (TextView) contentView
.findViewById(ActivityA.ID_TEXTVIEW);
textView.setText("ActivityB");
setContentView(contentView);
final Button button = (Button) contentView
.findViewById(ActivityA.ID_BUTTON);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ActivityB.this, ActivityC.class);
startActivity(intent);
}
});
finishReceiver = new FinishReceiver();
IntentFilter filter = new IntentFilter(ACTION_FINISH);
registerReceiver(finishReceiver, filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(finishReceiver);
}
private class FinishReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_FINISH)) {
finish();
}
}
}
}
public class ActivityC extends Activity {
public ActivityC() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View contentView = ActivityA.getContentView(this);
final TextView textView = (TextView) contentView
.findViewById(ActivityA.ID_TEXTVIEW);
textView.setText("ActivityC");
setContentView(contentView);
final Button button = (Button) contentView.findViewById(ActivityA.ID_BUTTON);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ActivityB.ACTION_FINISH);
sendBroadcast(intent);
intent = new Intent(ActivityC.this, ActivityC.class);
startActivity(intent);
finish();
}
});
}
}

Code in onActivityResult() not executed

I've got an android application that I want to open a different activity then my main one after a fresh install.
I tried this using startActivityForResult() and SharedPreferences. Here is my code:
main activity:
public class ONTTMainActivity extends Activity {
static final int REQUEST_CODE = 5;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences settings = getSharedPreferences("prefs", 0);
boolean firstRun = settings.getBoolean("firstRun", true);
if(firstRun){
startActivityForResult(
new Intent(this, ONTTSplashActivity.class), REQUEST_CODE);
}
setContentView(R.layout.activitymain);
}
second activity:
public class ONTTSplashActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activityonttsplash);
final Button btnSkip = (Button) findViewById(R.id.button_skip);
btnSkip.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setResult(RESULT_OK);
finish();
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Toast.makeText(ONTTSplashActivity.this, "Toast Reached", Toast.LENGTH_LONG).show();
if (resultCode == RESULT_OK) {
SharedPreferences settings = getSharedPreferences("ONTT_prefs", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("firstRun", false);
editor.commit();
}
}
The problem is that even though the second activity is ended the code in the onActivityResult function is never executed. I tried using a toast to see if it has been reached.
I've seen several similar questions but I've tried every solution but it's not working.
You are starting ONTTSplashActivity from ONTTMainActivity for getting result back from ONTTSplashActivity to ONTTMainActivity so put onActivityResult in first ONTTMainActivity activity:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Toast.makeText(ONTTMainActivity .this, "Toast Reached", Toast.LENGTH_LONG).show();
if (resultCode == RESULT_OK) {
SharedPreferences settings = getSharedPreferences("ONTT_prefs", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("firstRun", false);
editor.commit();
}
}
OnActivityResult() must be in you first activity not in the second activity.
Since from first activity only you are calling startActivityForResukts() so your first activity expect for results from the second activity.

Categories

Resources