Blog purpose for android basic example for android app developer. any query please my contact

Sunday, 13 December 2020

sharedpreferences login example in android

sharedpreferences login example in android

 In this Article Today learn sharedpreferences login example in android. for the follow full source code sharedpreferences login example in android.


1.MainActivity.java:

package com.akash.sharedpreferance;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;

import android.app.LoaderManager.LoaderCallbacks;
import android.content.ContentResolver;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build.VERSION;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

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

import static android.Manifest.permission.READ_CONTACTS;

/**
 * A login screen that offers login via email/password.
 */
public class MainActivity extends AppCompatActivity {


   
// UI references.
   
private EditText mEmailView;
   
private EditText mPasswordView;

   
private CheckBox checkBoxRememberMe;

   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);
       
// Set up the login form.
       
mEmailView = (EditText) findViewById(R.id.email);
       
mPasswordView = (EditText) findViewById(R.id.password);
       
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
           
@Override
           
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
               
if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    
return true;
                }
               
return false;
            }
        });

        Button mEmailSignInButton = (Button) findViewById(R.id.
email_sign_in_button);
        mEmailSignInButton.setOnClickListener(
new OnClickListener() {
            
@Override
           
public void onClick(View view) {
                attemptLogin();
            }
        });

       
checkBoxRememberMe = (CheckBox) findViewById(R.id.checkBoxRememberMe);
       
//Here we will validate saved preferences
       
if (!new PrefManager(this).isUserLogedOut()) {
           
//user's email and password both are saved in preferences
           
startHomeActivity();
        }

    }


   
/**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
   
private void attemptLogin() {

       
// Reset errors.
       
mEmailView.setError(null);
        
mPasswordView.setError(null);

       
// Store values at the time of the login attempt.
       
String email = mEmailView.getText().toString();
        String password =
mPasswordView.getText().toString();

       
boolean cancel = false;
        View focusView =
null;

       
// Check for a valid password, if the user entered one.
       
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
           
mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView =
mPasswordView;
            cancel =
true;
        }

       
// Check for a valid email address.
       
if (TextUtils.isEmpty(email)) {
           
mEmailView.setError(getString(R.string.error_field_required));
            focusView =
mEmailView;
            cancel =
true;
        }
else if (!isEmailValid(email)) {
           
mEmailView.setError(getString(R.string.error_invalid_email));
            focusView =
mEmailView;
            cancel =
true;
        }

       
if (cancel) {
           
// There was an error; don't attempt login and focus the first
            // form field with an error.
           
focusView.requestFocus();
        }
else {
           
// save data in local shared preferences
           
if (checkBoxRememberMe.isChecked())
                saveLoginDetails(email, password);
            startHomeActivity();
        }
    }

   
private void startHomeActivity() {
        Intent intent =
new Intent(this, HomeActivity.class);
        startActivity(intent);
        finish();
    }

   
private void saveLoginDetails(String email, String password) {
       
new PrefManager(this).saveLoginDetails(email, password);
    }


   
private boolean isEmailValid(String email) {
       
//TODO: Replace this with your own logic
       
return email.contains("@");
    }

   
private boolean isPasswordValid(String password) {
       
//TODO: Replace this with your own logic
       
return password.length() > 4;
    }
}

 

 


2.activity_main.xml:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
xmlns:tools="http://schemas.android.com/tools"
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
android:gravity="center_horizontal"
   
android:orientation="vertical"
    
android:paddingBottom="@dimen/activity_vertical_margin"
   
android:paddingLeft="@dimen/activity_horizontal_margin"
   
android:paddingRight="@dimen/activity_horizontal_margin"
   
android:paddingTop="@dimen/activity_vertical_margin"
   
tools:context=".MainActivity">

   
<!-- Login progress -->
   
<ProgressBar
       
android:id="@+id/login_progress"
       
style="?android:attr/progressBarStyleLarge"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_marginBottom="8dp"
       
android:visibility="gone"/>

    <
ScrollView
       
android:id="@+id/login_form"
       
android:layout_width="match_parent"
       
android:layout_height="match_parent">

        <
LinearLayout
           
android:id="@+id/email_login_form"
           
android:layout_width="match_parent"
           
android:layout_height="wrap_content"
           
android:orientation="vertical">

            <
android.support.design.widget.TextInputLayout
               
android:layout_width="match_parent"
               
android:layout_height="wrap_content">

                <
EditText
                   
android:id="@+id/email"
                   
android:layout_width="match_parent"
                   
android:layout_height="wrap_content"
                   
android:hint="@string/prompt_email"
                   
android:inputType="textEmailAddress"
                   
android:maxLines="1"
                   
android:singleLine="true"/>

            </
android.support.design.widget.TextInputLayout>

            <
android.support.design.widget.TextInputLayout
               
android:layout_width="match_parent"
               
android:layout_height="wrap_content">

                <
EditText
                   
android:id="@+id/password"
                   
android:layout_width="match_parent"
                   
android:layout_height="wrap_content"
                   
android:hint="@string/prompt_password"
                   
android:imeActionId="@+id/login"
                   
android:imeActionLabel="@string/action_sign_in_short"
                   
android:imeOptions="actionUnspecified"
                   
android:inputType="textPassword"
                   
android:maxLines="1"
                   
android:singleLine="true"/>

            </
android.support.design.widget.TextInputLayout>

            <
CheckBox
               
android:layout_width="match_parent"
               
android:layout_height="wrap_content"
               
android:text="Remember Me"
               
android:id="@+id/checkBoxRememberMe"/>

            <
Button
               
android:id="@+id/email_sign_in_button"
               
style="?android:textAppearanceSmall"
               
android:layout_width="match_parent"
               
android:layout_height="wrap_content"
               
android:layout_marginTop="16dp"
               
android:text="@string/action_sign_in"
               
android:textStyle="bold"/>

        </
LinearLayout>
    </
ScrollView>
</
LinearLayout>



3.PrefManager.java:


package com.akash.sharedpreferance;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * Class for Shared Preference
 */
