2012-07-05 174 views
1

Im很難從我的本地主機檢索數據。我使用xampp。我想要的是顯示從本地主機到Android手機列表視圖的數據。這是我在網上找到的關於localhost和android的基本代碼。這裏是片段:無法連接到本地主機使用Android手機調試

p

ublic class Database_demo extends ListActivity { 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState); 

     String result = null; 
     InputStream is = null; 
     StringBuilder sb = null; 
     ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
     List<String> r = new ArrayList<String>(); 

     try{ 

     //http post 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost("http://10.0.2.2/android_connect3/"); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
     HttpResponse response = httpclient.execute(httppost); 
     HttpEntity entity = response.getEntity(); 
     is = entity.getContent(); 
     } 
     catch(Exception e){ 
      Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show(); 
     } 

     //Convert response to string 
     try 
     { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8")); 

      sb = new StringBuilder(); 

      String line = null; 

      while ((line = reader.readLine()) != null) 
      { 
      sb.append(line + "\n"); 
      } 

      is.close(); 

      result = sb.toString(); 
     } 
     catch(Exception e) 
     { 
      Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show(); 
     } 
     //END Convert response to string 
     try{ 
       JSONArray jArray = new JSONArray(result); 
       JSONObject json_data=null; 
       for(int i=0;i<jArray.length();i++) 
       { 
        json_data = jArray.getJSONObject(i); 
        r.add(json_data.getString("reg")); 
       } 
       setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, r)); 
      } 
      catch(JSONException e1){ 
       Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show(); 
      } catch (ParseException e1) { 
       Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show(); 
     } 

    } 
} 

,這裏是我的PHP文件:

<?php 
mysql_connect('localhost','root',''); 
mysql_select_db('android_sql'); 
$sql = "select * from reg"; 
$query = mysql_query($sql); 

while($row = mysql_fetch_assoc($query)){ 
$output[] = $row; 
} 
print (json_encode($output)); 
mysql_close(); 


?> 

這是我的例外: http://pastebin.com/QZkfG0bp

+0

即時得到從本地主機 – thenewbie 2012-07-06 02:54:18

回答

1

我得到了它。這裏是我如何做。

InputStream is; 
    String result; 

    StringBuilder sb; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 

    } 

我宣佈他們爲全球和刪除空值ASIGN他們

0

你必須檢查該行

HttpPost httppost = new HttpPost("http://10.0.2.2/android_connect3/"); 

變化

HttpPost httppost = new HttpPost("http://10.0.2.2/android_connect3/your_php_file_name"); 
+0

我已經做到這一點的價值。這是行不通的.. – thenewbie 2012-07-06 02:35:27