2016-09-27 118 views
0

我正在開發一個連接到遠程MYSQL數據庫並通過JSON數據檢索信息的Android應用程序。我遇到的部分應用涉及在應用中搜索userID,並從數據庫中返回關聯的用戶信息,例如ID,名字,公司和位置。需要幫助從MYSQL數據庫獲取JSON數據到Android應用程序

問題是解析應用程序內的JSON數據。我得到的錯誤消息是System.err: org.json.JSONException: No value for id

php頁面顯示JSON數據。輸出兩個JSON對象:一個success對象和一個result對象。 success對象被應用程序正確解析並通過if語句告訴應用程序要執行什麼操作。因此,if success == 1,應用程序會執行一個代碼塊,該代碼塊應該分析result對象並將該數組的每個元素分配給應用程序中的String值。從PHP頁面的輸出是:

{"success":1,"message":"UserID found!"}{"result":[{"id":"1100011","firstname":"Kevin","company":"company","position":"bartender"}]} 

的問題是從results對象中的值不被由應用解析。這裏是PHP頁面:

<?php 
define('HOST','localhost'); 
define('USER','********'); 
define('PASS','**********'); 
define('DB','**********'); 

if (!empty($_POST)){ 

if (empty($_POST['userID'])){ 
    $response["success"] = 0; 
    $response["message"] = "Please enter a User ID"; 
    die(json_encode($response)); 
} 

$userID = mysql_escape_string($_POST['userID']); 

$con = mysqli_connect(HOST,USER,PASS,DB); 

$sql = "SELECT * FROM users WHERE id = $userID"; 

$res = mysqli_query($con,$sql); 

$result = array(); 

while($row = mysqli_fetch_array($res)){ 
    array_push($result, array(
      'id'=>$row[0], 
      'firstname'=>$row[4], 
      'company'=>$row[6], 
      'position'=>$row[7], 
     ) 
    ); 
} 

if($result){ 
    $response["success"] = 1; 
    $response["message"] = "UserID found!"; 
    echo json_encode($response); // if I comment out this line, the result array gets parsed properly by the app. 
    echo json_encode(array("result"=>$result)); 

}else{ 
    $response["success"] = 0; 
    $response["message"] = "UserID not found. Please try again."; 
    die(json_encode($response)); 
} 

mysqli_close($con); 


} else { 
?> 
     <h1>Search by User ID:</h1> 
     <form action="searchbyuserid.php" method="post"> 
      Enter the UserID of the receipient:<br /> 
      <input type="text" name="userID" placeholder="User ID" /> 
      <br /><br /> 
      <input type="submit" value="Submit" /> 
     </form> 
     <a href="register.php">Register</a> 
    <?php 
} 

?> 

如果我註釋掉線上面提到的,從應用程序日誌顯示了正確的數據由應用程序解析爲results陣列:

D/UserID Lookup:: {"result":[{"id":"1100011","firstname":"Kevin","company":"company","position":"bartender"}]},後來我因爲success未被髮送(顯然),所以得到W/System.err: org.json.JSONException: No value for success的錯誤。

這裏是我的Android代碼:

import android.app.ProgressDialog; ... 

public class SearchByUserID extends ActionBarActivity implements View.OnClickListener { 

    // Buttons 
    private Button mSubmitButton, mBackButton; 

    // EditText Field 
    EditText enterUserID; 

    // Progress Dialog 
    private ProgressDialog pDialog; 

    // JSON parser class 
    JSONParser jsonParser = new JSONParser(); 

    // Variable for holding URL: 
    private static final String LOGIN_URL = "http://www.***********/webservice/searchbyuserid.php"; 

    //JSON element ids from response of php script: 
    private static final String TAG_SUCCESS = "success"; 
    private static final String TAG_MESSAGE = "message"; 
    private static final String TAG_USERID = "id"; 
    private static final String TAG_FIRSTNAME = "firstname"; 
    private static final String TAG_COMPANY = "company"; 
    private static final String TAG_POSITION = "POSITION"; 