public class PrefManager {

    Context
context;

    PrefManager(Context context) {
       
this.context = context;
    }

   
public void saveLoginDetails(String email, String password) {
        SharedPreferences sharedPreferences =
context.getSharedPreferences("LoginDetails", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(
"Email", email);
        editor.putString(
"Password", password);
        editor.commit();
    }

   
public String getEmail() {
        SharedPreferences sharedPreferences =
context.getSharedPreferences("LoginDetails", Context.MODE_PRIVATE);
       
return sharedPreferences.getString("Email", "");
    }

   
public boolean isUserLogedOut() {
        SharedPreferences sharedPreferences =
context.getSharedPreferences("LoginDetails", Context.MODE_PRIVATE);
       
boolean isEmailEmpty = sharedPreferences.getString("Email", "").isEmpty();
       
boolean isPasswordEmpty = sharedPreferences.getString("Password", "").isEmpty();
       
return isEmailEmpty || isPasswordEmpty;
    }
}
 

4.HomeActivity.java:

package com.akash.sharedpreferance;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

public class HomeActivity extends AppCompatActivity {

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

 


5.activity_home.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
   
xmlns:android="http://schemas.android.com/apk/res/android"
   
xmlns:app="http://schemas.android.com/apk/res-auto"
   
xmlns:tools="http://schemas.android.com/tools"
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
android:paddingBottom="@dimen/activity_vertical_margin"
   
android:paddingLeft="@dimen/activity_horizontal_margin"
   
android:paddingRight="@dimen/activity_horizontal_margin"
   
android:paddingTop="@dimen/activity_vertical_margin"
   
app:layout_behavior="@string/appbar_scrolling_view_behavior"
   
tools:context=".HomeActivity"
   
tools:showIn="@layout/activity_home">

    <
TextView
        
android:id="@+id/textViewUser"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_centerInParent="true"
       
android:gravity="center"
       
android:text="Welcome"/>


</
RelativeLayout>



6.Dimen.xml:

 <resources>


    <!-- Default screen margins, per the Android Design guidelines. -->
   
<dimen name="activity_horizontal_margin">16dp</dimen>
    <
dimen name="activity_vertical_margin">16dp</dimen>
    <
dimen name="nav_header_vertical_spacing">8dp</dimen>
    <
dimen name="nav_header_height">176dp</dimen>
    <
dimen name="fab_margin">16dp</dimen>
</
resources>


7.manifest.xml:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   
package="com.akash.sharedpreferance">

    <
application
       
android:allowBackup="true"
       
android:icon="@mipmap/ic_launcher"
       
android:label="@string/app_name"
       
android:roundIcon="@mipmap/ic_launcher_round"
       
android:supportsRtl="true"
       
android:theme="@style/AppTheme">
        <
activity android:name=".HomeActivity"></activity>
        <
activity android:name=".MainActivity">
            <
intent-filter>
                <
action android:name="android.intent.action.MAIN" />

                <
category android:name="android.intent.category.LAUNCHER" />
            </
intent-filter>
        </
activity>
    </
application>

</
manifest>

 


 





No comments:

Post a Comment