So I am new to Android Studio and I am trying to make a login page. In my DB I created user_type attribute and if the user type is Admin, I want the login screen to redirect to the Admin Page instead of the normal home page. I tried using if-else statement for the intent, but it still always redirects me to the MainActivity class even though my user_type is already "Admin". Can anyone help tell me the problem? Thanks in advance.
Here is my User class:
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;
}
}
This is my 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","[email protected]","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 = '[email protected]';
*/
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 = '[email protected]' 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;
}
}
And this is my LoginActivity class:
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;
}
}
}
2
Answers
in your LoginActivity
remove the following line from the for loop
if your email and password got a match then u set match =true. but then the loop gonna keep continue to the next checking where its gonna set match=false. u don’t need an else condition if u are just trying to find a match using for loop. when u get a match u should stop the loop in this case remove the else condition where u set match=false
Well this need a debug. I suggest add several lines so you see information in LogCat.
If you still have problem, paste your LogCat to show us here.