我需要使用Volley請求將一些數據從遠程服務器返回到我的應用程序,但經過一段時間測試後,我無法使其工作。方法返回值但未正確傳遞值
我有一個看起來像這樣的代碼:
String recipientUsername = foo;
picture = retrievedPicture(recipientUsername);
Log.i(TAG, "String picture: " + picture);
recipientPicture = (NetworkImageView) findViewById(R.id.chat_image_circle_pic);
recipientPicture.setImageUrl(picture, imageLoader);
所以picture
全局聲明來檢索與排球內的方法的價值。在我的日誌時,上面的紋路讀這個樣子的:
I/ChatActivity: String picture: null
它得到令人困惑的方法本身實際上是返回的東西。該方法是這樣的:
public String retrievedPicture(final String username) {
// Tag used to cancel request
String tag_string_req = "req_update_user";
StringRequest stringRequest = new StringRequest(Request.Method.POST,
AppConfig.URL_RETRIEVE, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "User is retrieving on MySQL: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// Do no changes on SQLite at the moment
JSONObject userObj = jObj.getJSONObject("user");
picture = userObj.getString("picture");
Log.d(TAG, "Picture retrieved from MySQL: " + picture);
} else {
// Error occurred in updating user's data. Get the error message from php node:
String errorMsg = jObj.getString("error_msg");
Log.e(TAG, errorMsg);
//Toast.makeText(getActivity(), errorMsg, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error in retrieving user's data: " + error);
}
}) {
@Override
protected Map<String, String> getParams() {
// Posting the params to php (nodes, data to be changed)
Map<String, String> params = new HashMap<>();
params.put("tag", "retrievepic");
params.put("username", username);
return params;
}
};
// Adding request to the request queue
AppController.getInstance().addToRequestQueue(stringRequest, tag_string_req);
return picture;
}
和日誌表明,該方法不工作:
D/ChatActivity: User is retrieving on MySQL: {"tag":"retrievepic","error":false,"uid":19,"user":{"username":"test07","picture":"http:\/\/192.168.0.3\/worka\/uploads\/test07_05112015_155304.jpg"}}
D/ChatActivity: Picture retrieved from MySQL: http://192.168.0.3/worka/uploads/test07_05112015_155304.jpg
所以我可以猜測的是,我不是從法的try catch塊遞東西。如果是這樣,我能做些什麼來正確傳遞值? try catch塊已經嵌套在一個似乎固定的void方法中。我真的希望有這樣的解決方案,所以我可以把這個方法變成一個實用程序類。感謝閱讀傢伙!
請在下面閱讀我的答案http://stackoverflow.com/questions/33535435/how-to-create-a-proper-volley-listener-for-cross-class-volley-method-calling/33535554# 33535554 – BNK