简体   繁体   中英

shared preferences doesn't commit

I have some list view with "venues", places in a city. When you click on it you go to the Venue page, using the ID.

On this venue page, there is a little add-button, with a + on it. When you press this i need:

  • To get the list of other favorites from shared preferences, i saved it as a comma separated string and convert it to a list of integers
  • add the id of this item
  • Reconvert the list of integers to a string, comma separated.
  • Save this string under the same key, i used "fav"

and further change the image of the button, so the + becomes a -

I thought i managed to do this, my code is at the bottom of my post.

Now i my problem, my favorite string isn't really saved. For some reason (no idea why) every time i open a venue, there are two values in the string i retrieve from the shared preferences: null and 333. Even when i used a editor.clear(); in the startup-activity, AND used commit of course, it still had the same return values. Especially the 333 is very weird i guess, but i thought i excluded the possibility of saving null to the string as well.

What happens now is: when i click the button, most of the times it don't react the first time. Second time or so it does, i logged the process, then the id get added to the shared preferences, and my button changes nicely. Then on another press, mostly the first time no reaction again, and second time removes from favorites and button changes.

But when i leave my activity and open the same activity with another id, the string only has the null and 333 values again.

    final int favID = id;
        btFavourite.setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View v) {
                if(isFavourite(favID)){
                    btFavourite.setBackgroundResource(R.drawable.btn_favourites_remove);
                    DeleteFavourite(favID);
                }else{
                    btFavourite.setBackgroundResource(R.drawable.btn_favourites_add);
                    MakeFavourite(favID);
                }

            }
        });

}


     private void SaveFavourites(List<Integer> favs){
            SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            String commSepFavs = IntArrToComSepString(favs);
            editor.putString("favs", commSepFavs);
            editor.commit();
           }

           private List<Integer> LoadFavourites(){
            SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
            String favStr = sharedPreferences.getString("favs", "");
            System.out.println(favStr);
            if (favStr != null){
            return CommaSepStringToIntArr(favStr);
            }else{
                return null;
            }
            }

        public List<Integer> CommaSepStringToIntArr(String input){
               List <Integer> favs= new ArrayList<Integer>();
                    String[] separated = null;
                separated = input.split(",");
                 System.out.println("separated lengte " + separated.length);
                 String tijdelSep;
                for (int i=0;i<separated.length;i++){
                     tijdelSep = separated[i].replace(",","").trim();
                    System.out.println("tijdelSep "+i+" = " + tijdelSep);
                if(tijdelSep != null && tijdelSep.equals("")==false &&tijdelSep.equals("null")==false){
                    favs.add(Integer.parseInt(tijdelSep));
                }
                }
            return favs;
            }

           public String IntArrToComSepString(List<Integer> favs){
               String comSepFavs = null;
               for (int i=0;i<favs.size();i++){
                   comSepFavs = comSepFavs +","+String.valueOf(favs.get(i));
               }
            return comSepFavs;  
           }

           public boolean isFavourite(int id){
               boolean isFav = false;
               List<Integer> favs = LoadFavourites();
               for (int i=0;i<favs.size();i++){
                    if(favs.get(i)==id){
                        isFav=true;
                    }
                }
               return isFav;               
           }

           public void MakeFavourite(int id){
               List<Integer> favs = LoadFavourites();
               List<Integer> newfavs = new ArrayList<Integer>();
               for (int i=0;i<favs.size();i++){
                   newfavs.add(favs.get(i));
               }
               newfavs.add(id);
               SaveFavourites(newfavs);
           }

           public void DeleteFavourite(int id){
               List<Integer> favs = LoadFavourites();
               List<Integer> newfavs = new ArrayList<Integer>();
               int j=0;
               for (int i=0;i<favs.size();i++){
                   if(favs.get(i) != id){
                   newfavs.add(favs.get(i));
                   j++;
                   }
               }
               SaveFavourites(newfavs);
           }

I'm not sure about it, but your problem might be in SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);

AFAIK, you should use something like: SharedPreferences sharedPreferences = getPreferences("prefs_file_name", MODE_PRIVATE); instead of the line you have.

You can save your preferences in the default shared preferences too. Use SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

Take a look at the getDefaultSharedPreferences (Context context) method specification.

Could you post more (ie all of your activity) code? Besides that I also think you should use a DB, your called to shared preferences is ok (your call just calls sharedPreferences(String, int) with the activity name as the string. This file will persist every time you open the activity, and until you actually delete it. Shared preferences are pretty much just flat files that are stored on the device.

Some things: 1) when you did editor.clear() - did you commit and 2) did you make other changes on that editor (eg editor.putString() or something). It won't actually clear the file, it'll clear it and then insert whatever has been added on that editor instance

2) null and "" aren't the same things for Strings. That's why it's giving you a null when you initialize your String to null.

If you could post more of your code I could try and help more. Also, how are IDs getting passed to your activity?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM