我有一個Volley請求,我試圖將結果設置在一個變量中,但是我得到錯誤「Variable'stuff'從內部類訪問,需要聲明最後。」問題是,一旦我聲明它是最終的,我不允許設置變量等於響應(就像我試圖在try塊中)。我已經環顧四周討論這個問題的其他問題,但沒有一個真正有助於我的情況。 下面是代碼:將數據從Android Volley設置爲變量
public ArrayList getStuff() {
ArrayList<JSONObject> stuff;
new Thread(new Runnable() {
@Override
public void run() {
// Instantiate the RequestQueue.
RequestQueue queue = MySingleton.getInstance(getApplicationContext()).getRequestQueue();
String url ="http://localhost:6000/stuff";
RequestFuture<String> future = RequestFuture.newFuture();
// Testing out blocking
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, future, future);
// Add the request to the RequestQueue.
queue.add(stringRequest);
try {
String response = future.get(30, TimeUnit.SECONDS);
stuff = response;
Log.i("tutors after blocked: ", tutors);
} catch(InterruptedException e) {
e.printStackTrace();
} catch(ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
}
}).start();
// I want to be able to return 'stuff' here
return stuff;
}
然後,你必須將其聲明爲final.But你會得到一個空的ArrayList returned.Cause當它返回時,新線程仍在運行和我以前不獲取數據呢。 – xiaoyuan
試試這個'final ArrayList stuff;' –
ken
對不起,我應該提到這個,但是當我聲明它是final時,我不允許設置stuff = response(在try塊中)。這是我面臨的問題。我將編輯帖子以包含該信息。 – ProjectProgramAMark