Android - How to move to activity dynamically or previous activity? - java

I have 3 activities , Activity A and Activity B both can access to Activity C.
But at a time,I am using Intent to return back to previous activity.
Intent i = new Intent(C.this , A.class);
Here i use activity C to return back to Activity A.
but i want to return to activity A or B from C depending upon who called it.
Not using finish(); to return back to activity.
If A calls C then intent i = new Intent (C.this, "dynamically set A");
If B calls C then intent i = new Intent (C.this, "dynamically set B");

Pass a bundle in first call(A to C or B to C) and check where it's came from when clicking back action.

You can simply use finish() method without using the intent. Look at this:
Button button = this.findViewById(R.id.backButton);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});

Related

Return back to Fragment from Activity

I have MainActivity with BottomNav which includes 3 Fragments A, B, and C.
From Fragment A, I can go to Activity A and from, Activity A I can go to Activity B.
Now I want to return to specifically Fragment A from Activity B by pressing a Back button while skipping Activity A.
I've tried Intent.FLAG_ACTIVITY_CLEAR_TASK in Activity A before starting Activity B and also explicitly starting an Intent to MainActivity from Activity B but it's not giving the result I want and of course it doesn't seem like an efficient way to do it. How do I return back to the fragment?
Case 1
You need to finish Activity A after launching intent.
Intent intent = new Intent(ActivityB.this,ActivityA.class);
startActivity(intent);
finish();
case 2
If you want to come back on Activity A at some point then what you need is passing some flag from Activity B to A. And run this code at the beginning of your activity A.
if(extras.getBoolean("NameOfFlag", false))
{
ActivityA.finish();
}
send flag by using this code.
Intent i = new Intent(ActivityB.this, ActivityA.class);
i.putExtra("NameOfFlag", true);
startActivity(i);
finish();
Remember to finish() Activity when you don't need to come back. In this case ActivityB .
Maybe it is not the ideal solution but should work
In Activity B
#Override
public void onBackPressed() {
Intent i = new Intent(ActivityB.this, MainActivity.class);
i.putExtra("cameFromActivityB", true);
startActivity(i);
}
In Main Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
Bundle extras = getIntent.getExtras();
if(extras.getBoolean("cameFromActivityB", false))
{
loadFragmentA();
}
}
// Inside the onCreate on every Activity://
getSupportActionBar().setTitle("name of the Activity here");
getSupportActionBar().setDisplayHomeAsUpEnable(true);
//then go to the manifest file in //
//before that closing bracket
set the order of your Activities; example
(you have three activities,the Main Activity,Activity2,Activity3)//
<activity android:name=".Activity2"
android:parentActivityName=".MainActivity"></activity>
What you can do is when you start your ActivityB from ActivityA just finish your activityA by finish() method.
Intent intent = new Intent(ActivityB.this,ActivityA.class);
startActivity(intent);
finish();
By doing this you will not be redirected to ActivityA instead, you will be directy redirected to your main activity when you press back button from your activityB.

How to exit an app when Back Button is pressed

This is a small question but I'm finding very hard to solve this. I have multiple activities. For example A B and C. When app is launched A is opened and on click of button will redirect me to activity B and then from B on click of another button will take me to C. On Back pressed will now bring me back to B and again on Back button is pressed will take me to A which is main Activity.
Now if I press back button, instead the app should exit...it creates loop between B and A and never exit the app.
I already used the following method
Method 1:
use of this.finishonBackPressed which didn't help
Method 2:
use android:nohistory = true in manifest
But If I do so then from C activity it will directly take me to A which I don't want.
Method 2.
Use of
Intent intent = new Intent(Intent.ACTION_MAIN);
//to clear all old opened activities
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
when I use this then everytime this opens up in my device
Please anyone help.
This is my code in Mainactivity now
#Override
public void onBackPressed() {
finish();
super.onBackPressed();
}
But also it don't work and it creates loop between A and B Activity.
Your code (in MainActivity) is incorrect , put finish() after super.onBackPressed()
it must be :
#Override
public void onBackPressed() {
super.onBackPressed();
finishAffinity(); // or finish();
}

