首先,您应该在 .php 中进行一些更改,如下所示:
$r=mysql_query("select * FROM links",$con);
while($row=mysql_fetch_array($r))
{
$cls[]=$row;
}
print(json_encode($cls));
mysql_close($con);
?>
如果您在运行此脚本时得到一些结果,那么第一步就完成了。然后我们去用Java编写一些代码。
这是我的一个项目的一部分,所以不要只是复制。需要根据您的需要进行一些调整:
public Map<String, String> getTitlesUrls()
{
Map<String,String> TitlesUrl = new HashMap<String,String>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http:/10.0.0.2/yourscript.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e)
{
Log.e("1: log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line);
}
is.close();
result=sb.toString();
}
catch(Exception e)
{
Log.e("2: log_tag", "Error converting result "+e.toString());
}
//parse json data
try
{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++)
{
JSONObject json_data = jArray.getJSONObject(i);
}
JSONObject json_data = jArray.getJSONObject(0);
TitlesUrl.put("Title", String.valueOf(json_data.getString("Title")));
TitlesUrl.put("URL", String.valueOf(json_data.getString("url")));
}
catch(JSONException e)
{
Log.e("3: log_tag", "Error parsing data "+e.toString());
}
return TitlesUrl;
}