我在这里找到了一些代码。我只能让我的数据库返回一个空json对象。这是我的代码。
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
}
}
}
这是我的php脚本。
<?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();
?>
我有一个apache web服务器目前运行的网站和。php文件是在同一目录下的index.html文件。我有一个mySQL数据库,它与apache服务器在同一台机器上运行。我真的知道很少关于数据库,但我知道,当我运行SELECT * FROM dinner_info WHERE row_id = 1;它返回正确的信息。所以我猜我的错误是在php。我试图用localhost和"用户名"替换"主机",用我的用户名和"密码"替换我的密码。什么好主意吗?如果你需要更多的信息,请告诉我!谢谢所有人。
我猜数据库连接或查询失败尝试这有助于调试:
<?php
error_reporting(-1);
ini_set("display_errors", 1);
mysql_connect("host","username","password") or die('Could not connect: ' . mysql_error());;
mysql_select_db("mydb");
$query = "SELECT * FROM dinner_info WHERE row_id ='".mysql_real_escape_string($_REQUEST['row_id'])."'"
$q=mysql_query($query);
if (!$q) {
$message = 'Invalid query: ' . mysql_error() . "'n";
$message .= 'Whole query: ' . $query;
die($message);
}
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();