需要帮助从MYSQL数据库获取JSON数据到Android应用程序


Need help getting JSON data from MYSQL database to Android App

我正在开发一个Android应用程序,该应用程序连接到远程MYSQL数据库,并通过JSON数据检索信息。我遇到问题的应用程序部分包括在应用程序中按userID进行搜索,并从数据库中返回相关的用户信息,如ID、名字、公司和职位。

问题是解析应用程序中的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
}
?> 

如果我注释掉上面提到的行,应用程序中的Log会显示应用程序为results数组解析的正确数据:

D/UserID Lookup:: {"result":[{"id":"1100011","firstname":"Kevin","company":"company","position":"bartender"}]},但后来我收到了W/System.err: org.json.JSONException: No value for success的错误,因为success没有被发送(显然(。

这是我的安卓代码:

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错误。

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");

试着把你的代码转换成这个。