因此,我试图在AndroidStudio项目中使用Volley从本地json服务器(REST API)获取数据库,但似乎无济于事。它甚至都没有超过第一行代码,调试器似乎也没有帮助。
我一直看到的是,当它击中new Response.Listener<JSONObject>(...)
时,它只是跳过所有代码,我的调试器向我显示的下一个东西是最后一个闭合手镯,什么都没发生,没有任何错误或异常,我发现了。还是这只是调试器,我无法在调试中覆盖作为参数指定的类?
注:localhost运行正常,甚至可以使用邮递员发送请求。甚至使用Unirest而不是Volley进行了尝试。
在Android清单中:
<uses-permission android:name="android.permission.INTERNET"/>
代码段:
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
// ...
private void parseJSON() {
String url = "http://localhost:3000/db";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArrayProjects = response.getJSONArray("projects");
for (int i = 0; i < jsonArrayProjects.length(); i++) {
JSONObject projectJO = jsonArrayProjects.getJSONObject(i);
Log.d("PROJEKT-Name: ", projectJO.getString("name")); // just printing result to see if it works
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
requestQueue.add(request);
}
对我来说,似乎更像是无法访问服务器的问题。任何帮助表示赞赏!
编辑:将http://localhost:3000/db
更改为http://10.0.2.2:3000/db
现在似乎可以使用了,我可以在模拟器的镶边中打开服务器,但仍然无法检索数据。
只需确保这不是我的JSON中的小错误:这应该可以,对吧?
{
"projects": [
{
"id": 1,
"name": "Seminararbeit Geschichte",
"description": "Der Wilde Westen",
"comments": [],
"appointments": [],
"handlers": [],
"processors": [],
"type": "SEMINARARBEIT"
},
{
"id": 2,
"name": "Seminararbeit Soziologie",
"description": "Die Gesellschaft",
"comments": [],
"appointments": [],
"handlers": [],
"processors": [],
"type": "BACHELORARBEIT"
}
]
}
您不应该将localhost用于移动应用程序,因为它将在单独的设备(真实或虚拟)中运行,而不是在您的计算机上运行
1)从您的计算机创建一个接入点,或者使用一个IP地址连接到家庭WiFi并将其写入您的代码中
private void parseJSON() {
String ip = " your_ip_address_here ";
String url = "http://"+ip+":3000/db";
...
2)从运行该应用程序的设备,使用来自同一网络的IP地址连接到WiFi或接入点
然后您可以成功运行它