Android Studio 无法进入管理页面

Posted

技术标签:

【中文标题】Android Studio 无法进入管理页面【英文标题】:Android Studio Can't Go to Admin Page 【发布时间】:2021-09-23 03:40:27 【问题描述】:

所以我是 android Studio 的新手,我正在尝试制作一个登录页面。在我的数据库中,我创建了 user_type 属性,如果用户类型是管理员,我希望登录屏幕重定向到管理员页面而不是普通主页。我尝试使用 if-else 语句来表示意图,但即使我的 user_type 已经是“Admin”,它仍然总是将我重定向到 MainActivity 类。谁能帮忙告诉我这个问题?提前致谢。

这是我的用户类:

package com.example.voluminous.model;

//Create User class
public class User 

    private int id;
    private String type;
    private String name;
    private String email;
    private String password;

    public int getId() 
        return id;
    

    public void setId(int id) 
        this.id = id;
    

    public String getType() 
        return type;
    

    public void setType(String type) 
        this.type = type;
    

    public String getName() 
        return name;
    

    public void setName(String name) 
        this.name = name;
    

    public String getEmail() 
        return email;
    

    public void setEmail(String email) 
        this.email = email;
    

    public String getPassword() 
        return password;
    

    public void setPassword(String password) 
        this.password = password;
    

这是我的 DB Open Helper:

package com.example.voluminous.sql;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.example.voluminous.model.User;

import java.util.ArrayList;
import java.util.List;

