I am developing an android application that requires me to connect to a mysql database and retrieve information from it. I am using a php script to connect to the server and query it and then output the results in json format:
if(!mysql_connect($mysql_host,$mysql_user,$mysql_pass) || !mysql_select_db($mysql_db)){
die($conn_error);
}
$q=mysql_query("SELECT * FROM food");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();
?>
Here is my java code that uses HttpGet to get the data and convert it to a string. It is then meant to parse the data and show it on the screen.
public class HttpExample extends Activity {
TextView httpStuff;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.httpex);
httpStuff = (TextView) findViewById(R.id.tvHttp);
GetMethodEx test = new GetMethodEx();
String returned;
try {
returned = test.getInternetData();
httpStuff.setText(returned);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public class GetMethodEx {
public String getInternetData() throws Exception {
BufferedReader in = null;
String data = "";
String returnString = null;
// httpGet
try {
HttpClient client = new DefaultHttpClient();
URI website = new URI("http://10.0.2.2/connect.php");
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response
.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while ((l = in.readLine()) != null) {
sb.append(l + nl);
}
in.close();
data = sb.toString();
// return data;
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// parse json data
try {
JSONArray jArray = new JSONArray(data);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag", "Foodname: " + json_data.getString("food"));
// Get an output to the screen
returnString += "\n\t" + jArray.getJSONObject(i);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return returnString;
}
}
}
It is doing everything I want except to parse the data. It is just showing the entire contents of the database on the screen when I only want the food names.Can anyone help?Thanks
edit: Here is a screenshot of my json output from my php script