I was playing around with code that I found here. The I can only get my database to return a null json object. Here is my code.
public class TableTalkSplash extends Activity {
private InputStream is;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String result = "";
InputStream is = null;
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("row_id","1"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://mywebsite.com/myscript.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
System.out.println(result); // this is printing "null" to the console
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getInt("id")+
", name: "+json_data.getString("name")+
", sex: "+json_data.getInt("sex")+
", birthyear: "+json_data.getInt("birthyear")
);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString()); //exception is being caught here
}
}
}
Here is my php script.
<?php
mysql_connect("host","username","password");
mysql_select_db("mydb");
$q=mysql_query("SELECT * FROM dinner_info WHERE row_id ='".$_REQUEST['row_id']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();
?>
I have an apache webserver currently running a website and the .php file is in the same directory as the index.html file. I have a mySQL database that is running on the same box as the apache server. I really know very little about databases, but I do know that when I run SELECT * FROM dinner_info WHERE row_id = 1; It returns the correct information. So I am guessing my error is in the php. I’ve tried to replace the “host” with localhost and “username” with my username and “password” with my password. Any Ideas? if you need more information let me know! Thanks everyone.
I’m guessing the db connection or query is failing try this to help with the debugging: