gpt4 book ai didi

java - Volley 在第一次调用方法时返回 null

转载 作者:搜寻专家 更新时间:2023-11-01 09:27:08 25 4
gpt4 key购买 nike

我正在尝试使用 volley 从服务器检索数据,但是当我第一次调用此方法时,我从服务器获得了响应,但该方法返回了 null。如果我第二次调用它,我会得到最后的响应。

 public String retrieveDataFromServer(String url, String param, final String token){


StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try{
data = new JSONObject(response).toString();
}catch (Exception e){}
//Toast.makeText(getApplicationContext(), "wow" + data, Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
try{
data = new JSONObject(error.toString()).toString();
}catch (Exception e){}
//Toast.makeText(getApplicationContext(), "" +data, Toast.LENGTH_SHORT).show();
}
}) {
/**
* Passing some request headers
*/
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
String bearer = "Bearer ".concat(token);
Map<String, String> headersSys = super.getHeaders();

HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
//headers.put("token", token);

headersSys.remove("Authorization");
headers.put("Authorization", bearer);
headers.putAll(headersSys);
return headers;
}
};
// Adding request to request queue
addToRequestQueue(stringRequest);
//Toast.makeText(getApplicationContext(), "wow" + data, Toast.LENGTH_SHORT).show();

return data;
}

如何在第一次调用方法时获得响应?

最佳答案

您可以使用回调来返回 Volley 响应:

public void retrieveDataFromServer(final VolleyCallback callback) {
StringRequest strReq = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
callback.onSuccess(response);
}
}
}}

创建接口(interface):

public interface VolleyCallback{
void onSuccess(String response);
}

并从 Activity 中获取结果:

String yourString = "";
@override
public void onResume() {
super.onResume();
retrieveDataFromServer(new VolleyCallback(){
@Override
public void onSuccess(String response){
//Get result from here
yourString = response;
}
});
}

关于java - Volley 在第一次调用方法时返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49757340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com