2017-03-08 110 views
0

我想從Response中保存用戶類變量的值。 不幸的是,我不能。如何從Volley的onResponse中返回值?

請幫助我。

這是代碼JSONObjectRequest

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, 
    jsonURLFull, new Response.Listener<JSONObject>() { 

     @Override 
     public void onResponse(JSONObject response) { 
      Log.d(ActivityLogin.class.getSimpleName(), response.toString()); 

      try { 
       User userClass = new User(); 

       JSONObject jsonUser = response.getJSONObject("user"); 
       userClass.id = jsonUser.getInt("id"); 
       userClass.name = jsonUser.getString("email"); 
       userClass.email = jsonUser.getString("email"); 

      } catch (JSONException e) { 
       e.printStackTrace(); 
       Toast.makeText(getApplicationContext(), 
       "Error: " + e.getMessage(), 
       Toast.LENGTH_LONG).show(); 
      } 
      hidepDialog(); 
     } 
    }, new Response.ErrorListener() { 

     @Override 
     public void onErrorResponse(VolleyError error) { 
      VolleyLog.d(ActivityLogin.class.getSimpleName(), "Error: " + error.getMessage()); 
      Toast.makeText(getApplicationContext(), 
      error.getMessage(), Toast.LENGTH_SHORT).show(); 
      hidepDialog(); 
     } 
    }); 
    AppController.getInstance().addToRequestQueue(jsonObjReq); 

這是用戶等級:

public class User { 

    public int id; 
    public String name; 
    public String email; 

} 

這是API的JSON:

{"user":{"id":12,"name":"test_name","email":"[email protected]",}} 
+0

請申請二傳手吸氣用戶類,因爲如果你不做出it.It將垃圾收集。 –

+0

使用Setter Getter,然後傳遞您的User類對象「userClass」,其中 要使用這些值。 – Chandan

回答

0

兩點:

1.you parse emailname attribude。

userClass.name = jsonUser.getString("name"); 

2.您的JSON數據是錯誤的,由於最後','

{"user":{"id":12,"name":"test_name","email":"[email protected]"}}