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

Java 试图在我的Android应用程序中显示数据库中的用户信息,java,php,android,session,sharedpreferences,Java,Php,Android,Session,Sharedpreferences,我已经为此工作了一段时间。我尝试的第一件事是将登录用户存储在会话中,然后稍后尝试使用该变量,如以下所示: Login.php <?php session_start(); if($_SERVER['REQUEST_METHOD'] == 'POST'){ $sessionid = session_id(); require_once('connect.inc.php'); $sql = "SELECT username, password FROM USER WHER

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

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);
}
?>
<?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);
}
?>
它不起作用。我知道这与会议有关,但我不确定问题出在哪里

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


多谢各位

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

字符串enteredUsername=“username”; 输入的字符串password=“xxxxxx”


您应该首先检查用户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);
    }
private void login(){
最终字符串username=txtUsrnm.getText().toString().trim();
最终字符串密码=txtPswrd.getText().toString().trim();
//创建字符串请求
StringRequest StringRequest=new StringRequest(Request.Method.POST,Config.SERVER_ADDRESS+“Login.php”,
新的Response.Listener(){
@凌驾
公共void onResponse(字符串响应){
字符串responseOne=response.substring(0,9);
字符串responseTwo=response.substring(9);
if(responseOne.equalsIgnoreCase(Config.logInMessage)){
//创建共享pref
SharedReferences SharedReferences=Login.this.getSharedReferences(Config.SharedReferences,Context.MODE\u PRIVATE);
//编辑器将值存储到共享pref
SharedReferences.Editor=SharedReferences.edit();
//增加价值
putBoolean(Config.sharedPrefBool,true);
putString(Config.username,username);
putString(Config.password,password);
putString(Config.SID,responsewo);
commit();
意图=新意图(Login.this,Home.class);
星触觉(意向);
}否则{
//显示错误消息
Toast.makeText(Login.this,“错误的用户名或密码”,Toast.LENGTH_LONG.show();
}
}
},
新的Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
}
}){
@凌驾
受保护的映射getParams()引发AuthFailureError{
//来自android.com:地图是由一组键和
//每个键映射到单个值的值。对象的类
//在声明映射时声明用作键,就像
//相应的值。
Map hashMap=新hashMap();
//将指定的字符串键、用户名和密码映射到指定的字符串值
put(Config.username,username);
put(Config.password,password);
返回hashMap;
}
};
//将字符串请求添加到队列
RequestQueue RequestQueue=Volley.newRequestQueue(this);
添加(stringRequest);
}

感谢您的回复,我添加了更多信息,包括我的登录方法。
      $sql = "SELECT * FROM USER WHERE username = '$username'";
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);
}
SharedPreferences sharedPreferences = getSharedPreferences(Config.sharedPref, Context.MODE_PRIVATE);
sharedPreferences.Editor edit = prefs.edit();
edit.putStringSet("Personal Information", set);
edit.commit();
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);
    }