dsgw3315 2016-09-27 01:03
浏览 83

需要帮助从MYSQL数据库获取JSON数据到Android App

I'm developing an Android app that connects to a remote MYSQL database and retrieves info via JSON data. The part of the app I'm having trouble with involves searching by userID in the app, and returning the associated user info from the database, such as the ID, first name, company and position.

The problem is parsing the JSON data within the app. The error message I get is System.err: org.json.JSONException: No value for id.

The php page displays JSON data. Two JSON objects are outputted: a success object and a result object. The success object is properly parsed by the app and tells the app what to do via an if-statement. So if success == 1, the app executes a block of code that should parses the result object and assigns each element of the array to a String value in the app. The output from the php page is:

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

The problem is the values from the results object are not being parsed by the app. Here is the php page:

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

?> 

If I comment out the line noted above, the Log from the app shows the correct data being parsed by the app for the results array:

D/UserID Lookup:: {"result":[{"id":"1100011","firstname":"Kevin","company":"company","position":"bartender"}]}, but then I get an error for W/System.err: org.json.JSONException: No value for success because success isn't being sent (obviously).

Here's my android code:

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();
            }

        }

    }
}

So basically I'm able to properly parse either the success object or the results object, but not both. If I try to parse both, I get a JSON error for no value for id.

  • 写回答

1条回答 默认 最新

  • duanlun1955 2016-09-27 05:28
    关注
    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");
    

    try converting your code to this.

    评论

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题