在登录Android上获取共享偏好的用户信息

时间:2013-10-10 15:49:39

标签: php android mysql json sharedpreferences

我在android上创建了一个登录活动,因为你需要电子邮件地址和密码。

它工作但是由于我是android的新手,我不知道如何获取其余的用户信息并将其保存在共享偏好中。

请帮帮我

的login.php

<?php

//load and connect to MySQL database stuff
require("config.inc.php");

if (!empty($_POST)) {
    //gets user's info based of a username.
    $query = " 
            SELECT 
                user_id, 
                user_name,
                user_email,
                user_password,
                user_salt,              
                user_mobile,
                user_country
            FROM users 
            WHERE 
                user_email = :email 
        ";

    $query_params = array(
        ':email' => $_POST['user_email']
    );

    try {
        $stmt   = $db->prepare($query);
        $result = $stmt->execute($query_params);
    }
    catch (PDOException $ex) {
        // For testing, you could use a die and message. 
        //die("Failed to run query: " . $ex->getMessage());

        //or just use this use this one to product JSON data:
        $response["success"] = 0;
        $response["message"] = "Database Error 1. Please Try Again!";
        die(json_encode($response));

    }

    //This will be the variable to determine whether or not the user's information is correct.
    //we initialize it as false.
    $validated_info = false;

    //fetching all the rows from the query
    $row = $stmt->fetch();
    if ($row) {
        //if we encrypted the password, we would unencrypt it here, but in our case we just
        //compare the two passwords
        $check_password = hash('sha256', $_POST['user_password'] . $row['user_salt']);
        for($round = 0; $round < 65536; $round++) 
        {
            $check_password = hash('sha256', $check_password . $row['user_salt']);
        }

        if($check_password === $row['user_password'])
        {
            // If they do, then we flip this to true
            $login_ok = true;
        }
    }

    // If the user logged in successfully, then we send them to the private members-only page 
    // Otherwise, we display a login failed message and show the login form again 
    if ($login_ok) {

        // Here I am preparing to store the $row array into the $_SESSION by
        // removing the salt and password values from it.  Although $_SESSION is
        // stored on the server-side, there is no reason to store sensitive values
        // in it unless you have to.  Thus, it is best practice to remove these
        // sensitive values first.
        unset($row['user_password']);
        unset($row['user_salt']);       

        // This stores the user's data into the session at the index 'user'.
        // We will check this index on the private members-only page to determine whether
        // or not the user is logged in.  We can also use it to retrieve
        // the user's details.
        $_SESSION['user_email'] = $row;

        $response["success"] = 1;
        $response["message"] = "Login successful!";
        die(json_encode($response));
    } else {
        // Show them their username again so all they have to do is enter a new
        // password.  The use of htmlentities prevents XSS attacks.  You should
        // always use htmlentities on user submitted values before displaying them
        // to any users (including the user that submitted them).  For more information:
        // http://en.wikipedia.org/wiki/XSS_attack
        $submitted_username = htmlentities($_POST['user_email'], ENT_QUOTES, 'UTF-8');

        $response["success"] = 0;
        $response["message"] = "Invalid Credentials!";
        die(json_encode($response));
    }
} else {
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p>
<label>Email:</label><br>
<input name="user_email" type="text" value="" maxlength="254"/>
</p>
<p>
<label>Password:</label><br>
<input name="user_password" type="password" value="" maxlength="16"/>
</p>
<p>
<input type="submit" value="Login" name="submit"/>
</p>
</form>
<a href="register.php">Register</a>
</body>
</html>
<?php } ?> 

LoginActivity.java

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

        /**
         * Before starting background thread Show Progress Dialog
         */
        boolean failure = false;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(LoginActivity.this);
            pDialog.setMessage(getString(R.string.em_AttemptingLogin));
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
            // Check for success tag
            int success;
            /*String user_name = "";*/
            String user_email = etEmail.getText().toString();
            String user_password = etPassword.getText().toString();
           /* String user_mobile = "";
            String user_country = "";*/
            try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("user_email", user_email));
                params.add(new BasicNameValuePair("user_password", user_password));

                Log.d("request!", "starting");
                // getting product detail s by making HTTP request
                JSONObject json = jsonParser.makeHttpRequest(
                        LOGIN_URL, "POST", 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("Login Successful!", json.toString());

                    //SAVE
                    SharedPreferences ui = getSharedPreferences("UserInfo", MODE_PRIVATE);
                    SharedPreferences.Editor edUi = ui.edit();
                    /*edUi.putString("user_name", user_name);*/
                    edUi.putString("user_email", user_email);
                    /*edUi.putString("user_mobile", user_mobile);
                    edUi.putString("user_country", user_country);*/
                    edUi.commit();

                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    finish();

                    // Returns Toast "Login success!"
                    //return json.getString(TAG_MESSAGE);
                } else {
                    Log.d("Login Failure!", 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(LoginActivity.this, file_url, Toast.LENGTH_LONG).show();
            }

        }

    }

我尝试过与电子邮件相同但不起作用的方式,您可以看到它已注释/ * * / on .java

由于

2 个答案:

答案 0 :(得分:0)

服务器端

我的PHP相当生疏,但我很确定如果您只是回显您的json解析结果,那么该信息将在您的android上的JSONObject中捕获:

echo json_encode($response);

破解JSONObject

在你的机器人上,你应该希望从$ result对象获得所有信息。

要提取出类似的信息(不相关的例子只是为了显示机制):

            JSONObject jsonObject; // ... retreived earlier in the code
            try {

                if (jsonObject.getString("status").equals("OK")) {
                    jsonObject = jsonObject.getJSONArray("results")
                            .getJSONObject(0);
                    jsonObject = jsonObject.getJSONObject("geometry");
                    jsonObject = jsonObject.getJSONObject("location");
                    String lat = jsonObject.getString("lat");
                    String lng = jsonObject.getString("lng");


                    position = new LatLng(Double.valueOf(lat),
                            Double.valueOf(lng));
                }

            } catch (JSONException e) {
                Log.e(TAG, e.getMessage(), e);
            }

有关共享偏好的建议

示例在共享偏好设置中保存字符串,然后在应用中的任意位置再次检索它。

public class PreferencesData {

    public static void saveString(Context context, String key, String value) {
        SharedPreferences sharedPrefs = PreferenceManager
                .getDefaultSharedPreferences(context);
        sharedPrefs.edit().putString(key, value).commit();
    }

    public static String getString(Context context, String key, String defaultValue) {
        SharedPreferences sharedPrefs = PreferenceManager
                .getDefaultSharedPreferences(context);
        return sharedPrefs.getString(key, defaultValue);
    }
}

用法:

// save a note to the 'mynote' key
PreferencesData.saveString(context, "mynote", "This is a test note");

// retrieve the 'This is a test note' String
String note = PreferencesData.getString(context, "mynote", "");

可选说明:

我更喜欢尽可能少的硬编码字符串,所以我有一个/res/values/strings_prefkeys.xml文件,用于存储首选项键。对于注释示例,此文件将包含:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="key_note">key_note</string>
</resources>

然后上面的保存和检索将成为:

// save a note to the 'mynote' key
PreferencesData.saveString(context, context.getString(R.string.key_note), "This is a test note");

// retrieve the 'This is a test note' String
String note = PreferencesData.getString(context, context.getString(R.string.key_note), "");

这只是一个组织问题,并将意外重复密钥的风险降至最低,这会导致一些难以追踪的错误。

答案 1 :(得分:0)