【发布时间】:2023-04-09 10:45:01
【问题描述】:
我正在开发一个基于 Web 服务的 android 应用程序。如何根据单击的项目运行查询(使用 php 和 MySQL 的服务器)并从网络获取结果。我还想将一些值显示为列表(列表布局)。有没有办法做到这一点?
【问题讨论】:
我正在开发一个基于 Web 服务的 android 应用程序。如何根据单击的项目运行查询(使用 php 和 MySQL 的服务器)并从网络获取结果。我还想将一些值显示为列表(列表布局)。有没有办法做到这一点?
【问题讨论】:
您要做的是开发一个为您的 android 应用程序提供数据的 rest api。例如。你的网站有一些你想在你的应用程序中使用的内容,然后你可以编写一个 php 脚本,它只以特定格式返回该数据。
例如mysite.net/rest/fetchAllLocations.php?maybe_some_parameters
这将返回位置,例如json 格式,这是一个示例:
[{"id":1,"shop_lng":8.5317153930664,"shop_lat":52.024803161621,"shop_zipcode":33602,"shop_city":"Bielefeld","shop_street":"Arndtstra\u00dfe","shop_snumber" :3,"shop_name":"M\u00fcller","shop_desc":"Kaufhaus"}]
这里是一个rest api请求的例子:
http://shoqproject.supervisionbielefeld.de/public/gateway/gateway/get-shops-by-city/city/Bielefeld
因此,当您设置好 rest api 后,您就可以使用您的 android 手机接收该数据。我使用静态方法来获取这些数据:
public class JsonGrabber{
public static JSONArray receiveData(){
String url = "your url";
String result = "";
DefaultHttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet(url);
HttpResponse res = null;
try {
res = client.execute(method);
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try{
InputStream is = res.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
JSONArray jArray = null;
try{
jArray = new JSONArray(result);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
}
就是这样,一旦你有了 json 格式的数据,你只需要解析它:
JSONArray 测试 = (JSONArray) JsonGrabber.receiveData()
try {
for(int i=0;i<test.length();i++){
JSONObject json_data = test.getJSONObject(i);
int id = json_data.getInt("id");
}
}
网络请求应该在另一个线程中运行,因为它可能是一个耗时的过程。所以你需要处理AsyncTask。以下是一些资源:
Painless Threading Multithreading for performance Hello Android Tutorial
【讨论】: