开发者

SharedPreferences Android issue

I'm trying to use SharedPreferences in my application and I need a little hep because I just start using it.Basically the thing that I want to do is : I create SharedPreference object in my main activity, then in second activity I have a list view and clickin item i use putInt(); to put integer to send a text.On the new activity I have a button which add the sharedpreference in adroid system. And finally depending on the id sent to the second activity I want to show different text in activity number 3.

Here is a little code :

Main Activity :

SharedPreferences faves = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = faves.edit();
        editor.putInt("favorites",0);
        editor.commit();

Second activity:

SharedPreferences favs= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        final SharedPreferences.Editor editor = favs.edit();

Third Activity where I want to show text depends on wh开发者_如何学Pythonich item is clicked:

favs.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                editor.putInt("favorites", getIntent().getIntExtra("id", 0));
            }
        });

Any suggestions how to fix that?


You don't really have to create your own SharedPreference object, the api Activity.getSharedPreference(name, mode) will do it.

Basically what it does is to create a xml file under your app's own folder, and every put...() will add an item in the xml so that you can update and read later, you just need to give the correct name.

having a global editor is a bad idea, sometime it may lose your data, so get an editor every time you want to read/write the sharedPreference.


Ok, first off it is difficult to understand the question. In the example code you are attempting to store values in the main activity and the third activity but don't seem to ever read values. Then at the end you ask "Any suggestions how to fix that?" what does "that" represent? Are you getting an error or a result you don't expect? Here is some sample code I use. I have a static Constants class with some values I reuse in other parts of my app but you get the idea.

ApplicationContext context = ApplicationContext.getInstance(); //I use a custom app context but any context will do.
SharedPreferences prefs = context.getSharedPreferences(
Constants.PREFS_FILE_NAME, Activity.MODE_PRIVATE);
prefs.getString("favorites", null);//or any other getter you want to use
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