开发者

How to store one string and arrayvalue in sharedpreference?

I have array values of up[]={0,0,0,0,0}开发者_StackOverflow社区 and view="adult" thesetwo value i want to store and retrieve in from sharedpreference how to do that...


Assuming that you have a list of preferences for you app called MY_PREFS, I'd do this:

SharedPreferences settings = getSharedPreferences(MY_PREFS, 0);
      SharedPreferences.Editor editor = settings.edit();
      editor.putInt("arrayLength",up.size());
      for(int i=0; i<up.size(); i++){
         editor.putInt("up"+String.valueOf(i), up[i]);
      }
      editor.putString("view", "adult");

To retrieve them do:

   SharedPreferences settings = getSharedPreferences(MY_PREFS, 0);
   int arraySize = settings.getInt("arrayLength");
   int up[] = new int[arraySize];
   for(int i=0; i<arraySize; i++){
      up[i] = settings.getInt("up"+String.valueOf(i));
   }
   String view = settings.getString("view");


you can do by simple way, like this

SharedPreferences settings = getSharedPreferences("pref_name", 0);
      SharedPreferences.Editor editor = settings.edit();

     String values="";

      for(int i=0; i<yourArray.length; i++){
         values+=","+Integer.toString(yourArray[i]);
      }

      editer.putString("array",values);
      editor.putString("view", "adult");

To get those values,

 SharedPreferences settings = getSharedPreferences("pref_name", 0);

 String[] strArray=settings.getString("array").split(",");
int[] yourArray=new int[strArray.length];

for(int i=0;i<strArray.length;i++){
   yourArray[i]=Integer.toParseInt(strArray[i]);
}


Well as far as I have seen you can't directly store an array in shared preferences. You can however use a for loop to save an int with an increasing name and have it call it back the same way when you need it and store it into another array.

for(int i=0; i<numInYourArray; i++){
editor.putInt("up"+i, up[i]);
}

If you aren't sure on how to use Shared Preferences in general look here

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