我有一个带有一个唯一表的 MySQL 数据库:geopoints,它有 3 列:id、lat和long,并且该表已经填满了 4 个条目, 4 个 lat 和 long 值(1E6 因为它用于地图视图) .
我的目标是使用生成 json 数组的 php 脚本和 httpPost 等在地图视图上动态标记所有这 4 个地理点...
这是我到目前为止的代码:
getjson = (Button) findViewById(R.id.button1);
getjson.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();//Whats this for?
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
"http://????????.com/????/getGeopoints.php");
HttpResponse response = httpclient.execute(httpPost);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error connecting to http " + e.toString());
}
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
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 " + e.toString());
}
try {
jArray = new JSONArray(result);
for (int i = 0; i <= jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag", "id: " + json_data.getInt("id")
+ ", latitude: " + json_data.getInt("lat")
+ ", longitude: " + json_data.getInt("long"));
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
});
这是php文件:
<?php
mysql_connect("?????.com", "username", "password");
mysql_select_db("database_name");
$q = mysql_query("SELECT * FROM geopoints");
while ($e = mysql_fetch_assoc($q))
$output[] = $e;
print(json_encode($output));
mysql_close();
?>
我让这个文件正常运行,因为当我在浏览器上输入 url 时,它会生成包含我想要的确切信息的确切 json 数组。只是觉得我不明白,HttpEntity 是干什么用的?因为我跟进了一个教程,并且在那里它使用了一个包含信息的数组来从数据库中过滤,因为我不想过滤任何信息(我想要所有数据库表条目,而不仅仅是一个或两个)我刚刚离开它是空白的。
我的代码有什么问题?我在 logcat 中得到的错误是所有捕获消息“11-29 12:47:29.662: E/log_tag(898): Error connected to http Http android.os.NetworkOnMainThreadException”。