2013-03-08 151 views
0

我在phpMyAdmin中有一個數據庫。我想從表中獲取信息並使用它在我的Android應用中填充ListView從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(); 
    } 
?> 

我在Android中創建了一個ListView。我如何獲得這些信息並將其放入列表中?

回答

0

假設你的PHP文件輸出正確的JSON;您的下一步將調用URL以使用HttpGet訪問此JSON。這會給你一個迴應,這是一個字符串的JSON。

您必須解析此響應。你可以使用'gson'。 因此你可以填充一些列表,對象或數據庫,並用它來填充你的ListView。

0

您可以通過方法來調用你的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