【问题标题】:Trying to display User info from a database in my Android application尝试在我的 Android 应用程序中显示数据库中的用户信息
【发布时间】:2016-06-21 20:31:00
【问题描述】:

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

Login.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文件:

GetUserData.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 文件中调用该变量并运行查询以使用该变量显示用户信息。我该怎么做?

谢谢。

【问题讨论】:

    标签: java php android session sharedpreferences


    【解决方案1】:

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

    字符串输入用户名 = "用户名"; 字符串输入密码 = "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 和用户名保存到 SharedPreference

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

    您应该首先检查是否存储了用户 ID,以确定该用户是否是注册用户。如果用户未注册,则显示登录表单,否则将用户重定向到个人资料活动页面。

    【讨论】:

    • 感谢您的回复,我添加了更多信息,包括我的登录方法。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-08
      • 2015-06-12
      • 2018-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多