[英]Connecting to MySQL database using PHP for Android Development
I was reading a tutorial about how to connect android to mysql database over the internet using a php interface. 我正在阅读一个关于如何使用php界面通过互联网将android连接到mysql数据库的教程。 I made everything as it said to.
我按照它说的做了一切。
the php code is this: php代码是这样的:
$q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();
?>
and the java code is this: 而java代码是这样的:
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year","1980"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://example.com/getAllPeopleBornAfter.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream 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();
}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());
}
Now the problem is it gives me an error that the variable 'is' doesn't exist! 现在问题是它给我一个错误,变量'是'不存在! what should I do?
我该怎么办?
The tutorial is from website helloandroid.com : http://www.helloandroid.com/tutorials/connecting-mysql-database 本教程是从网站helloandroid.com: http://www.helloandroid.com/tutorials/connecting-mysql-database
try{
InputStream is = entity.getContent();
...
...
} //'is' goes out of scope here!
The scope is limited to the first try-catch block, and hence, is
is unavailable in the second. 的范围不限于第一try-catch块,因此,
is
在第二不可用。
Do: 做:
InputStream is = entity.getContent(); // 'is' now accessible in both try-catch
HttpEntity entity = response.getEntity(); // 'entity' is now accessible in both try-catch
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://example.com/getAllPeopleBornAfter.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
...
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.