未访问Android SharedPreference JSON

时间:2018-06-06 21:45:09

标签: android

我正在使用排球向雅虎的天气API发送http请求,如下所示:

        public Object requestData(String url) {
        final RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        JsonObjectRequest objectRequest = new JsonObjectRequest(
                Request.Method.GET,
                url,
                null,
                new Response.Listener < JSONObject > () {
                    @Override
                    public void onResponse(JSONObject response) {
                     String responseList = response.toString();
                   cityList.edit().putString(String.valueOf(i), responseList);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }
        );
        requestQueue.add(objectRequest);
        return null;
    }

正如您所看到的,我将响应放在我声明为&#34; citylist&#34;的共享偏好中。 :

      cityList = getSharedPreferences(String.valueOf(i), MODE_PRIVATE);

然后我在共享偏好中访问此响应,如下所示:

       String mResponse = cityList.getString(String.valueOf(i), "");
                Log.d("log", mResponse);

                try {
                    JSONObject jsonObj = new JSONObject(mResponse);
                    JSONObject response = jsonObj.getJSONObject("query");
                    createdCity.temperature = response.optJSONObject("results").optJSONObject("channel").optJSONObject("item").optJSONObject("condition").getInt("temp");
                    createdCity.conditions = response.optJSONObject("results").optJSONObject("channel").optJSONObject("item").optJSONObject("condition").getString("text");
                    createdCity.town = response.optJSONObject("results").optJSONObject("channel").optJSONObject("location").getString("city");
                    createdCity.country = response.optJSONObject("results").optJSONObject("channel").optJSONObject("location").getString("country");
                    createdCity.state = response.optJSONObject("results").optJSONObject("channel").optJSONObject("location").getString("region");
                   Log.d("log", String.valueOf(createdCity.town));
                    cities.add(createdCity);
                    addMenuItemInNavMenuDrawer();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

问题在于&#34; log&#34;不输出任何东西。我从logcat获得的唯一信息是:

org.json.JSONException: End of input at character 0 of 

我该如何解决我的问题?有没有更好的方法呢?

1 个答案:

答案 0 :(得分:1)

您是否在编辑首选项后提交?根据您的回复,您也可以使用apply(),因为它可以异步执行。

如果您确定提交不会影响主线程,则可以使用cityList.commit()或安全使用cityList.apply()。但是您需要执行这两个中的任何一个,否则更改不会写入磁盘,这是您无法检索数据的原因。

此链接应该有所帮助: https://developer.android.com/training/data-storage/shared-preferences#java