这里是代码,但它无法获取json数据,虽然浏览器显示json数据时我打开它为什么?php代码工作正常但是当android试图获取它时说我我取得空白
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 :(得分:1)
您确定可以从模拟器访问本地主机吗?你应该看看这个: Accessing localhost:port from Android emulator
答案 1 :(得分:0)
您正在UI线程上启动http请求。可能它崩溃了。
尝试记录异常,而不是放在resultview对象中并确认
答案 2 :(得分:0)
是你的PHP版本5.5?
你应该使用mysqli而不是使用mysql
php代码是正确的,也许访问数据库没有正确的数据
答案 3 :(得分: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) {
}
}