2013-12-19 92 views
0

這裏是代碼,但它不能得到json數據,雖然瀏覽器顯示json數據時,我打開它爲什麼?php代碼工作正常,但當在Android正試圖把它拿來都說我取空我的android應用程序不geting從服務器json數據

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    StrictMode.enableDefaults(); 
    resultview=(TextView)findViewById(R.id.resulttext); 
    getdata(); 

} 

public void getdata() 
{ 
    String result=null; 
    InputStream inputstream=null; 
    try{ 
     HttpClient httpclient=new DefaultHttpClient(); 
     HttpPost httppost=new HttpPost("http://127.0.0.1/getallcustomers.php"); 
     HttpResponse response=httpclient.execute(httppost); 
     HttpEntity httpentity=response.getEntity(); 
     inputstream= httpentity.getContent(); 
    } 
    catch(Exception ex) 
    { 
     resultview.setText(ex.getMessage()+"at 1st exception"); 
    } 
    try{ 
     BufferedReader reader=new BufferedReader(new InputStreamReader(inputstream,"iso-8859-1"),8); 
     StringBuilder sb=new StringBuilder(); 
     String line=null; 
     while((line=reader.readLine())!= null)     
     { 
      sb.append(line +"\n"); 
     } 
     inputstream.close(); 
     result=sb.toString(); 
    } 
    catch(Exception ex) 
    { 
     resultview.setText(ex.getMessage()+"at 2nd exception"); 
    } 
    try{ 
     String s="test :"; 
     JSONArray jarray=new JSONArray(result); 
     for(int i=0; i<jarray.length();i++) 
     { 
      JSONObject json=jarray.getJSONObject(i); 
      s= s + 
        "Name : "+json.getString("firstname")+" "+json.getString("lastname")+"\n"+ 
        "age :"+json.getString("age")+"\n"+ 
        "phone : "+json.getString("phone"); 
     } 
     resultview.setText(s); 
    } 
    catch(Exception ex) 
    { 
     this.resultview.setText(ex.getMessage()+"at 3rd exception"); 
    } 

} 

}

+0

這裏是php –

+0

當你直接訪問你的php文件時,你看到了什麼結果? –

回答

1

你確定你可以從仿真器訪問您的本地主機?你應該看看這個: Accessing localhost:port from Android emulator

+0

曼非常感謝我不知道這一點,現在它插入10.0.2.2:80作爲IP後,再次感謝男人。 :) –

0

你正在UI線程上啓動http請求。可能它爲此而崩潰。

嘗試登錄例外,而不是把你的resultview對象,並確認

+0

它的工作現在一切都好,我不得不使用正確的IP與正確的端口爲Android。 –

0

是你的PHP 5.5版?

您使用mysqli不使用mysql

的PHP代碼是正確的,也許是訪問數據庫不具有正確的數據

0

代碼從服務器獲取JSON數據。它對我來說工作得很好。

private void get_valueFromServer(String php) { 
String responseString = null; 
try{  
    HttpClient httpclient = new DefaultHttpClient(); 
    String url ="your_url"; 
    HttpPost httppost = new HttpPost(url); 
    HttpResponse response = httpclient.execute(httppost); 
    ByteArrayOutputStream out = new ByteArrayOutputStream(); 
    response.getEntity().writeTo(out); 
    out.close(); 
    responseString = out.toString(); 
    Toast.makeText(getApplicationContext(),responseString,1000).show(); 

    //The below code is for Separating values.It may varies according with your result from server. 

    JSONArray ja = new JSONArray(responseString); 
    int x=Integer.parseInt(ja.getJSONObject(0).getString("your_string_name")); 

} catch(Exception e) { 
} 
} 
相關問題