从Android电子连接MySQL数据库
嗯,这是在code片断我用来访问getUser.php以检索在我的应用程序从MySQL数据库用户的详细信息:
well this is the code snippet i use to access the getUser.php to retrive user details from a MySQL database in my application:
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("uid","demo"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.xxx.xx.xxx/getUser.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{
InputStream is = null;
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("fname")+
", sex: "+json_data.getInt("sex")+
", birthyear: "+json_data.getInt("dob")
);
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
所有的设定罚款:MySQL数据库,IIS FastCGI的,PHP工具和驱动程序。 的http:// 192甚至从浏览器的URL时调用下面的脚本。 xxx.xx.x.xxx/getUser.php?uid=demo 工作正常,但是在android的是显示java.lang.NullPointerException 和 org.json.JSONEXCEPTION返回错误:输入的字符0结束
Everything is configured fine: the MySQL Db, IIS with FASTCGi, PHP tools and drivers. even the script below when called from browser with url: http://192.xxx.xx.x.xxx/getUser.php?uid=demo works fine, But returns error in android with java.lang.NullPointerException and org.json.JSONEXCEPTION: End of input at character 0
<?php
mysql_connect("myhost","username","pwd");
mysql_select_db("mydb");
$q=mysql_query("SELECT * FROM userinfo WHERE uid ='".$_REQUEST['uid']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();
?>
在本节中任何人都可以帮忙吗?
Can anybody help in this section?
问候, 米斯特里Hardik
Regards, Mistry Hardik
您正在使用HttpPost对象,这意味着你正在发起一个后要求!你确定你不想做一个HTTPGET请求? 我碰到了同样的问题,切换到HTTPGET解决我的问题!
You are using the HttpPost Object, which means that are you are initiating a post-request! Are you sure you dont want to do a HttpGet Request? I ran into the same issue and switching to HttpGet solved my problem!