public class UserDatabaseHelper extends SQLiteOpenHelper 
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "UserManager.db";

    // User table name
    private static final String TABLE_USER = "user";

    // User Table Columns names
    private static final String COLUMN_USER_ID = "user_id";
    private static final String COLUMN_USER_TYPE = "user_type";
    private static final String COLUMN_USER_NAME = "user_name";
    private static final String COLUMN_USER_EMAIL = "user_email";
    private static final String COLUMN_USER_PASSWORD = "user_password";

    // create table sql query
    private String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USER + "("
            + COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + COLUMN_USER_TYPE + " TEXT DEFAULT 'Customer' NOT NULL,"
            + COLUMN_USER_NAME + " TEXT NOT NULL," + COLUMN_USER_EMAIL + " TEXT NOT NULL," + COLUMN_USER_PASSWORD + " TEXT NOT NULL" + ")";

    // drop table sql query
    private String DROP_USER_TABLE = "DROP TABLE IF EXISTS " + TABLE_USER;

    /**
     * Constructor
     *
     * @param context
     */
    public UserDatabaseHelper(Context context) 
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    

    @Override
    public void onCreate(SQLiteDatabase db) 
        db.execSQL(CREATE_USER_TABLE);
        db.execSQL("INSERT INTO user (user_type, user_name, user_email, user_password) VALUES (?,?,?,?)", new Object[]"Admin","Administrator","admin@voluminous.com","123");
    


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 

        //Drop User Table if exist
        db.execSQL(DROP_USER_TABLE);

        // Create tables again
        onCreate(db);

    

    /**
     * This method is to create user record
     *
     * @param user
     */
    public void addUser(User user) 
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COLUMN_USER_TYPE, user.getType());
        values.put(COLUMN_USER_NAME, user.getName());
        values.put(COLUMN_USER_EMAIL, user.getEmail());
        values.put(COLUMN_USER_PASSWORD, user.getPassword());

        // Inserting Row
        db.insert(TABLE_USER, null, values);
        db.close();
    

    /**
     * This method is to fetch all user and return the list of user records
     *
     * @return list
     */
    public List<User> getAllUser() 
        // array of columns to fetch
        String[] columns = 
                COLUMN_USER_ID,
                COLUMN_USER_TYPE,
                COLUMN_USER_EMAIL,
                COLUMN_USER_NAME,
                COLUMN_USER_PASSWORD
        ;
        // sorting orders
        String sortOrder =
                COLUMN_USER_NAME + " ASC";
        List<User> userList = new ArrayList<User>();

        SQLiteDatabase db = this.getReadableDatabase();

        // query the user table
        /**
         * Here query function is used to fetch records from user table this function works like we use sql query.
         * SQL query equivalent to this query function is
         * SELECT user_id,user_name,user_email,user_password FROM user ORDER BY user_name;
         */
        Cursor cursor = db.query(TABLE_USER, //Table to query
                columns,    //columns to return
                null,        //columns for the WHERE clause
                null,        //The values for the WHERE clause
                null,       //group the rows
                null,       //filter by row groups
                sortOrder); //The sort order


        // Traversing through all rows and adding to list
        if (cursor.moveToFirst()) 
            do 
                User user = new User();
                user.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(COLUMN_USER_ID))));
                user.setType(cursor.getString(cursor.getColumnIndex(COLUMN_USER_TYPE)));
                user.setName(cursor.getString(cursor.getColumnIndex(COLUMN_USER_NAME)));
                user.setEmail(cursor.getString(cursor.getColumnIndex(COLUMN_USER_EMAIL)));
                user.setPassword(cursor.getString(cursor.getColumnIndex(COLUMN_USER_PASSWORD)));
                // Adding user record to list
                userList.add(user);
             while (cursor.moveToNext());
        
        cursor.close();
        db.close();

        // return user list
        return userList;
    

    /**
     * This method to update user record
     *
     * @param user
     */
    public void updateUser(User user) 
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COLUMN_USER_TYPE, user.getType());
        values.put(COLUMN_USER_NAME, user.getName());
        values.put(COLUMN_USER_EMAIL, user.getEmail());
        values.put(COLUMN_USER_PASSWORD, user.getPassword());

        // updating row
        db.update(TABLE_USER, values, COLUMN_USER_ID + " = ?",
                new String[]String.valueOf(user.getId()));
        db.close();
    

    /**
     * This method is to delete user record
     *
     * @param user
     */
    public void deleteUser(User user) 
        SQLiteDatabase db = this.getWritableDatabase();
        // delete user record by id
        db.delete(TABLE_USER, COLUMN_USER_ID + " = ?",
                new String[]String.valueOf(user.getId()));
        db.close();
    

    /**
     * This method to check user exist or not
     *
     * @param email
     * @return true/false
     */
    public boolean checkUser(String email) 

        // array of columns to fetch
        String[] columns = 
                COLUMN_USER_ID
        ;
        SQLiteDatabase db = this.getReadableDatabase();

        // selection criteria
        String selection = COLUMN_USER_EMAIL + " = ?";

        // selection argument
        String[] selectionArgs = email;

        // query user table with condition
        /**
         * Here query function is used to fetch records from user table this function works like we use sql query.
         * SQL query equivalent to this query function is
         * SELECT user_id FROM user WHERE user_email = 'jack@androidtutorialshub.com';
         */
        Cursor cursor = db.query(TABLE_USER, //Table to query
                columns,                    //columns to return
                selection,                  //columns for the WHERE clause
                selectionArgs,              //The values for the WHERE clause
                null,                       //group the rows
                null,                      //filter by row groups
                null);                      //The sort order
        int cursorCount = cursor.getCount();
        cursor.close();
        db.close();

        if (cursorCount > 0) 
            return true;
        

        return false;
    

    /**
     * This method to check user exist or not
     *
     * @param email
     * @param password
     * @return true/false
     */
    public boolean checkUser(String email, String password) 

        // array of columns to fetch
        String[] columns = 
                COLUMN_USER_ID
        ;
        SQLiteDatabase db = this.getReadableDatabase();
        // selection criteria
        String selection = COLUMN_USER_EMAIL + " = ?" + " AND " + COLUMN_USER_PASSWORD + " = ?";

        // selection arguments
        String[] selectionArgs = email, password;

        // query user table with conditions
        /**
         * Here query function is used to fetch records from user table this function works like we use sql query.
         * SQL query equivalent to this query function is
         * SELECT user_id FROM user WHERE user_email = 'jack@androidtutorialshub.com' AND user_password = 'qwerty';
         */
        Cursor cursor = db.query(TABLE_USER, //Table to query
                columns,                    //columns to return
                selection,                  //columns for the WHERE clause
                selectionArgs,              //The values for the WHERE clause
                null,                       //group the rows
                null,                       //filter by row groups
                null);                      //The sort order

        int cursorCount = cursor.getCount();

        cursor.close();
        db.close();
        if (cursorCount > 0) 
            return true;
        

        return false;
    

这是我的 LoginActivity 类:

package com.example.voluminous;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.service.autofill.UserData;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.voluminous.model.User;
import com.example.voluminous.sql.UserDatabaseHelper;

