我在phpMyAdmin中有一个数据库。我想从表中获取信息,并使用它来填充我的安卓应用程序中的ListView。
我创建了一个PHP文件:
<?php
$host="localhost";
$user="root";
$pass="";
$dbname="ltc";
$con= mysql_connect($host,$user,$pass);
$BD= mysql_select_db($dbname, $con);
$query=mysql_query("select * from posts");
$num=mysql_num_rows($query);
if($num==1)
{
while($list=mysql_fetch_assoc($query))
{
$output=$list;
echo json_encode($output);
}
mysql_close();
}
?>我在安卓系统中创建了一个ListView。如何获取信息并将其放入列表中?
发布于 2013-03-08 23:33:20
假设您的PHP文件输出了一个正确的JSON,下一步将是使用HttpGet调用这个URL来访问这个JSON。这将返回一个响应,即字符串形式的JSON。
您必须解析此响应。你可以使用'gson‘来实现。因此,您可以填充一些列表、对象或数据库,并使用它们来填充您的ListView。
发布于 2013-03-08 23:36:28
您可以使用如下方法调用您的php页面:
public static String getWebData(String url) {
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpGet httpgett = null;
httpgett = new HttpGet(url);
String result="";
try {
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httpgett);
int status = response.getStatusLine().getStatusCode();
result = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
System.out.println("--->" + "ClientProtocolException" + e.getMessage());
return "";
} catch (IOException e) {
// TODO Auto-generated catch block
return "";
} catch (Exception e) {
// TODO Auto-generated catch block
return "";
}
return result;
}一旦你有了数据,你就可以把它放到你的ListView中
https://stackoverflow.com/questions/15297256
复制相似问题