    @Override 
    protected void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState); 
     this.supportRequestWindowFeature(Window.FEATURE_NO_TITLE); 
     setContentView(R.layout.search_by_user_id_layout); 

     mSubmitButton = (Button)findViewById(R.id.submit); 
     mBackButton = (Button)findViewById(R.id.back); 

     mSubmitButton.setOnClickListener(this); 
     mBackButton.setOnClickListener(this); 

     enterUserID = (EditText)findViewById(R.id.enterUserIdNumber); 
    } 

    @Override 
    public void onClick(View v) { 

     switch (v.getId()) { 
      case R.id.submit: 
       new SearchUserId().execute(); 
       break; 
      case R.id.back: 
       finish(); 
       break; 

      default: 
       break; 
     } 
    } 

    class SearchUserId extends AsyncTask<String, String, String> { 

     // Show progress dialog 
     boolean failure = false; 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(SearchByUserID.this); 
      pDialog.setMessage("Searching User ID..."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(true); 
      pDialog.show(); 
     } 

     @Override 
     protected String doInBackground(String... args) { 
      // Check for success tag 
      int success; 
      String userID = enterUserID.getText().toString(); 
      try { 
       // Building Parameters 
       List<NameValuePair> params = new ArrayList<NameValuePair>(); 
       params.add(new BasicNameValuePair("userID", userID)); 

       Log.d("UserID:", userID); 
       Log.d("request!", "starting"); 

       JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params); 

       // check your log for json response 
       Log.d("UserID Lookup:", json.toString()); 

       // json success tag 
       success = json.getInt(TAG_SUCCESS); 
       if (success == 1) { 
        JSONObject json2 = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params); 
        String userid = json2.getString(TAG_USERID); 
        String firstName = json2.getString(TAG_FIRSTNAME); 
        String company = json2.getString(TAG_COMPANY); 
        String position = json2.getString(TAG_POSITION); 

        Log.d("User ID Found!", json.toString()); 
        Log.d("userid:", userid); 
        Log.d("firstName:", firstName); 
        Log.d("company:", company); 
        Log.d("position:", position); 

        Intent i = new Intent(SearchByUserID.this, HomeActivity.class); 
        finish(); 
        startActivity(i); 
        return json.getString(TAG_MESSAGE); 
       }else{ 
        Log.d("User ID not found.", json.getString(TAG_MESSAGE)); 
        return json.getString(TAG_MESSAGE); 

       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

      return null; 

     } 
     /** 
     * After completing background task Dismiss the progress dialog 
     * **/ 
     protected void onPostExecute(String file_url) { 
      // dismiss the dialog once product deleted 
      pDialog.dismiss(); 
      if (file_url != null){ 
       Toast.makeText(SearchByUserID.this, file_url, Toast.LENGTH_LONG).show(); 
      } 

     } 

    } 
} 

所以基本上我能正確解析無論是success對象或results對象,但不能同時使用。如果我嘗試解析兩者,則會出現no value for id的JSON錯誤。

+0

這不是有效的JSON。您正在輸出兩個JSONObjects。只需將該數組添加到響應中,並確保只調用一次「echo json_encode()」。結果如下所示:http://pastebin.com/4QxBvyZF作爲一種替代方案,您也可以將它封裝在帶有兩個JSONObjects的JSONArray中,結果如下所示:http://pastebin.com/0JHQYGqh –

+0

**警告**:使用'mysqli'時,您應該使用[參數化查詢](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php)和['bind_param'](http:/ /php.net/manual/en/mysqli-stmt.bind-param.php)將用戶數據添加到您的查詢。 **不要**使用字符串插值或連接來完成此操作,因爲您創建了嚴重的[SQL注入漏洞](http://bobby-tables.com/)。 **絕不**將'$ _POST'或'$ _GET'數據直接放入查詢中,如果有人試圖利用您的錯誤,這會非常有害。 – tadman

+0

在代碼中間的'die'調用中阻塞也是不好的形式。如果您有錯誤,請設置響應代碼,渲染一些內容,然後執行常規清理。 – tadman

回答

0
JSONObject json2 = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params); 
JSONArray jsArray = json2.getJSONArray("result"); 

String usrid  = jsArray.getJSONObject("id"); 
String firstName = jsArray.getJSONObject("firstname"); 
String company = jsArray.getJSONObject("company"); 
String position = jsArray.getJSONObject("position"); 

嘗試將您的代碼轉換爲此。

相關問題