【问题标题】:How to store json object to shared preferences?如何将 json 对象存储到共享首选项?
【发布时间】:2016-01-17 10:24:13
【问题描述】:

我正在创建一个应用程序,在我的应用程序中我得到响应并在自定义警报对话框中显示它,直到这里它工作正常,现在我要做的是如果用户从警报对话框中选择一个项目一次,它应该优先存储它,这样就不需要每次都获取数据。

以下是我的代码 sn-p。

我得到的以下回复是:

    {
    "states": [
        {
            "id": "1",
            "state_slug": "agra",
            "statename": "Agra"
        },
        {
            "id": "2",
            "state_slug": "andaman_and_nicobar_islands",
            "statename": "Andaman and Nicobar Islands"
        },
        {
            "id": "3",
            "state_slug": "andhra_pradesh",
            "statename": "Andhra Pradesh"
        },
        {
            "id": "4",
            "state_slug": "arunachal_pradesh",
            "statename": "Arunachal Pradesh"
        },
        {
            "id": "5",
            "state_slug": "assam",
            "statename": "Assam"
        },
        {
            "id": "6",
            "state_slug": "bihar",
            "statename": "Bihar"
        },
        {
            "id": "7",
            "state_slug": "bulandshahr",
            "statename": "Bulandshahr"
        },
        {
            "id": "8",
            "state_slug": "chhattisgarh",
            "statename": "Chhattisgarh"
        },
        {
            "id": "9",
            "state_slug": "dadra_and_nagar_haveli",
            "statename": "Dadra & Nagar Haveli"
        },
        {
            "id": "10",
            "state_slug": "daman_and_diu",
            "statename": "Daman & Diu"
        },
        {
            "id": "11",
            "state_slug": "delhi",
            "statename": "Delhi"
        },
        {
            "id": "12",
            "state_slug": "farrukhabad",
            "statename": "Farrukhabad"
        },
        {
            "id": "13",
            "state_slug": "goa",
            "statename": "Goa"
        },
        {
            "id": "14",
            "state_slug": "gujarat",
            "statename": "Gujarat"
        },
        {
            "id": "15",
            "state_slug": "haryana",
            "statename": "Haryana"
        },
        {
            "id": "16",
            "state_slug": "himachal_pradesh",
            "statename": "Himachal Pradesh"
        },
        {
            "id": "17",
            "state_slug": "jammu_and_kashmir",
            "statename": "Jammu & Kashmir"
        },
        {
            "id": "18",
            "state_slug": "jharkhand",
            "statename": "Jharkhand"
        },
        {
            "id": "19",
            "state_slug": "karnataka",
            "statename": "Karnataka"
        },
        {
            "id": "20",
            "state_slug": "kerala",
            "statename": "Kerala"
        },
        {
            "id": "21",
            "state_slug": "lakshadweep",
            "statename": "Lakshadweep"
        },
        {
            "id": "22",
            "state_slug": "madhya_pradesh",
            "statename": "Madhya Pradesh"
        },
        {
            "id": "23",
            "state_slug": "maharashtra",
            "statename": "Maharashtra"
        },
        {
            "id": "24",
            "state_slug": "manipur",
            "statename": "Manipur"
        },
        {
            "id": "25",
            "state_slug": "meghalaya",
            "statename": "Meghalaya"
        },
        {
            "id": "26",
            "state_slug": "mizoram",
            "statename": "Mizoram"
        },
        {
            "id": "27",
            "state_slug": "nagaland",
            "statename": "Nagaland"
        },
        {
            "id": "28",
            "state_slug": "orissa",
            "statename": "Orissa"
        },
        {
            "id": "29",
            "state_slug": "pondicherry",
            "statename": "Pondicherry"
        },
        {
            "id": "30",
            "state_slug": "punjab",
            "statename": "Punjab"
        },
        {
            "id": "31",
            "state_slug": "purulia",
            "statename": "Purulia"
        },
        {
            "id": "32",
            "state_slug": "rajasthan",
            "statename": "Rajasthan"
        },
        {
            "id": "33",
            "state_slug": "sikkim",
            "statename": "Sikkim"
        },
        {
            "id": "34",
            "state_slug": "tamil_nadu",
            "statename": "Tamil Nadu"
        },
        {
            "id": "35",
            "state_slug": "tripura",
            "statename": "Tripura"
        },
        {
            "id": "36",
            "state_slug": "uttar_pradesh",
            "statename": "Uttar Pradesh"
        },
        {
            "id": "37",
            "state_slug": "uttarakhand",
            "statename": "Uttarakhand"
        },
        {
            "id": "38",
            "state_slug": "west_bengal",
            "statename": "West Bengal"
        }
    ]
}

我在我的警报对话框中显示 statename,