Android exit whole program syntax

currently I'm working on Android development, now I'm facing a problem to exit the whole application that had launched.
I'v tried .finish(), but it doesn't show what I want.
I have 2 Activities, A and B. Activity A will forward to Activity B when button click. In activity B, when I click button "Exit" (that I created) with the listener to trigger .finish(), it just back to Activity A but not to close whole application (what I want is back to home screen directly and kill the background process as well).
How can I exit whole application wherever in the application? Thank you.
button.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
//here to exit whole application not just backwards to previous activity
}
});
You write in Activity A after
startActivity(new Intent(A.this, B.class))
finish()
then you also write in Activity B finish() on button click listener. It should works.
public class A extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(A.this, B.class));
finish(); // you must write this also in A activity to close whole application
}
});
}
public class B extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_1);
Button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
EDIT: I assumed there are cases when the underlying activity either should or shouldn't be terminated on return. This will allow you to handle both cases.
Case A)
Activity A starts activity B, which starts activity C. You want to close all of them from activity C. If they're all in the same task (i.e. probably your case) you can close the whole task by calling
finishAffinity();
According to docs this is what happens:
Finish this activity as well as all activities immediately below it in the current task that have the same affinity. This is typically used when an application can be launched on to another task (such as from an ACTION_VIEW of a content type it understands) and the user has used the up navigation to switch out of the current task and in to its own task. In this case, if the user has navigated down into any other activities of the second application, all of those should be removed from the original task as part of the task switch.
Note that this finish does not allow you to deliver results to the previous activity, and an exception will be thrown if you are trying to do so.
See Activity.finishAffinity().
Case B)
Activity A starts activity B, which starts activity C. You want to close activities B and C from activity C.
This is how you start activity C from B expecting and handling a result:
public class ActivityB extends Activity {
private static final int RC_ACTIVITY_C = 1;
public static final int RESULT_FINISH = 1;
...
public void startActivityC() {
Intent intent = new Intent(this, ActivityC.class);
startActivityForResult(intent, RC_ACTIVITY_C);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_ACTIVITY_C && resultCode == RESULT_FINISH) {
finish();
}
}
}
This is how you let activity B it has to finish from activity C. At any point before finishing activity C call:
setResult(ActivityB.RESULT_FINISH);
See Activity.startActivityForResult(Intent, int) and Activity.setResult(int).
You can try System.exit(0). That should do the job.
EDIT: Take a look at this post for the difference between finish() and System.exit(). Difference between finish() and System.exit(0)

Activities Stack Issue

