-1

I'm attempting to write new value into a Shared Preference and seems not to work, am I missing something.

// this tests output 
System.out.println("This OLD ID : "+oldPost+ " - NEW ID :"+postID);


// output : This OLD ID : 5233 - NEW ID :5216



        ///get old id
        SharedPreferences prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE);
        String oldPost = prefs.getString("newsId", null);


            if (oldPost.equals(postID))
            {
                System.out.println("This has been alerted : ");
            }
            else
            {

                System.out.println("This is something new : ");


//set old post to new post - does not seem to work
SharedPreferences.Editor editor = getSharedPreferences("MyPrefs", MODE_PRIVATE).edit();
                    editor.clear();
                    editor.putString("newsId", "" + oldPost);
                    editor.commit();
                }
            }

Hope this is a obvious answer... Thanks in advance.

user7763438
  • 65
  • 1
  • 8
  • Check this [answer](http://stackoverflow.com/questions/18793903/android-sharedpreferences-update-does-not-work) – Pial Kanti Mar 27 '17 at 16:58
  • If there will be no value ins sharedPrefs, your line `if (oldPost.equals(postID))` will give you nullPointerException, so you want to probably check if it is not null, or set default value for `oldPost` – miljon Mar 27 '17 at 17:04
  • Provide the code when you first put newsId to your SharedPreference. In above code you are applying getString even before putting the string. – tahsinRupam Mar 27 '17 at 17:05
  • // output : This OLD ID : 5233 - NEW ID :5216 – user7763438 Mar 27 '17 at 17:11
  • In first 3 lines you are setting `postID` to 232, then printing `postID` and output is 5216.. I don't think so ;) post whole code, and describe exactly what is wrong.. – miljon Mar 27 '17 at 17:18

2 Answers2

0

Instead of

editor.putString("newsId", "" + oldPost);

Do this

editor.putString("newsId", "" + postID);
Basu
  • 763
  • 8
  • 27
0

First things first, do not use null, use empty string "" in String oldPost = prefs.getString("newsId", null); Next editor.putString("newsId", "" + oldPost); here you inserting a oldPost should it be postID. Second you do not need to cast a string to a string with "" + oldPost because there of the same type, and if you are going to perform casting, please the default String.format API much cleaner.Also you do not need to clear the sharedPreference simply OverWrite it. So remove the clear method. You can simply individually remove keys if you wish with editor.remove(String key);

Remario
  • 3,813
  • 2
  • 18
  • 25