开发者

How do I save and load information to the phone from an App?

开发者 https://www.devze.com 2023-03-05 18:14 出处:网络
My app is a basic golf counter that is mainly an array of \"hole\" objects that contains 2 integers; hole number and the stroke number.

My app is a basic golf counter that is mainly an array of "hole" objects that contains 2 integers; hole number and the stroke number.

I am trying to save the information to the phone as a string when the app is killed and then read it back in and use String.split() and Integer.parse() to write the information back into the array.

I use OnPause() and OnResume() and I have been testing my app by pressing the back arrow 开发者_Python百科button to see if it is saving. But I cant seem to get it to work.

Am I right to use OnPause() and OnResume()?


if you wan the values to be saved permanently, then you need to use SharedPreferences like this:

(within onCreate)
...
SharedPreferences user_info = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
hole = user_info.getInt("hole", 0);
stroke = user_info.getInt("stroke", 0);
...
}

@Override
public void onPause()
    {
    super.onPause();
    SharedPreferences user_info = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    user_info.edit()
    user_info.putInt("hole", hole)
    user_info.putInt("strike", stroke)
    user_info.commit();
    }

if you don't include the commit() then nothing happens. also you can (and i would) use method chaining for the SharedPreferences, i just thought i should keep it simple.

it is just as easy to leave them as int (or int[] i wasnt entirely clear which you were going for) instead of dealing with all that splitting and parseing. now if you are trying to add them so that everytime you quit, your hole and strike are added to an evergrowing array, thats a little more complex and i can help you with that too if thats the case.


If not already familiar with it, it's well-worth reading http://developer.android.com/guide/topics/data/data-storage.html


As you can see on the attached image. OnPause() and OnResume() are the right places:

How do I save and load information to the phone from an App?

You should check your code. How are you saving the data? How is it read back? Do some logcat debug output...

Perhaps you should use the mySQL database to save the data persistent.

0

精彩评论

暂无评论...
验证码 换一张
取 消