I have two sets of Activities suppose 3 Activities each set, (A1,B1,C1 || A2,B2,C2) I start my App from A1 then -> B1 -> C1 here I want to jump from C1 to -> A2 and at A2 if I press back it should exist the App and not put me back for C1, then from A2 I navigate to -> B2 -> C2.
So it is basically I want to change the starting Activity, it is like I have two Apps in one App and when I flip to the second App I have to clear the Activity Stack. Is that possible? Any Ideas?
Seems to me you've answered your own question. You wrote:
So it is basically I want to change the starting Activity, it is like
I have two Apps in one App and when I flip to the second App I have to
clear the Activity Stack.
I would do it this way:
Create a DispatcherActivity which is the activity that gets launched when the application is started. This Activity is the root activity of your task and is responsible for launching either A1 or A2 depending... and NOT call finish() on itself (ie: it will be covered by A1 or A2 but still be at the root of the activity stack).
In A1, trap the "back" key and tell the DispatcherActivity to quit like this:
#Override
public void onBackPressed() {
Intent intent = new Intent(this, DispatcherActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addExtra("exit", "true");
startActivity(intent);
}
This will clear the task stack down to the root activity (DispatcherActivity) and then start the DispatcherActivity again with this intent.
In C1, to launch A2, do the following:
Intent intent = new Intent(this, DispatcherActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addExtra("A2", "true");
startActivity(intent);
This will clear the task stack down to the root activity (DispatcherActivity) and then start the DispatcherActivity again with this intent.
In DispatcherActivity, in onCreate() you need to determine what to do based on the extras in the intent, like this:
Intent intent = getIntent();
if (intent.hasExtra("exit")) {
// User wants to exit
finish();
} else if (intent.hasExtra("A2")) {
// User wants to launch A2
Intent a2Intent = new Intent(this, A2.class);
startActivity(a2Intent);
} else {
// Default behaviour is to launch A1
Intent a1Intent = new Intent(this, A1.class);
startActivity(a1Intent);
}
In A2, trap the "back" key and tell the DispatcherActivity to quit using the same override of onBackPressed() as in A1.
Note: I just typed this code in, so I've not compiled it and it may not be perfect. Your mileage may vary ;-)
You can check when the button that is pressed in Activity A2 and then if its a Back button you can close the app. You can use the following method in A2
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
this.finish();
}
return super.onKeyDown(keyCode, event);
}
try launching the activity A2 with this intent - intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Handle this using onBackPressed and finish methods.
Before launching other activity, better you close the current activity using finish() method.
If you want to go to previous activity on back press, override onBackPressed method and call the particular intent.
In A2 activity, add finish method in onBackPressed method (dont call previous activity here). This is one of the way.
while passing Intent from Activity C1 to A2 use as
Intent intent=new Intent(C1.this,A2.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
and in Your Activity A2 Override Back Button by
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
A2.this.finish();
}
return super.onKeyDown(keyCode, event);
}
if you want to close your app when press the back button instead of go back last activity, you should overwrite the back button. in the overwrite method call finish() method after close the activity. i hope this may help you.
edited:
check the below link : this is for close all activities in your view stack. before closing your app close all activities.
http://www.coderzheaven.com/2011/08/27/how-to-close-all-activities-in-your-view-stack-in-android/
FLAG_ACTIVITY_CLEAR_TOP is not what you are looking for.
i think you are looking for:
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);

Passing data between activities

I have the following code:
chart.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final String aux= (String) lt.getItemAtPosition(position);
Intent myIntent = new Intent(infoList.this, tabList.class);
startActivity(myIntent);
}
});
I also have a ListView. When I click on an item from that ListView I navigate to another activity that shows me the info for that activity. How do I do that? I want that info to correspond to the item I clicked.
Here is what I did in this situation, if you don't want to just pass an id back:
I call the other activity with this:
Intent intent = new Intent(myapp, CreateExerciseActivity.class);
intent.putExtra("selected_id", workout.getId());
startActivityForResult(intent, CREATE_ACTIVITY);
I then do
Intent returnIntent = new Intent();
returnIntent.putExtra("name", m.getName());
returnIntent.putExtra("unit", m.getUnit());
returnIntent.putExtra("quantity", m.getQuantity());
if (getParent() == null) {
setResult(Activity.RESULT_OK, returnIntent);
} else {
getParent().setResult(Activity.RESULT_OK, returnIntent);
}
finish();
So, in this case I was passing in an id in order to get more details from the user, and then I pass those back to the calling activity, in order to add it, as I didn't want to save this until the user chooses to later.
So, you need to do startActivityForResult in order to have it able to return the data.
You can add some data to the Intent with the methods putExtra(), and then retrieve the data in the new Activity with getExtras().getSomething().
i guess you have to use OnItemClickListener instead of the click event and you need intent to call the next activity.
private OnItemClickListener mMessageClickedHandler = new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id)
{
Intent intent = new Intent(this, MyInfoActivity.class);
intent.putExtra("selected_id", getIdFor(position));
startActivity(intent);
}
};
mHistoryView = (ListView)findViewById(R.id.history);
mHistoryView.setOnItemClickListener(mMessageClickedHandler);
Possible answer: How do I pass data between Activities in Android application?
http://thedevelopersinfo.wordpress.com/2009/10/15/passing-data-between-activities-in-android/
It really depends on what the data is in your listview. For example, if you're displaying a list of contacts in the listview, you could just pass the ID of the contact over to the other activity, and let that activity access the content provider for contacts to retrieve the data you want it to work with. You'd pass an ID within a URI in the data field of the intent, as opposed to in the extras bundle.

Categories

Resources