尝试在我的 Android 应用程序中显示数据库中的用户信息


Trying to display User info from a database in my Android application

我已经为此工作了一段时间。我尝试的第一件事是将登录的用户存储在会话中,然后稍后尝试使用该变量,如下所示:

登录.php

<?php
session_start();
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$sessionid = session_id();
    require_once('connect.inc.php');
    $sql = "SELECT username, password FROM USER WHERE username = ?";
    $stmt = $conn->prepare($sql);
    $username = $_POST["username"];
    $password = $_POST["password"];
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt->bind_result($user, $pass);
    while($stmt->fetch()){
        $verify = password_verify($password, $pass);
    }
    if($verify){
        $_SESSION["username"] = $username;
        echo 'connected';
    echo $sessionid;
    }else{
        echo 'check details';
    }
    mysqli_close($conn);
}
?>

然后,我将登录消息的响应拆分为两个变量。登录响应和会话 ID。我获取会话 ID 并存储在共享首选项中。我正在尝试将会话 ID 存储在我的 java 方法中,以便可以访问会话用户。这是我尝试获取用户的 java 代码:

GetUserData Java 方法

private void getUserData() {
    SharedPreferences sharedPreferences = getSharedPreferences(Config.sharedPref, Context.MODE_PRIVATE);
    String sessionId = sharedPreferences.getString(Config.SID, "SessionID");
    StringRequest stringRequest = new StringRequest(Request.Method.GET, Config.SERVER_ADDRESS + "GetUserData.php?PHPSESSID=" + sessionId,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    JSONObject jsonObject = null;
                    try {
                        //json string to jsonobject
                        jsonObject = new JSONObject(response);
                        //get json sstring created in php and store to JSON Array
                        result = jsonObject.getJSONArray(Config.json_array);
                        //get username from json array
                        getUserInfo(result);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                }
            });
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}
private void getUserInfo(JSONArray jsonArray){
    for(int i = 0; i < jsonArray.length(); i++) {
        try {
            JSONObject json = jsonArray.getJSONObject(i);
            userInfo.add(json.getString(Config.getUsername));
        } catch (JSONException e) {
        }
    }
}

以下是 java 方法尝试调用的 php 文件:

获取用户数据.php

<?php
 session_start();
if($_SERVER['REQUEST_METHOD'] == 'GET'){
            $username = $_SESSION['username'];
    $sql = "SELECT * FROM USER WHERE username = '$username'";
    require_once('connect.inc.php');
    $run = mysqli_query($conn, $sql);
    $result = array();
    while($row = mysqli_fetch_array($run)){
        array_push($result, array(
            'id' => $row['id'],
            'fname' => $row['fname'],
            'lname' => $row['lname'],
            'username' => $row['username'],
            'email' => $row['email'],
        ));
    }
    echo json_encode(array('result'=>$result));
    mysqli_close($conn);
}
?>

调试时,"result"数组为空,因此出于某种原因,

      $sql = "SELECT * FROM USER WHERE username = '$username'";

不工作。我知道这与会话有关,但我不确定问题出在哪里。

我的下一次尝试是尝试仅将登录用户存储在共享首选项中,然后从 php 文件调用该变量并运行查询以使用该变量显示用户信息。我该怎么做?

谢谢。

您要做的是在用户向服务器输入用户名和密码时发送请求,就像您在此处所做的那样。注意我修改了你的代码。

输入的字符串用户名 = "用户名";输入的字符串密码 = "xxxxxx";

String uri = String.format("http://somesite.com/some_endpoint.php?param1=%1$s&param2=%2$s", enteredUsername, enteredPassword);
 StringRequest stringRequest = new StringRequest(Request.Method.GET, uri,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                JSONObject jsonObject = null;
                try {
                    // parse the response object and store user id and data in sharedpreference.
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}

检查用户尚未注册,将用户添加到数据库并返回用户数据库唯一 ID 以及所需的其他数据。

然后将用户 ID 和用户名保存到共享首选项

SharedPreferences sharedPreferences = getSharedPreferences(Config.sharedPref, Context.MODE_PRIVATE);
sharedPreferences.Editor edit = prefs.edit();
edit.putStringSet("Personal Information", set);
edit.commit();

您应该首先检查用户 ID 是否优先存储,以确定该用户是否是注册用户。 如果用户未注册,则显示登录表单,否则将用户重定向到配置文件活动页面。

我已经有一个登录类来确保用户已注册。正如我所说,我只是试图从数据库中获取用户信息。这是我可能应该提供的登录方法:

private void login(){
        final String username = txtUsrnm.getText().toString().trim();
        final String password = txtPswrd.getText().toString().trim();
        //create string request
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.SERVER_ADDRESS + "Login.php",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        String responseOne = response.substring(0,9);
                        String responseTwo = response.substring(9);
                        if(responseOne.equalsIgnoreCase(Config.logInMessage)){
                            //create shared pref
                            SharedPreferences sharedPreferences = Login.this.getSharedPreferences(Config.sharedPref, Context.MODE_PRIVATE);
                            //editor stores values to the shared pref
                            SharedPreferences.Editor editor = sharedPreferences.edit();
                            //add values
                            editor.putBoolean(Config.sharedPrefBool, true);
                            editor.putString(Config.username, username);
                            editor.putString(Config.password, password);
                            editor.putString(Config.SID, responseTwo);
                            editor.commit();
                            Intent intent = new Intent(Login.this, Home.class);
                            startActivity(intent);
                        }else{
                            //display error message
                            Toast.makeText(Login.this, "Wrong Username or Password", Toast.LENGTH_LONG).show();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                //from android.com: A Map is a data structure consisting of a set of keys and
                // values in which each key is mapped to a single value. The class of the objects
                // used as keys is declared when the Map is declared, as is the class of the
                // corresponding values.
                Map<String,String> hashMap = new HashMap<>();
                //maps specified string key, username and password, to specified string value
                hashMap.put(Config.username, username);
                hashMap.put(Config.password, password);
                return hashMap;
            }
        };
        //add string request to queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }