【问题标题】:Getting single value from server and saving to sharedpreferences从服务器获取单个值并保存到 sharedpreferences
【发布时间】:2016-02-03 05:26:24
【问题描述】:

我想得到这个{"status": [{"RegistrationID":"4"}]}
来自服务器的值并将该值保存在 sharedpreferences 中,但这会引发 nullpointerexception 这是我正在尝试的代码...

        JSONObject o = new JSONObject(result);
        JSONObject obj = o.optJSONObject("status");
        String uid = obj.optString("RegistrationID");
        Log.e("RegistrationID", uid);
        AvailableItems  set = new AvailableItems();

        set.sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        String value = set.sp.getString("RegistrationID", uid);
        SharedPreferences.Editor editor = set.sp.edit();
        editor.putString("first", value);
        editor.commit();

此行中显示异常 `String uid = obj.optString("RegistrationID");'

【问题讨论】:

  • @hardik vyas 现在检查一下......
  • “结果”是什么类型的变量?它是字符串还是任何其他格式
  • @Ragu Swaminathan 是的结果是字符串类型

标签: string sharedpreferences jsonobject


【解决方案1】:

您在结果字符串中得到数组。但是在您的代码中,您将其作为 JsonObject 获取。 “RegistrationID”以数组形式出现。 试试下面的代码。

try {
      JSONObject o = new JSONObject(result);
      JSONArray obj = o.getJSONArray("status");
      JSONObject jsonobj = obj.getJSONObject(0);
      Log.e("RegistrationID", jsonobj.getString("RegistrationID"));
    } catch (Exception e) {
      e.printStackTrace();
    }

编码愉快..!!

【讨论】:

  • 答案是 Ragu 但现在在 AvailableItems set = new AvailableItems();这显示在 logcat RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
  • 这对我来说是另一个问题。这个对你有用吗?如果是,请接受。
  • 现在请提出任何解决该问题的方法,我也是 android 新手
  • 你能不能发帖是一个单独的问题。因为按照 SO,每个答案一个问题。如果您想问另一个问题,请将其发布为另一个问题。对不起..
  • 请检查我在这里发布了一个新问题stackoverflow.com/questions/35173611/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多