我想获取保存在 mysql Db 中的图像的标题,我发现您必须通过 Json 执行此操作,现在我有一个 .php 文件:
<?php
mysql_connect("localhost","xx","xx");
mysql_select_db("xx");
$q=mysql_query("SELECT title FROM field_title");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();
?>
它输出如下:
[{"title":"titleone"},{"title":"titletwo"},{"title":"titlethree"}]
但是现在我被卡住了,我想把这些标题放在一个简单的数组列表中,但我不知道如何在输出数据和数组列表本身之间建立联系。
ArrayList<String> list = new ArrayList<String>();
for (??) {
list.add(string);
}
是否有可能以一种简单的方式做到这一点?我看过这个例子,但我似乎无法弄清楚:
http://www.helloandroid.com/tutorials/connecting-mysql-database
谢谢。
编辑
好的,我能够通过 httppost 建立连接:但是当我运行我的应用程序时,它从一开始就崩溃了......
// http post
InputStream inputStream = null;
String result = null;
try {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://www.webmention.com/bosshunting.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
ArrayList imageUrls = new ArrayList();
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
imageUrls.add(json_data.getString("url"));
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
不知道我是否以正确的方式将项目添加到数组中。我猜不是?我尝试获取 titleone、titletwo、titlethree 的 arraylist imageUrls