java - 如何从 URL 访问我的应用程序中的 JSON 数据?
问题描述
在这个 URL 中,我有一些 Json 数据。如何使用该 URL 将该数据获取到我的 andorid 应用程序。
我在谷歌上看到了参考资料。但没有得到解决方案。
我是 Andorid 的新手。
请帮我。
解决方案
做这个 :
步骤 - 1 在您的 gradle 中导入 volley 库:
实施 'com.android.volley:volley:1.1.0'
然后在java中写下这段代码:
ProgressDialog progressDialog; // define globally
public void getLocations(){ //call this method onCreate or on OnClickEvent
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Feteching....");
progressDialog.setCancelable(false);
progressDialog.show();
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest request = new StringRequest(Request.Method.GET, "YOUR URL", new Response.Listener<String>() { //you can change here POST/GET
@Override
public void onResponse(String response) {
progressDialog.dismiss();
System.out.println("Response : " + response);
try {
JSONObject jsonResponse = new JSONObject(response);
JSONArray locations = jsonResponse.getJSONArray("LOCATIONS");
for (int i = 0; i < locations.length(); i++) {
JSONObject jsonObject = locations.getJSONObject(i);
String name = jSONObject.getString("name");
String lat = jSONObject.getString("lat");
String lng = jSONObject.getString("lng");
System.out.println("LOCATIONS : " + name +"," + lat + "," + lng);
// check this print in logcats
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("VolloError " + error);
progressDialog.dismiss();
Toast.makeText(YourActivity.this, "Network Connection Error...!!!", Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
// use params when you are using POST method
return params;
}
};
request.setRetryPolicy(new RetryPolicy() {
@Override
public int getCurrentTimeout() {
return 50000;
}
@Override
public int getCurrentRetryCount() {
return 50000;
}
@Override
public void retry(VolleyError error) throws VolleyError {
}
});
queue.add(request);
}
推荐阅读
- excel - 如何忽略 Excel 查询错误
- javascript - 在表格 AngularJS 的列中插入指令
- php - Laravel 5.6 会话不重定向到视图
- python - 无法导入 Keras 库
- regex - Regular expression to match all but some specific lines of logs
- html - Jenkins Active Choices Reactive Reference Parameter 不适用于格式化的 HTML 输入文本框
- python - 使用新代码更新 Docker 容器
- objective-c - 目标 c 中的 XCTKVOExpectation 使用示例
- vba - 用于组合列单元格中不同值的 Excel 宏
- regex - 在使用正则表达式的行之前删除