Reputation: 130
here is the code but it can not get the json data although the browser is showing the json data when i m turning it on why?the php code is working fine but when the android is trying to fetch it says i am fetching null
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");
}
}
}
Upvotes: 0
Views: 108
Reputation: 96
Code to get json data from server. It is working fine for me.
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) {
}
}
Upvotes: 0
Reputation: 298
is your php version 5.5?
you should use mysqli not use mysql
the php code is correct, perhaps the access database does not have the correct data
Upvotes: 0
Reputation: 749
You are launching the http request on UI thread. Probably it crashes for this.
Try to log the exception, not put in your resultview object and confirm that
Upvotes: 0
Reputation: 1719
Are you sure you can access your localhost from the emulator? You should take a look at this: Accessing localhost:port from Android emulator
Upvotes: 1