JSON对象php响应NullPointerException

时间:2013-12-16 12:52:57

标签: php android json android-asynctask

我是使用php和JSON的新手。我正在编写一个Android应用程序,用于调用在数据库上插入的php函数。这是插入数据的php代码:

<?php
$response = array();

// check for required fields
if ( isset($_POST['username']) && isset($_POST['password']) ) {

    $username = $_POST['username'];
    $password = $_POST['password'];

    // include db connect class
    require_once __DIR__ . '/db_connect.php';

    // connecting to db
    $db = new DB_CONNECT();

    // mysql inserting a new row
    $result = mysql_query("INSERT INTO users(username, password) VALUES('$username', '$password')");

    // check if row inserted or not
    if ($result) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "User successfully added.";

        // echoing JSON response
        echo json_encode($response);
    } else {
        // failed to insert row
        $response["success"] = 0;
        $response["message"] = "Oops! An error occurred.";

        // echoing JSON response
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    // echoing JSON response
    echo json_encode($response);
}
?>

这是我内心的AsyncTask doInBackGround代码:

protected Void doInBackground(Void... args) {


        JSONParser jsonParser = new JSONParser();
        // create parameters list
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username", username));
        params.add(new BasicNameValuePair("password", password));
        // get JSON Object by using POST method
        JSONObject json = jsonParser.makeHttpRequest(register_url, "POST",
                params);
        try {
            int flag = json.getInt(TAG_SUCCESS);
            if (flag == 1) {

            } else {

            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

这是JSONParser对象实现:

public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

public JSONParser() {
};

// function get json from url by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if (method == "POST") {
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } else if (method == "GET") {
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    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();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}
}

当我运行我的应用程序并尝试执行json代码时,我发现错误http://nopaste.info/d7de67983a.html

NullPointerException在AsyncTask上,第137行是:

int flag = json.getInt(TAG_SUCCESS);

出了什么问题?

3 个答案:

答案 0 :(得分:1)

尝试在网络浏览器中显示您的网页,并使用GET方法通过网址发送数据。查看页面返回并调试此内容;)

您可以在此处查看您的json是否有效:jsonlint.com

答案 1 :(得分:0)

Maby无法解析JSON,因为PHP正在解析JSON对象的JSON数组INSTEAD。要强制使用JSON对象:json_encode($array, JSON_FORCE_OBJECT)

我不知道android代码是如何工作的,但你可以尝试先发送(注释你的php代码并发送静态JSON对象)并解析一个JSON对象。学习如何调试!

答案 2 :(得分:0)

它表示你的json包含一个"<br"字符串。

我认为您的PHP响应不提供有效的JSON字符串,可能是PHP错误。

尝试通过

记录您从PHP脚本获得的响应
Log.i("PHP Response", json);