[英]How can I return value from function onResponse of Volley?
public class getString {
String tag_string_req = "string_raq";
String url = "http://10.0.2.2/eat/locations/index.json";
String result="";
public String get_String() {
StringRequest strReq = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
result=response;
System.out.println(response);
;
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
System.out.println(volleyError.getMessage());
}
});
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
return result;
}}
我會構建一個 getString 對象並在其他字段中調用 get_String 。 但似乎很難從 onResponse 中得到結果。 我知道它不能以目前的方式工作。 誰能幫我解決這個問題?
你想像這樣使用回調接口:
public void getString(final VolleyCallback callback) {
StringRequest strReq = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
... // (optionally) some manipulation of the response
callback.onSuccess(response);
}
}...
}}
其中回調定義為
public interface VolleyCallback{
void onSuccess(String result);
}
活動中的示例代碼:
public void onResume(){
super.onResume();
getString(new VolleyCallback(){
@Override
public void onSuccess(String result){
... //do stuff here
}
});
}
您還可以使VolleyCallback
更加健壯,如果您想進行處理,可以使用泛型類型,或者添加start()
、 failed(Exception e)
、 complete()
等方法來進行更細粒度的狀態檢查。
請記住,這是一個異步調用,因此當您返回結果(在success()
)時,您必須更新視圖等。
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val rootView = inflater.inflate(R.layout.mission_fragment_list, container, false)
val recycler = rootView.findViewById(R.id.list) as RecyclerView
GlobalScope.async {
val queue = Volley.newRequestQueue(context)
val gson = Gson()
val url = "YPUR_API"
val stringRequest = StringRequest(
Request.Method.GET, url,
Response.Listener<String> { response ->
recycler.layoutManager = LinearLayoutManager(context)
val listType: Type = object : TypeToken<MutableList<MissionModel>?>() {}.type
val data: MutableList<MissionModel> = gson.fromJson(response, listType)
recycler.adapter = MissionAdapter(data)
},
Response.ErrorListener { error ->
error.printStackTrace()
})
queue.add(stringRequest)
}
return rootView
}
簡單的代碼。 你需要添加依賴實現 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.1'
正如 wblaschko 提到的一個非常好的解決方案所提到的,我理解這個解決方案對於那些經驗較少的人來說可能會有點混亂。 在 wblaschko 的解決方案之上我編輯的解決方案下方:
VolleyCallback.java(接口)
public interface VolleyCallback {
void onSuccess(String result);
void onError(String result);
}
我做了一個 HTTPRequest 類來保持干凈。
HTTPReq.java (類)
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
public class HTTPReq {
public static StringRequest getRequest(String path, final VolleyCallback callback) {
// Instantiate the RequestQueue.
String url = "https:// **FILL HERE BASE API URL** /" + path;
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
callback.onSuccess(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
callback.onError(error.toString());
}
});
return stringRequest;
}
}
最后,在活動中,您要實現以下代碼:
創建一個全局變量:
private RequestQueue mQueue;
之后,在活動的 onCreate 函數中應用 VolleyRequestQue:
mQueue = Volley.newRequestQueue(this);
最后,實際執行 API 請求並捕獲響應的函數:
mQueue.add(HTTPReq.getRequest( **FILL WITH PATH AND/OR PARAMS**, new VolleyCallback() {
@Override
public void onSuccess(String result) {
System.out.println(result);
}
@Override
public void onError(String result) {
System.out.println(result);
}
}));
希望這更清楚。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.