Android,使用PHP连接MySQL:空指针异常


Android, Connecting to MySQL using PHP: Null Pointer exception

我是安卓系统的新手,正在学习使用Php、MySql和JSON通过安卓客户端连接到服务器。出于测试目的,我在localhost上运行。这就是我所做的。数据库演示.php

public class Database_demo extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    String result = null;
    InputStream is = null;
    StringBuilder sb = null;
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    List<String> r = new ArrayList<String>();
    try{
    //http post
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://10.0.2.2/PhpAndMySql/category.php");
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    is = entity.getContent();
    }
    catch(Exception e){
        Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
   }
    //Convert response to string  
    try
    {
      BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
      sb = new StringBuilder();
      String line = null;
      while ((line = reader.readLine()) != null) 
      {
         sb.append(line + "'n");
      }
      is.close();
      result = sb.toString();
    }
    catch(Exception e)
    {
        Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
    }
    //END Convert response to string   
    try{
            JSONArray jArray = new JSONArray(result);
            JSONObject json_data=null;
            for(int i=0;i<jArray.length();i++)
            {
               json_data = jArray.getJSONObject(i);
               r.add(json_data.getString("category"));
           }
           setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, r));
        }
        catch(JSONException e1){
            Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
        } catch (ParseException e1) {
            Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
    }
}

}

category.php

<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
$q=mysql_query("SELECT * FROM category ORDER BY 'category'.'category' ASC");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>

MySQL

CREATE TABLE `test`.`category` (
`category_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`category` VARCHAR( 255 ) NOT NULL
 ) ENGINE = MYISAM ;

当我在android中执行时,我得到了一个NullPointer异常。Php文件正确吗?

求你了,我需要你的帮助!感谢

我认为您的php应该如下所示(而不是表上的引号。列使用反勾号)。

<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
$q=mysql_query("SELECT * FROM category ORDER BY `category` ASC");
$output = array();
while($row = mysql_fetch_assoc($sql))
    $output[]=$row;
print(json_encode($output));
mysql_close();
?>