How to create a forwards, backwards system in Android
I am building a game, that is step based, so I need to be able to create forward and back button.
Each step has an Id and the info for it is taken from and SQLite database. I am going to be saving maxLevel
, the maximum reached step, as well as currentStep
, the cu开发者_StackOverflow中文版rrent step, in the shared preferences. Now I was wondering how do I start a new action that would take someone to the next/previous step, without clogging up the memory too much. I know I can start a new action and pass it data something like this:
final Context mContext=this;
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("count", 2);
editor.commit();
Intent myIntent = new Intent(mContext, PlayGame.class);
mContext.startActivity(myIntent);
Now my main worry here is the memory usage. If I go forward 2 times using this, then back 2 times and then forward 2 times again, won't it create 6 instances of the activity? That could be a massive memory hog.
So the question here is:
How do I implement a forward/back system with 1 activity, that is relaunched and retrieves data from a database?
For more background info: The activity is a TabHost, which has 4 tabs, and each of these tabs has an activity inside it. Each activity retrieves the data it needs from the database. Therefore my concern about the memory usage.
Edit:
I seem to have found a solution. I am calling the finish()
function before I start the new activity. I do believe, that this should help avoid any leaks. am I right in thinking this?
Just a thought
How about running a back ground thread which will update your UI, Such as AsynTask. back and forward method will trigger background thread which will update your UI and can update data from SQL as well, By this you don't have to change activity
Helpful Links,
http://developer.android.com/resources/articles/painless-threading.html
http://topandroid.net/threads-handlers-asynctask
Happy Coding!
After your edition,
If your second activity has different data structure than this is a good idea to finish() as you are going to create new object anyway. But if data structure is same than probably using same objects and update their value will be more efficient.
One more edition, After updating your variables from background thread you may have to call set methods on your views for your UI to show a recent change. This is logical but just wanted to share it :)
Enjoy!
精彩评论