import java.util.ArrayList;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener 

    private UserDatabaseHelper UserDBHelper;
    private Button mBtLoginactivityRegister;
    private RelativeLayout mRlLoginactivityLayout;
    private EditText mEtLoginactivityEmail;
    private EditText mEtLoginactivityPassword;
    private LinearLayout mLlLoginactivityTwo;
    private Button mBtLoginactivityLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        initView();

        UserDBHelper = new UserDatabaseHelper(this);
    

    private void initView() 

        mBtLoginactivityLogin = findViewById(R.id.bt_loginactivity_login);
        mBtLoginactivityRegister = findViewById(R.id.bt_loginactivity_register);
        mRlLoginactivityLayout = findViewById(R.id.rl_loginactivity_layout);
        mEtLoginactivityEmail = findViewById(R.id.et_loginactivity_email);
        mEtLoginactivityPassword = findViewById(R.id.et_loginactivity_password);
        mLlLoginactivityTwo = findViewById(R.id.loginactivity_loginbox);

        mBtLoginactivityLogin.setOnClickListener(this);
        mBtLoginactivityRegister.setOnClickListener(this);
    

    public void onClick(View view) 
        switch (view.getId()) 
            case R.id.tv_loginactivity_register:
                startActivity(new Intent(this, RegisterActivity.class));
                finish();
                break;

            case R.id.bt_loginactivity_login:
                String email = mEtLoginactivityEmail.getText().toString().trim();
                String password = mEtLoginactivityPassword.getText().toString().trim();
                if (!TextUtils.isEmpty(email) && !TextUtils.isEmpty(password)) 
                    ArrayList<User> data = (ArrayList<User>) UserDBHelper.getAllUser();
                    boolean match = false;
                    boolean isAdmin = false;
                    for (int i = 0; i < data.size(); i++) 
                        User user = data.get(i);
                        if (email.equals(user.getEmail()) && password.equals(user.getPassword())) 
                            if (user.getType().equals("Admin"))
                                isAdmin = true;
                            match = true;
                            break;
                         else 
                            match = false;
                        
                    
                    if (match) 
                        SharedPreferences sp = getSharedPreferences("user",MODE_PRIVATE);
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString("e-mail", email);
                        editor.commit();
                        Toast.makeText(this, "Login successful", Toast.LENGTH_SHORT).show();
                        if (!isAdmin)
                        
                            Intent intent = new Intent(this, MainActivity.class);
                            startActivity(intent);
                        
                        else if (isAdmin)
                        
                            Intent intent = new Intent(this, AdminActivity.class);
                            startActivity(intent);
                        
                        finish();
                     else 
                        Toast.makeText(this, "Incorrect user name or password, please re-enter.", Toast.LENGTH_SHORT).show();
                    
                 else 
                    Toast.makeText(this, "Please enter your user name or password.", Toast.LENGTH_SHORT).show();
                
                break;
        
    

【问题讨论】:

我强烈建议您应该使用 Room 进行本地数据库 SQLite 操作,Room 让您的数据库操作变得非常简单 将一些日志 (Log.i()) 放入代码并验证用户的 type 是否等于 "Admin" 并且标志设置正确。我也强烈推荐使用Android-Debug-Database - 使用此工具您将能够验证数据库中存在的内容 感谢您建议我登录。我认为问题在于我在数据库助手中创建管理员。它将类型列为管理员而不是管理员,所以这是我的错误。 【参考方案1】:

在您的登录活动中

从 for 循环中删除以下行

 else  match = false;
for (int i = 0; i < data.size(); i++) 
User user = data.get(i);
if (email.equals(user.getEmail()) && password.equals(user.getPassword())) 
                            if (user.getType().equals("Admin"))
                                isAdmin = true;
                            match = true;
                            break;
                        
                    

如果您的电子邮件和密码匹配,则设置 match =true。但随后循环将继续进行下一次检查,它将在哪里设置 match=false。如果您只是尝试使用 for 循环查找匹配项,则不需要 else 条件。当您获得匹配项时,您应该在这种情况下停止循环,删除您设置 match=false 的 else 条件

【讨论】:

这是一个错误,但不是问题所在。如果 match 为 false,则两个 Activity 都不会打开。 如果匹配为假,就会显示“用户名和密码错误”,这不是应该的吗? 是的,它会显示“用户名不正确...”,但不会显示 MainActivity。问题是它总是显示 MainActivity。 现在我明白了你之前所说的,如果匹配为假,它不会打开任何活动,但有问题他说,它总是打开 MainActivity,只有当匹配为真时才会发生isAdmin=false,但是我还是看不到在循环中设置match=false的意义,因为匹配会变成false,如果数组的最后一个元素不匹配检查,这就是为什么我在答案 感谢您指出这一点。我没有意识到这个问题,但我现在删除了它。我也刚刚注意到在创建管理员用户时出现了问题,我将类型列为“管理员”而不是“管理员”。【参考方案2】:

这需要调试。我建议添加几行,以便您在 LogCat 中查看信息。

                        if (user.getType().equals("Admin"))
                            isAdmin = true;
                        else
                            Log.i("Match", user.getName() + " has type " +  user.getType() + " is not Admin");

如果您仍有问题,请将您的 LogCat 粘贴到此处向我们展示。

【讨论】:

谢谢!这有助于我诊断问题。

以上是关于Android Studio 无法进入管理页面的主要内容,如果未能解决你的问题,请参考以下文章

Android Studio:无法启动守护进程

通过按下 Android Studio 中的片段中的按钮进入新页面

Android Studio报:Connection timed out: connect. If you are behind an HTTP proxy错误

使用Android Studio创建Andorid模拟器

android studio 无法解析 webview 等等

无法按照 Google“入门”页面中的说明在 Android Studio 中添加地图; Android Studio 报错