class LoadAllStates extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {

          ArrayAdapter<String> adapterallstates ;
        private ProgressDialog pDialog;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(MainActivity.this);
                pDialog.setMessage("Please wait..");
                pDialog.setIndeterminate(true);
               // pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
                pDialog.setCancelable(true);
                pDialog.show();

            }
            protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
                ServiceHandler sh = new ServiceHandler();

                // Making a request to url and getting response
                statedata = new ArrayList<HashMap<String, String>>();
                String jsonStr = sh.makeServiceCall(STATE_URL, ServiceHandler.GET);

                Log.d("Response: ", "> " + jsonStr);

                if (jsonStr != null) {
                    try {
                        JSONObject jsonObj = new JSONObject(jsonStr);
                        state_list = jsonObj.getJSONArray(COUNTRY_LIST);

                        // looping through All Contacts
                        for (int i = 0; i < state_list.length(); i++) {
                            JSONObject c = state_list.getJSONObject(i);

                            // creating new HashMap
                            HashMap<String, String> map = new HashMap<String, String>();

                            // adding each child node to HashMap key => value
                              map.put(STATE_SLG, c.getString(STATE_SLG));
                          map.put(STATE_ID, c.getString(STATE_ID));
                            map.put(STATE_NAME,c.getString(STATE_NAME));

                           statedata.add(map);

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    Log.e("ServiceHandler", "Couldn't get any data from the url");
                }

                return statedata;
            }

            protected void onPostExecute(ArrayList<HashMap<String,String>> result) {

                super.onPostExecute(result);
               pDialog.dismiss();

                String[] arrallstates=new String[statedata.size()];
                for(int index=0;index<statedata.size();index++){
                          HashMap<String, String> map=statedata.get(index);
                      arrallstates[index]=map.get(STATE_NAME);
                 }  


                 // pass arrConuntry array to ArrayAdapter<String> constroctor :
                adapterallstates = new ArrayAdapter<String>(MainActivity.this,
                                    android.R.layout.simple_spinner_dropdown_item,
                                                                          arrallstates);
                spstate.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View w) {
                          new AlertDialog.Builder(MainActivity.this)
                          .setTitle("Select")
                          .setAdapter(adapterallstates, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                spstate.setText(adapterallstates.getItem(which).toString());

                                 try {

                                     String n  = state_list.getJSONObject(which).getString("state_slug");


                                    statename=state_list.getJSONObject(which).getString("state_slug");
                                    stnm=state_list.getJSONObject(which).getString(STATE_NAME);

                                     Log.d("Response statenm: ", "> " + statename);

                                     SharedPreferences.Editor editor = sharedpreferences.edit();

                                        editor.putString(States, n);
                                        editor.commit();
                                     new LoadAllStatesCity().execute();

                                    // Toast.makeText(getActivity(), statename, Toast.LENGTH_LONG).show();
                                } catch (JSONException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }

                              dialog.dismiss();
                            }
                          }).create().show();
                        }
                });

            }
     }

【问题讨论】:

  • 你可以写一个文件吗?比在 sp 中存储 json 响应更好?
  • 您只想存储选定的值?还是整个回复?
  • 您面临的具体问题是什么?
  • @RahulTiwari 如果用户选择古吉拉特邦,那么它应该保持选中状态,直到用户更改它..
  • @Droidwala 问题是每次我加载状态名称并选择它..所以我需要加载一次并选择它并使其被选中,直到用户更改它

标签: android json sharedpreferences android-alertdialog


【解决方案1】:

如果你想存储响应,更好的方法是将内容写入文件。如果你只想存储一些值,你可以这样做

SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
 editor.putString("key_from_json", "String_value_from_json");
 editor.putInt("key_from_json","int_value_from_json");
 editor.commit();

