Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching activities back and forth in Android

I'm starting on Android and got a beginner question on switching between multiple activities.

I understand i can go between two activities by invoking an intent and then returning with setResult(). What I want to know is how to jump between multiple activities. Specifically I want to learn about the process life-cycle. I understand how every activity is started ar onCreated(), but I'm not sure how to implement onResume() or onRestart() when I want to come back.

So basically I have 3 activities: Activity1, Activity2 and Anctivity3.

I start with Activity1 and then invoke Activity2 with an Intent, and Activity2 invokes Activity3. Using buttons. Now I want to come back to Activity1 from Activity3. I do the same thing here too. Make an Intent and call startActivity(Activity1_Intent). But it gives a runtime error.

I think I need to implement OnResume() or onRestart(), but I'm not sure how to do this. In onCreate() I make a gridView, so when I come back, do I need to make that gridView again?

If anybody could give a small explanation of refer to a tutorial it would be great. Thank you very much.

like image 258
madu Avatar asked Sep 22 '10 12:09

madu


1 Answers

In your manifest file set android:launchMode="singleTop" to your Activity1.

Then to call your Activity1 use:

Intent intent = new Intent(this, Activity1 .class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

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.

FLAG_ACTIVITY_NEW_TASK: If set, this activity will become the start of a new task on this history stack.

http://developer.android.com/reference/android/content/Intent.html

like image 178
john 4d5 Avatar answered Oct 19 '22 05:10

john 4d5