簡體   English   中英

嘗試在我的Android應用程序中顯示數據庫中的用戶信息

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

我已經為此工作了一段時間。 我嘗試的第一件事是將登錄的用戶存儲在會話中,然后稍后嘗試使用該變量,例如:

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

調試時,“結果”數組為空,因此由於某種原因,

      $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和用戶名保存到SharedPreference

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM