2016-02-03 22 views
-1

我試圖從服務器獲取該{"status": [{"RegistrationID":"4"}]}
值並保存在sharedpreferences該值但被拋出NullPointerException異常,這是我努力的代碼...正在從服務器單個值並將其保存到sharedpreferences

 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」);'

+0

@hardik vyas現在檢查.... –

+0

亞其右... –

+0

什麼類型的變量是'結果'?它是一個字符串或任何其他格式 –

回答

0

你正在得到的字符串中的數組。但在你的代碼中,你將它作爲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(); 
    } 

快樂編碼.. !!

+0

回答拉古,但現在有另一個問題在行AvailableItems set = new AvailableItems();這在logcat RuntimeException中顯示:不能在線程內創建沒有調用Looper.prepare() –

+0

的處理程序,這對我來說是另一個問題。這個是否適合你?如果是的話,請接受它。 –

+0

現在請爲這個問題提出任何解決方案,我也是新的Android的 –

相關問題