2013-12-16 3 views
0

Я новичок в php и JSON. Я пишу приложение Android для вызова функции php, которая вставляет в базу данных. Это PHP код данных вставки:JSON ojbect php response 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

NullPointerEx cept на AsyncTask, а строка 137:

int flag = json.getInt(TAG_SUCCESS); 

что не так?

+0

что номер строки 137 в Login_activity.java ... ??? – SilentKiller

+0

это строка asynctask (закодированная внутри Login_activity), которую я указал в своем сообщении – giozh

+0

сообщение ur php output –

ответ

1

Try для отображения страницы в веб-браузере и отправлять данные через URL с помощью метода GET. Посмотрите, что возвращение страницы и отладки этого;)

Вы можете проверить, если ваш JSON действителен здесь: jsonlint.com

+0

ok. Мой 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.

Попробуйте войти ответ вы получили от вашего PHP скрипта

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