我正在开发一个基于网络服务的安卓应用程序。如何根据单击的项目运行查询(使用 php 和 MySQL 的服务器)并从 web 获取结果。我还想将一些值显示为列表(列表布局)。有没有办法做到这一点?
最佳答案
您要做的是开发一个为您的 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":"比勒费尔德","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");
}
}
Web 请求应该在另一个线程中运行,因为它可能是一个耗时的过程。所以需要处理AsyncTask。以下是一些资源:
Painless Threading Multithreading for performance Hello Android Tutorial
关于php - 如何获取Android应用程序的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4245308/