2013-12-16 67 views
0

我是新的使用PHP和JSON。我正在編寫一個android應用程序,用於調用一個在數據庫中插入的php函數。這是插入數據的PHP代碼:JSON ojbect php響應NullPointerException

<?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

The NullPointerEx ception在AsyncTask上,第137行是:

int flag = json.getInt(TAG_SUCCESS); 

有什麼不對?

+0

是什麼Login_activity.java行號137 ... ??? – SilentKiller

+0

它是asynctask的行(在Login_activity中編碼)我已經在我的文章中指定 – giozh

+0

後ur php輸出 –

回答

1

嘗試登錄你從你的PHP腳本得到的迴應在Web瀏覽器中顯示您的網頁,並通過URL用GET方法發送數據。看看哪些頁面返回和調試這一點;)

您可以檢查您的JSON是有效的位置:jsonlint.com

+0

好的。我的php代碼沒有找到包含DB_CONNECT函數定義的文件。 – giozh

0

Maby無法解析JSON,因爲PHP正在解析JSON數組INSTEAD的JSON對象。強制使用JSON對象使用:json_encode($array, JSON_FORCE_OBJECT)

我不知道android代碼如何工作,但您可以嘗試先發送(註釋您的php代碼併發送靜態JSON對象)並解析JSON對象。學習如何調試!

0

它說你的json包含一個"<br"字符串。

我認爲你的PHP響應沒有提供有效的JSON字符串,可能是一個PHP錯誤。

嘗試通過

Log.i("PHP Response", json);