Search code examples
androidandroid-sqlite

keep user logged in and logout successfully in android app sqlite database


I want to create a login activity which include navigation drawer so how can i keep user logged in and logout successfully.

This is the login code

MainAcitivity.java

package com.example.takeattendence;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.drawerlayout.widget.DrawerLayout;

import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.takeattendence.database.LoginContract.LoginEntry;
import com.example.takeattendence.database.LoginDbHelper;

public class MainActivity extends AppCompatActivity
{
    private LoginDbHelper mLoginDbHelper;

    EditText emailEditText, passwordEditText;
    Button loginButton;
    TextView newAccountTextView;
    String EmailHolder, PasswordHolder;
    Boolean EditTextEmptyHolder;
    SQLiteDatabase db;
    Cursor cursor;
    String TempPassword = "NOT_FOUND" ;
    public static final String UserEmail = "";
    SharedPreferences sp;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        newAccountTextView = (TextView) findViewById(R.id.textview_create_new_account_sign_in);
        loginButton = (Button) findViewById(R.id.button_login);
        emailEditText = (EditText) findViewById(R.id.editText_email_sign_in);
        passwordEditText = (EditText) findViewById(R.id.editText_pass_sign_in);

        mLoginDbHelper = new LoginDbHelper(this);

        //Adding click listener to log in button.
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                // Calling EditText is empty or no method.
                CheckEditTextStatus();

                // Calling login method.
                LoginFunction();
            }
        });



        newAccountTextView.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent i = new Intent(MainActivity.this,NewAccount.class);
                startActivity(i);
            }
        });


    }

    @Override
    public void onBackPressed()
    {
        moveTaskToBack(true);
    }




    // Checking EditText is empty or not.
    public void CheckEditTextStatus()
    {

        // Getting value from All EditText and storing into String Variables.
        EmailHolder = emailEditText.getText().toString();
        PasswordHolder = passwordEditText.getText().toString();

        // Checking EditText is empty or no using TextUtils.
        if( TextUtils.isEmpty(EmailHolder) || TextUtils.isEmpty(PasswordHolder))
        {

            EditTextEmptyHolder = false ;

        }
        else
        {
            EditTextEmptyHolder = true ;
        }
    }

    // Login function starts from here.
    public void LoginFunction()
    {

        if(EditTextEmptyHolder)
        {

            // Opening SQLite database write permission.
            db = mLoginDbHelper.getWritableDatabase();

            // Adding search email query to cursor.
            cursor = db.query(LoginEntry.TABLE_NAME, null, " " + LoginEntry.COLUMN_EMAIL_ID + "=?", new String[]{EmailHolder}, null, null, null);

            while (cursor.moveToNext())
            {

                if (cursor.isFirst())
                {

                    cursor.moveToFirst();

                    // Storing Password associated with entered email.
                    TempPassword = cursor.getString(cursor.getColumnIndex(LoginEntry.COLUMN_PASSWORD));

                    // Closing cursor.
                    cursor.close();
                }
            }

            // Calling method to check final result ..
            CheckFinalResult();

        }
        else
        {

            //If any of login EditText empty then this block will be executed.
            Toast.makeText(MainActivity.this,"Please Enter UserName or Password.",Toast.LENGTH_LONG).show();

        }



    }

    // Checking entered password from SQLite database email associated password.
    public void CheckFinalResult()
    {

        if(TempPassword.equalsIgnoreCase(PasswordHolder))
        {

            Toast.makeText(MainActivity.this,"Login Successfully",Toast.LENGTH_LONG).show();

            // Going to Dashboard activity after login success message.
            Intent intent = new Intent(MainActivity.this, WelcomeApp.class);

            // Sending Email to Dashboard Activity using intent.
            intent.putExtra(UserEmail, EmailHolder);

            startActivity(intent);


        }
        else {

            Toast.makeText(MainActivity.this,"UserName or Password is Wrong, Please Try Again.",Toast.LENGTH_LONG).show();

        }
        TempPassword = "NOT_FOUND" ;
    }
  }

This is the navigation drawer code which including logout option how can i logout successfully

WelcomeApp.java

package com.example.takeattendence;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.MenuItem;

import com.google.android.material.navigation.NavigationView;

public class WelcomeApp extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener
{
    private DrawerLayout drawerLayout;

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

        Toolbar toolbar = findViewById(R.id.nav_toolbar);
        setSupportActionBar(toolbar);

        drawerLayout = findViewById(R.id.drawer_layout);

        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,
                R.string.navigation_drawer_open,R.string.navigation_drawer_close);

        drawerLayout.addDrawerListener(actionBarDrawerToggle);
        actionBarDrawerToggle.syncState();

        if(savedInstanceState == null)
       {
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    new ProfileFragment()).commit();


            navigationView.setCheckedItem(R.id.nav_profile);
        }

    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem)
    {
        switch (menuItem.getItemId())
        {
            case R.id.nav_profile:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new ProfileFragment()).commit();
                break;

            case R.id.nav_update_profile:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new UpdateProfileFragment()).commit();
                break;

            case R.id.nav_see_database:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new StudenetInfoFragment()).commit();
                break;

            case R.id.nav_logout:
                Intent in = new Intent(WelcomeApp.this,MainActivity.class);
                startActivity(in);
                finish();

                break;

            default:
        }

        drawerLayout.closeDrawer(GravityCompat.START);
        return true;
    }
    @Override
    public void onBackPressed()
    {
        moveTaskToBack(true);
    }
}

I used sharepreference class but not get proper solution


Solution

  • Using shared preferences should do the trick....you can use it as below:

    in login page (MainActivity.java) when user email password matches:

    SharedPreferences.Editor editor = getSharedPreferences("name", MODE_PRIVATE).edit();
    editor.putString("email", emailVlaue);
    editor.putString("password", passwordValue);
    editor.putBoolean("isLoggedIn", true);
    //any other detail you want to save
    editor.apply();
    

    when you open this activity

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    SharedPreferences prefs = getSharedPreferences("name", MODE_PRIVATE);
    boolean isLoggedIn= prefs.getBoolean("isLoggedIn", false);
    
    if(isLoggedIn){
        startActivity(new Intent(getApplicationContext(),WelcomeApp.class)
        finish();
        return;
    }
    setContentView(R.layout.activity_home);
    //your other codes
    

    this will redirect user to WelcomeApp activity if they are logged in

    to log out once the user clicks logOut button

    SharedPreferences.Editor editor = getSharedPreferences("name", MODE_PRIVATE).edit();
    editor.putString("password", "");
    editor.putString("email", "");
    editor.putBoolean("isLoggedIn", false);
    editor.apply();
    
    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
    intent.putExtra("finish", true);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
    
    finish();