Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle "Don't keep Activities" in android app

I have 2 activities: an activity showing a list of informations to the user, and its subactivity where the user can create new informations.

In clear, from the first activity, I call a "startActivityForResult()" and when the user puts what he wants in the second activity, I go back to the first activity and I receive the informations in the "onActivityResult()" function to save the informations.

My problem here is the "Don't keep Activities" options. I read that this occurs in low memory phones. But how can we handle that when the device close the activities?

In my example, when the second activity is called, the first one is killed, so a crash occurs when we go back to that activity, and my informations are lost.

What is the proper way to handle that? Knowing that I cannot save my information in the second activity because I am using files.

like image 500
FR073N Avatar asked Nov 18 '12 10:11

FR073N


2 Answers

Use SharedPreferences to your purpose. By the way, you can use this technique to store your data when you close your activity at all.

Take your class data, convert it to String by using GSON and store it.

On load just move it from SharedPreferences and convert back from String to your Object.

lets say you have MyData class with all impotent information.

MyData myData = ....;

SharedPreferences mPrefs = context.getSharedPreferences("MyPrefs", 0);
Gson gson = new Gson();
String toStore = gson.toJson(myData);


SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("stored", toStore);
editor.commit();

 ....

When you load back your previous Activity:

String loadedMyDataStr = mPrefs.getString("stored", "");
MyData data = gson.fromGson(loadedMyDataStr, MyData.class );
like image 122
Maxim Shoustin Avatar answered Sep 20 '22 03:09

Maxim Shoustin


As you said, each activity can be killed anytime after the onPause method call. You can store your ListView state from the first activity in onPause and load it in onResume - you may use a singleton for this purpose.

Also your operations in onPause should be as fast as possible, don't do any complex operations in there. Otherwise your application may look like it has frozen and no user can interact with it...

like image 37
user219882 Avatar answered Sep 20 '22 03:09

user219882