0

我想在 mysql 中选择行值。当我运行代码时,logcat 显示“缺少必填字段”。我不确定 php 或 android 代码中的问题。我希望有一个人可以帮助我。

public class profileActivity extends Activity{   


EditText txtName;
EditText inputusername;
EditText answer;
EditText txtPrice;
EditText txtDesc;
EditText txtCreatedAt;
String username;

private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_FIRSTNAME = "first_name";
private static String KEY_lASTNAME = "last_name";
private static String KEY_EMAIL = "email";



private DatabaseHandler dbHelper;  
private ProgressDialog pDialog;

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

// single product url
private static final String profileURL =       "http://10.0.2.2/android_login_api4/include/profile.php";

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.profile);       

 // getting product details from intent
        Intent i = getIntent();

        // getting product id (pid) from intent
        username = i.getStringExtra(KEY_NAME);


    // Getting complete product details in background thread
    new GetProfileDetails().execute(); 

}



 /**
 * Background Async Task to Get complete product details
 * */
class GetProfileDetails extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(profileActivity.this);
        pDialog.setMessage("Loading product details. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }


        /**
         * Getting product details in background thread
         * */
        protected String doInBackground(String... params) {

            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    // Check for success KEY
                    int success;
                    try {


                        // Building Parameters
                        List<NameValuePair> params = new ArrayList<NameValuePair>();
                        params.add(new BasicNameValuePair("username", username));

                        // getting product details by making HTTP request
                        // Note that product details url will use GET request
                        JSONObject json = jsonParser.getJSONFromUrl(
                                profileURL, params);

                        // check your log for json response
                        Log.d("Single Product Details", json.toString());

                        // json success KEY
                        success = json.getInt(KEY_SUCCESS);
                        if (success == 1) {
                            // successfully received product details
                            JSONArray productObj = json
                                    .getJSONArray(KEY_NAME); // JSON Array

                            // get first product object from JSON Array
                            JSONObject product = productObj.getJSONObject(0);

                            // product with this uid found
                            // Edit Text
                            txtName = (EditText) findViewById(R.id.name);
                            txtPrice = (EditText) findViewById(R.id.email);
                            txtDesc = (EditText) findViewById(R.id.tel);

                            // display product data in EditText
                            txtName.setText(product.getString(KEY_lASTNAME));
                            txtPrice.setText(product.getString(KEY_FIRSTNAME));
                            txtDesc.setText(product.getString(KEY_EMAIL));

                        }else{
                            // product with uid not found
                        }
                    } 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 got all details
            pDialog.dismiss();
        }
    }
}

那是php的代码

  <?php

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


// include db connect class
require_once 'DB_Connect.php';

// connecting to db
$db = new DB_CONNECT();

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

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

if (!empty($result)) {
    // check for empty result
    if (mysql_num_rows($result) > 0) {

        $result = mysql_fetch_array($result);

        $product = array();
        $product["username"] = $result["username"];
        $product["first_name"] = $result["first_name"];
        $product["last_name"] = $result["last_name"];
        $product["email"] = $result["email"];
        $product["tel"] = $result["tel"];
        $product["age"] = $result["age"];
        // success
        $response["success"] = 1;

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

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

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

        // echo no users JSON
        echo json_encode($response);
    }
} else {
    // no product found
    $response["success"] = 0;
    $response["message"] = "No product found";

    // echo no users JSON
    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);
}
?>
4

2 回答 2

0

您可以通过在浏览器中打开此网址来检查您的 php 代码。

http://10.0.2.2/android_login_api4/include/profile.php?username=username

确保您在 URL 末尾放置了正确的用户名。

如果你的 php 代码是正确的,它会显示一个 json 格式的文本,否则会显示一个错误,这样你就可以发现你的 php 代码是正确的还是不正确的。

于 2013-02-26T14:20:19.143 回答
0

我认为您的问题是您的代码没有以适当的方式将参数提供给服务器。

这是我如何进行这种交流的简单示例:

private static String convertStreamToString(InputStream IS) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(IS));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            IS.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

