2017-09-01 64 views
0

我想使用Android Volley發佈數據並接收Json響應。我有下面的代碼,我似乎無法看到錯誤的位置,因爲我在網上找到的所有代碼都與此類似。我附上了android給出的消息的截圖。使用Android Volley發佈並獲取Json數據

public String rBody = null;//Is Initialized also tried (String)null 

    public void loadSharedPreferencesData(){ 
    SharedPreferences sharedPre = getSharedPreferences("userinfo", Context.MODE_PRIVATE); 
    final String loggedStatus = sharedPre.getString("isLogged", "0"); 
    final String loggedUserId = sharedPre.getString("userId", "0"); 

    String loginUrl   = "http://dataUrl[![enter image description here][1]][1]/startvapp-ci/appdata/getsession/"; 

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, loginUrl, rBody , 
      new Response.Listener<JSONObject>() { 
       @Override 
       public void onResponse(JSONObject response){ 
        //returnResponse = response.toString(); 
        //Toast.makeText(getApplicationContext(), returnResponse , Toast.LENGTH_LONG).show(); 
        System.out.println(response); 
        //Toast.makeText(getApplicationContext(), "Error in Response" , Toast.LENGTH_LONG).show(); 
       } 
      }, 
      new Response.ErrorListener() { 
       @Override 
       public void onErrorResponse(VolleyError error) { 
        //Save this to some global variable 
        Toast.makeText(getApplicationContext(), "Error in Response" , Toast.LENGTH_LONG).show(); 
       } 
      } 
    ){ 
     @Override 
     protected Map<String,String> getParams(){ 
      Map<String,String> params = new HashMap<String, String>(); 
      params.put(KEY_SESS_USERID,loggedUserId); 
      params.put(KEY_SESS_STATUS,loggedStatus); 
      return params; 
     } 
    }; 
    MySingleton.getInstance(this.getApplicationContext()).addToRequestQueue(jsonObjectRequest); 
} 

Android Studio Error

回答

3

該錯誤消息指出該jsonRequest說法是錯誤的類型。它期望JSONObject,但您提供StringrBody變量)。

如果rBody字符串是有效的JSON字符串,那麼您可以簡單地將該字符串傳遞給JSONObject構造函數。然後將此JSONObject傳遞給JsonObjectRequest構造函數而不是rBody

JSONObject jsonRequest = new JSONObject(rBody); 

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
     Request.Method.POST, loginUrl, jsonRequest, 
     new Response.Listener<JSONObject>() { 
      // Response Listener code here 
     }, 
     new Response.ErrorListener() { 
      // Error Listener code here 
     }); 
+0

我已經這樣做了,錯誤消失了。但是,現在我得到錯誤的迴應。可能是什麼原因。我也需要rBody或者我可以只有JSONObject jsonRequest = new JSONObject(); – jmsiox

+0

我已經設法使用你的答案做這個工作。謝謝。 – jmsiox

+0

@jmsiox您需要發佈錯誤信息以便我提供幫助。如果你想要*發佈*數據;那麼是的,你需要有一個身體。如果你沒有發佈數據,那麼你可以傳遞'null'作爲第三個參數,而不是創建一個空的'JSONObject()'。 – Bryan

相關問題