gpt4 book ai didi

android - Volley 获取请求 : onResponse is never called

转载 作者:太空狗 更新时间:2023-10-29 13:53:01 24 4
gpt4 key购买 nike

我是 Android Studio 的新手,我正在尝试使用 Volley 构建一个获取请求,服务器响应是一个 JsonObject。我用断点测试了代码,但我想知道为什么我不跳转到 onResponse 或为什么它不起作用。

这是我的 Get 方法代码:

public Account GetJsonObject(String urlExtension, String name, Context context) {
String baseURL = "myurl.com/api";
baseURL += urlExtension + "/" + name;
// url will look like this: myurl.com/api/user/"username"

final Account user = new Account("","");
//Account(name, email)
RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(context);

JsonObjectRequest jsonObject = new JsonObjectRequest(Request.Method.GET, baseURL,null,
new Response.Listener<JSONObject>() {

// Takes the response from the JSON request
@Override
public void onResponse(JSONObject response) {
try {
JSONObject obj = response.getJSONObject("userObject");

String username = obj.getString("Username");
String email = obj.getString("Email");
user.setUsername(username);
user.setEmail(email);

}
catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});


requestQueue.add(jsonObject);
return user;
}

最佳答案

正如@GVillavani82 所评论的,您的onErrorResponse() 方法体是空的。尝试像这样记录错误

 new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("ERROR", "Error occurred ", error);
}
}

确保您在 AndroidManifest.xml 文件中设置了以下权限并且 api URL 正确。

<uses-permission android:name="android.permission.INTERNET"/>

JsonObjectRequest类返回异步网络调用类。像下面这样修改您的代码。

// remove Account return type and use void

public void GetJsonObject(String urlExtension, String name, Context context) {
....
.... // other stuffs
....

JsonObjectRequest jsonObject = new JsonObjectRequest(Request.Method.GET, baseURL,null,
new Response.Listener<JSONObject>() {

// Takes the response from the JSON request
@Override
public void onResponse(JSONObject response) {

processResponse(response); // call to method

}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("ERROR", "Error occurred ", error);
}
});

requestQueue.add(jsonObject);
}

现在创建另一个如下所示的方法

private void processResponse(JSONObject response) {
try {
final Account user = new Account("","");
JSONObject obj = response.getJSONObject("userObject");

String username = obj.getString("Username");
String email = obj.getString("Email");
user.setUsername(username);
user.setEmail(email);

} catch (JSONException e) {
e.printStackTrace();
}
}

关于android - Volley 获取请求 : onResponse is never called,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43568696/

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