【讨论】:

    【解决方案2】:

    您可以使用优先存储整个对象类 gson.jar file -> click here

    然后使用它...

    static public void setPreferenceObject(Context c, Object modal,String key) {
        /**** storing object in preferences  ****/
        SharedPreferences appSharedPrefs = PreferenceManager.getDefaultSharedPreferences(
                c.getApplicationContext());
        Editor prefsEditor = appSharedPrefs.edit();
    
        Gson gson = new Gson();
        String jsonObject = gson.toJson(modal);
        prefsEditor.putString(key, jsonObject);
        prefsEditor.commit();
    
    }
    
    static public Object getPreferenceObjectJson(Context c,String key) {
    
        SharedPreferences appSharedPrefs = PreferenceManager.getDefaultSharedPreferences(
                c.getApplicationContext());
        /**** get user data    *****/
        String json = appSharedPrefs.getString(key, "");
        Gson gson=new Gson();
        User selectedUser=gson.fromJson(json, User.class);
        return  selectedUser;
    }
    

    【讨论】:

      【解决方案3】:

      SharedPreferences 是存储小数据的首选。因此,要保存您的 entire response,最好将其保存到文件中(例如:.bin),如下所示:

       public static synchronized void saveToFileSystem(Context context, Object object, String binFileName) {
              try {
                  String tempPath = context.getFilesDir() + "/" + binFileName + ".bin";
                  File file = new File(tempPath);
                  ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
                  oos.writeObject(object);
                  oos.flush();
                  oos.close();
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      

      为了阅读它,你可以这样做:

      public static synchronized Object readFromFileSystem(Context context, String binFileName) {
              Object obj = new Object();
              try {
                  String tempPath = context.getFilesDir() + "/" + binFileName + ".bin";
                  File file = new File(tempPath);
                  if (file.exists()) {
                      ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
                      obj = ois.readObject();
                      ois.close();
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              }
      
              return obj;
          }
      

      【讨论】:

      • 请解释一下..这个 bin 文件是什么?
      • @learner 它只是一种文件。您可以使用任何其他文件类型。这只是一个例子
      • 您也可以将其转换为jsonStringGson,反之亦然,当检索它时
      【解决方案4】:

      您可以使用共享首选项中的键轻松将 JSON 文件完全保存为字符串变量,并在您打算再次阅读时对其进行解析。

      【讨论】:

        【解决方案5】:

        将 JSON 对象存储到共享首选项的最简单方法是 只需使用 toString

        让 JSONObject 将值添加到 JSONObject 最后保存到首选项
         private void storeDataToPref() {
            SharedPreferences sharedPreferences = getSharedPreferences("localpref", MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("name", "hello");
                jsonObject.put("number", "aaaa");
                android.util.Log.d("response", jsonObject.toString());
                editor.putString("pref_data", jsonObject.toString()).commit();
            } catch (JSONException json) {
        
            }
        }
        

        为了从共享偏好中获取结果,首先将读取的字符串转换为 jsonobject 并获得您想要的值,希望这对您有所帮助,谢谢

        private void getDataFromPref() {
            SharedPreferences sharedPreferences = getSharedPreferences("localpref", MODE_PRIVATE);
            String value = sharedPreferences.getString("pref_data", "");
            try {
                JSONObject jsonObject = new JSONObject(value);
                String name = jsonObject.getString("name");
                String number = jsonObject.getString("number");
                android.util.Log.d("result", name + "...." + number);
            } catch (Exception e) {
        
            }
        }
        

        【讨论】:

          【解决方案6】:

          我会将选定的值存储在 SharedPreferences 中的一个键中。然后,在启动时,您将能够加载 SharedPreferences 以检查您是否已经有一个值(在这种情况下,您可以完全重新加载您的 JSON)

          指南here.

          IMMO,如果您只是在寻找存储值,那么保存文件是没有用的。这就是应该使用 SharedPreferences 的地方:即使您关闭应用程序并重新启动它,它们也会保留。

          【讨论】:

            【解决方案7】:

            状态数据多年不变,因此您可以保留此 json data in assets 并从那里使用它或将其保存在 static map 中。而不是调用 webservice 来获取它。

            为了持久化选定的值,您可以使用SharedPreferences 并在其中存储状态id。下次当您扩充状态列表时,您可以检查您的共享偏好并选择已保存的偏好。

            【讨论】:

            • 你能帮我解决我的问题吗?
            • 你的答案是?
            • 我的意思是在我的代码中我正在获取并在对话框中显示 json 响应
            • 请尝试我的回答。如果您在尝试时遇到问题,请告诉我。
            【解决方案8】:

            基本上你可以检查偏好的值是否被存储。

            你可以这样做 onCreate() 方法:
            检查偏好值是否存在
            如果存在:
            那么不需要进行 AsyncTask 调用
            如果没有:
            然后进行 AsyncTask 调用

            代码:

            String statename = preferences.getString("STATE_NAME<name you gave while committing for first time>,"");
             if(statename!=""){
               //Then directly go inside main activity
            
             }
             else{
            //Make AsyncTask Call
            
             }
            

            【讨论】:

            • 如果第一个用户想要更改怎么办?
            • 对不起,我没听懂?你想说什么?
            • @Lakhan 你的意思是问如何改变用户设置的状态?
            • 然后在 mainactivity 中,您可以为用户提供单击某个按钮或菜单选项的选项,无论哪个是最好的,一旦他单击它,您再次使用上面的代码并在对话框中获取 json 结果和允许他选择它。一旦选择,您更改设置新状态的首选项.. 清除?
            • 是的,但我不能使用另一个额外的按钮或其他东西
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2018-02-06
            • 2017-01-22
            • 2016-01-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-09-20
            相关资源
            最近更新 更多