从服务器获取单个值并保存到 sharedpreferences
Getting single value from server and saving to sharedpreferences
我正在尝试获取这个{"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");'
您正在生成的字符串中获取数组。但是在您的代码中,您将其作为 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();
}
编码愉快..!!
我正在尝试获取这个{"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");'
您正在生成的字符串中获取数组。但是在您的代码中,您将其作为 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();
}
编码愉快..!!