Home > front end >  How can I keep the user logged in when I reopens the app android studio
How can I keep the user logged in when I reopens the app android studio

Time:02-12

I have made the app and using the sqlite database I stored the details in the database. But now I want to verify and keep the user logged in and if the user is logged in directly next activity should be opened. Can any one help me with that.

This is the Login activity:

     private TextInputEditText mobileedittext,passwordedittext;
private DBase dBase;
private User user;

public static String PREFS = "prefsFile";
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    initview();
    initListener();
    initObject();

}

private void initview(){
    layout = findViewById(R.id.login_layout);

    lay_login_mobile = findViewById(R.id.lay_login_mobile);
    lay_login_password = findViewById(R.id.lay_login_password);

    mobileedittext = findViewById(R.id.loginmobile_edit);
    passwordedittext = findViewById(R.id.loginpassword_edit);

    b1 = findViewById(R.id.Loginbtn);

}

private void initListener(){
    b1.setOnClickListener(v -> {


        String mob = mobileedittext.getText().toString();
        String pass = passwordedittext.getText().toString();
        if(mob.equals("") || pass.equals("")){
            Toast.makeText(Login.this, "Enter all the fields", Toast.LENGTH_SHORT).show();

        } else {
            if(!dBase.checkUser(mobileedittext.getText().toString(),passwordedittext.getText().toString())) {
                Toast.makeText(Login.this, "Invalid Credentials. Check Mobile number or Password", Toast.LENGTH_LONG).show();
            }
            else {
                Toast.makeText(Login.this, "Login Successful", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(Login.this, BabyDetails.class);
                startActivity(intent);
            }
        }
        SharedPreferences sharedPreferences = getSharedPreferences(Login.PREFS,0);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean("hasLoggedIn",true);
        editor.commit();
    });
}

private void initObject(){
    dBase = new DBase(Login.this);
    user = new User();
}

The Main Activity(Splash screen) :

  ProgressBar pb;
Handler h = new Handler();
int count = 0;
Timer timer;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



    pb = (ProgressBar) findViewById(R.id.progressBar);

    timer = new Timer();
    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            count  ;
            pb.setProgress(count);
            if(count == 99){
                h.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        SharedPreferences sharedPreferences = getSharedPreferences(Login.PREFS,0);
                        Boolean hasLoggedIn = sharedPreferences.getBoolean("hasLoggedIn",false);

                        if(hasLoggedIn){
                            Intent intent = new Intent(MainPage.this,BabyDetails.class);
                            startActivity(intent);
                            finish();
                        }
                        else {
                            Intent i = new Intent(MainPage.this, Login.class);
                            startActivity(i);
                            finish();
                        }


                    }
                },100);


            }
        }
    };
    timer.schedule(timerTask,0,100);

the database contains the checkuser function it check if the user is already existed but now it should check if the user is logged in also :

        private static final String DATABASE_NAME = "UserDetails.db";
private static final String TABLE_USER = "User";
private static final String COLUMN_USER_ID = "user_id";
private static final String COLUMN_USER_MOBILE = "mobile";
private static final String COLUMN_USER_EMAIL = "email";
private static final String COLUMN_USER_MOTHERNAME = "mother_name";
private static final String COLUMN_USER_FATHERNAME = "father_name";
private static final String COLUMN_USER_PASSWORD = "password";
private static final String COLUMN_USER_CONFIRM_PASSWORD = "confirm_password";


private String CREATE_USER_TABLE = "CREATE TABLE  "  TABLE_USER   "("  
        COLUMN_USER_ID  " INTEGER PRIMARY KEY AUTOINCREMENT , "   COLUMN_USER_MOBILE   " TEXT,"   COLUMN_USER_EMAIL   " TEXT, "
          COLUMN_USER_MOTHERNAME   " TEXT, "   COLUMN_USER_FATHERNAME   " TEXT, "  
        COLUMN_USER_PASSWORD   " TEXT, "   COLUMN_USER_CONFIRM_PASSWORD   " TEXT "   ")";




private String DROP_USER_TABLE = "DROP TABLE IF EXISTS "   TABLE_USER;

public DBase(Context context){
    super(context,DATABASE_NAME,null,DATABASE_VERSION);

}




@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_USER_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
     db.execSQL(DROP_USER_TABLE);
    onCreate(db);
}

public void addUser(User user){
    SQLiteDatabase db= this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(COLUMN_USER_MOBILE,user.getMobile());
    values.put(COLUMN_USER_EMAIL,user.getEmail());
    values.put(COLUMN_USER_MOTHERNAME,user.getMothername());
    values.put(COLUMN_USER_FATHERNAME,user.getFathername());
    values.put(COLUMN_USER_PASSWORD,user.getPass());
    values.put(COLUMN_USER_CONFIRM_PASSWORD,user.getConpass());
    db.insert(TABLE_USER,null,values);
    db.close();
}
 public boolean checkUser(String mobile, String pass ){

    String[] column = {COLUMN_USER_ID};
    SQLiteDatabase db= this.getReadableDatabase();
    String selection = COLUMN_USER_MOBILE  " = ? "   " AND "   COLUMN_USER_PASSWORD   " = ? ";
    String[] selectionArgs = {mobile, pass};

    int cursorCount;
    try (Cursor cursor = db.query(TABLE_USER, column, selection, selectionArgs, null, null, null)) {
        cursorCount = cursor.getCount();
    }
    db.close();
    if(cursorCount > 0){
        return true;
    }

    return false;
}

Can anybody provide the necessary codes for it and explain it also .

Thank you

CodePudding user response:

When You Login In LoginActivity Just Set SharedPreference

   public static final String MyPREFERENCES = "MyPrefs" ;
   public static final String Name = "nameKey";

In OnCreate()

SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.commit();

And In MainActivity

  SharedPreferences sharedpreferences = getSharedPreferences(MainActivity.MyPREFERENCES, Context.MODE_PRIVATE);
  SharedPreferences.Editor editor = sharedpreferences.edit();
  editor.clear();
  editor.commit();
  • Related