从Android连接MySQL数据库

时间:2010-11-30 17:47:34

标签: mysql android

这是我用来访问getUser.php以从我的应用程序中的MySQL数据库中检索用户详细信息的代码片段:

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());
        }

}

此代码段取自http://helloandroid.com

一切都配置正常:MySQL Db,带FASTCGi的IIS,PHP工具和驱动程序。甚至以下脚本从浏览器调用时使用url:http://192.xxx.xx.x.xxx/getUser.php?uid=demo工作正常,但在android中返回错误 java.lang.NullPointerException org.json.JSONEXCEPTION:输入结束在角色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();
?>

这部分有人可以提供帮助吗?

此致 Mistry Hardik

1 个答案:

答案 0 :(得分:1)

您正在使用HttpPost对象,这意味着您正在发起一个后请求!你确定你不想做HttpGet请求吗? 我遇到了同样的问题,切换到HttpGet解决了我的问题!