使用php检索json对象时出现空指针异常?

时间:2014-10-31 17:34:07

标签: php android json nullpointerexception

android代码:

protected String doInBackground(String... params) {
        // TODO Auto-generated method stub

        try {
            SharedPreferences prefs = getActivity().getSharedPreferences("Login_Prefs", 0);

            username = prefs.getString("username", "defValue");

            String url = "http://www.iloveexpressions.com/eh/viewFriendList.php";

            nameValuePairs = new ArrayList<NameValuePair>(1);

            Log.d("Parameters ", username);

            nameValuePairs.add(new BasicNameValuePair("username", username.trim()));

            Log.d("name value pairs", nameValuePairs.toString());

            JSONObject json = jsonParser.makeHttpRequest(url, "POST",
                    nameValuePairs);

            Log.d("Printing after json", json.toString());

            success = json.getString("success");

            Log.d("Success : ", success);

        } catch (Exception e) {
            Log.d("Error : ", e.toString());
        }

php代码:

  <?php

require 'connection.php';

   $response = array();

if(isset($_POST["username"]))
 {
$username = $_POST["username"];

$response["success"] = 1;

echo json_encode($response);
 }
else
 {
$response["success"] = 0;

echo json_encode($response);
}

?>

这是我在日志中得到的错误:

Parameters(30889): aaa

name value pairs(30889): [username=aaa]

Error :(30889): java.lang.NullPointerException

如何解决此错误?我使用相同的方法在Android上使用PHP发送和检索数据,它工作正常吗?如果用户名正确发送到php文件,我将返回成功

我在片段中使用doInBackground进程并且在onCreateView()方法中调用execute()方法是否可能?

2 个答案:

答案 0 :(得分:0)

你应该使用google的Volley库。与此方法相比,它速度快,并且异步工作。

RequestQueue queue = Volley.newRequestQueue(context);
  JsonObjectRequest  jsonObject = new JsonObjectRequest  (Request.Method.POST,"http://www.iloveexpressions.com/eh/viewFriendList.php", new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    }){
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> params = new HashMap<String, String>();
            params.put("usename",username);    
            return params;
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String,String> params = new HashMap<String, String>();
            params.put("Content-Type","application/x-www-form-urlencoded");
            return params;
        }
    };
    queue.add(jsonObject);

public void onResponse方法中,您将获得所需的json响应。

答案 1 :(得分:0)

我没有初始化我的JSONParser jsonParser;  我将其更改为JSONParser jsonParser = new JSONParser();它工作了