无法通过带有JSON的php从mysql数据库获取数据到Android应用程序

时间:2016-09-16 02:07:26

标签: php android mysql json

我正在开发一个通过php脚本连接到远程mysql数据库的Android应用程序。该脚本应该查询数据库,并通过JSON数据返回结果。我正在尝试使用userID并返回与该用户相关的数据,例如fistnamecompanyposition

它返回JSON数据,但无论是搜索现有的userID,不存在的用户ID还是将editText字段留空,它总是一样的。基本上,这个if语句总是解析为false:if (!empty($result))所以这总是结果:$response["message"] = "User not found 2";

这是我的PHP脚本:

<?php

require("config.inc.php");

// array for JSON response
$response = array();


// check for post data
if (isset($_GET['userID'])) {
    $userid = $_GET['userID'];

    // get a product from products table
    $result = mysql_query("SELECT * FROM users WHERE id = $userid");

    if (!empty($result)) { //<-------This is always resovling to false even when I leave the editText field blank ----------
        // check for empty result
        if (mysql_num_rows($result) > 0) {

            $result = mysql_fetch_array($result);

            $user = array();
            $user["userid"] = $result["userid"];
            $user["firstname"] = $result["firstname"];
            $user["company"] = $result["company"];
            $user["position"] = $result["position"];

            // success
            $response["success"] = 1;

            // user node
            $response["user"] = array();

            array_push($response["user"], $user);

            // echoing JSON response
            echo json_encode($response);
        } else {
            // no product found
            $response["success"] = 0;
            $response["message"] = "User not found 1";

            // echo no users JSON
            echo json_encode($response);
        }
    } else {
        // no product found
        $response["success"] = 0;
        $response["message"] = "User not found 2"; //--------------THIS IS THE RESULT THAT IS ALWAYS RETURNED----------------

        // echo no users JSON
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field is missing";

    // echoing JSON response
    echo json_encode($response);
}
?>

这是我的android java文件:

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;

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.website.com/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";

    @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);
        enterUserID.addTextChangedListener(new TextWatcher() {

            int keyDel;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                enterUserID.setOnKeyListener(new View.OnKeyListener() {

                    @Override
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        if (keyCode == KeyEvent.KEYCODE_DEL)
                            keyDel = 1;
                        return false;
                    }
                });

                if (keyDel == 0) {
                    int len = enterUserID.getText().length();
                    if(len == 2 || len == 6) {
                        enterUserID.setText(enterUserID.getText() + "-");
                        enterUserID.setSelection(enterUserID.getText().length());
                    }
                } else {
                    keyDel = 0;
                }
            }
            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
        }

    @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("request!", "starting");

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

                // check your log for json response
                Log.d("Login attempt", json.toString());

                // json success tag
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {

                    Log.d("User ID Found!", json.toString());
                    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();
            }

        }

    }
}

0 个答案:

没有答案