private JSONObject processCommand(String command, String params) {
    JSONObject result = null;

    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
    HttpResponse response;

    try{
        String s = serverURL + command + ".php";
        if (params.length() != 0) s += "?" + params;

        Log.v("Wordster", s);

        HttpGet get = new HttpGet(s);
        response = client.execute(get);

        if (response != null){
            InputStream instream = response.getEntity().getContent();

            String instring = convertStreamToString(instream);

            Log.v("Wordster", instring);

            JSONObject json = new JSONObject(instring);
            instream.close();

            result = json;
        }
    } catch(Exception e) {
        e.printStackTrace();
        result = null;
    }

    return result;
}


public CommandResult getUserProfile(int userId) {
    String paramstr = 
            "sessionid=" + sessionID + 
            "&userid=" + userId;

    JSONObject data = processCommand("getuserprofile", paramstr);

    if (data != null) {
        try {
            if (data.getString("result").equals("ok")) {

                JSONObject u = data.getJSONObject("data");

                User user = new User(
                        u.getInt("userid"),
                        u.getString("loginname"),
                        u.getString("username"),
                        u.getString("email"),
                        u.getString("sex"),
                        AXUtils.convertSQLStringToDate(u.getString("birthdate"))
                );

                return new CommandResult(ResultCodes.OK, user);
            } else {
                if (data.getInt("errcode") == -2) 
                    return new CommandResult(ResultCodes.ERR_INVALID_SESSION);
                else
                    return new CommandResult(ResultCodes.ERR_INTERNAL);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    return new CommandResult(ResultCodes.ERR_COMM_ERROR);
}

Activity 的用法如下:

private void loadUserProfile() {
    AsyncTask<Integer, Void, CommandResult> load = new AsyncTask<Integer, Void, CommandResult>() {
        @Override
        protected CommandResult doInBackground(Integer... userId) {
            WordsterApp app = (WordsterApp) getApplication();
            return app.server.getUserProfile(userId[0]);
        }

        @Override
        protected void onPostExecute(CommandResult result) {
            User u = (User) result.data;
            if (u != null) {
                user = u;

                findViewById(R.id.ControlsLayout).setVisibility(View.VISIBLE);
                findViewById(R.id.LoadingLayout).setVisibility(View.GONE);

                EditText et = (EditText) findViewById(R.id.LoginNameEditText);
                et.setText(user.loginName);
                et = (EditText) findViewById(R.id.UserNameEditText);
                et.setText(user.userName);
                et = (EditText) findViewById(R.id.EmailEditText);
                et.setText(user.email);
                et = (EditText) findViewById(R.id.BirthDateEditText);
                et.setText(AXUtils.ConvertDateToString(getBaseContext(), user.birthDate));        
            } else {
                new AXErrDialog(UserProfileActivity.this, R.string.cannot_communicate_with_server) {
                    @Override
                    void onClosed() {
                        setResult(Activity.RESULT_CANCELED);
                        finish();
                    };
                }.Show();
            }
        }
    };

    load.execute(userID);   
}

php代码是(getuserprofile.php):

require_once("../config.php");
require_once(LIBSDIR."db.class.php");
require_once(LIBSDIR."xutils.php");
require_once(LIBSDIR."ws_base.php");

if (!isset($_REQUEST["sessionid"]) || !isset($_REQUEST["userid"])) {
    Error(-1);
}

$sessionid = $_REQUEST["sessionid"];
$userid = $_REQUEST["userid"];

$db = new DataBase(DB_SERVER, DB_DATABASE, DB_USER, DB_PASSWORD);

if (!$uid = CheckSessionID($db, $sessionid)) {
    Error(-2);
}

if ($userid == -1)
    $userid = $uid;

$ds = $db->query(
    "SELECT " .
    "  nID as userid, " .
    "  cLoginName as loginname, " .
    "  cUserName as username, " .
    "  cEmail as email, " .
    "  cSex as sex, " .
    "  dBirth as birthdate, " .
    "  cProfilePictureID as profilepictureid " .
    "FROM WS_Users " .
    "WHERE " .
    "  nID = $userid");

$details = mysql_fetch_array($ds, MYSQL_ASSOC);

$data = array(
    "result" => "ok", 
    "data" => $details
);

echo json_encode($data);
于 2013-02-26T14:33:08.793 回答