0

I am working in remember me function in android where i have stored the username and password in storage class,the storage class is the class where i implement the Shared preferences.

What i have done

First i am checking that if the checkbox is checked or not if ischecked then i store the value in storage class(shared preferences).and in login service i am calling the username with password.

Here is the code:

Inside OnCreate

boolean isChecked = true;

    login_submit_btn.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    LoginService();
                }
            });


    chkRememberMe.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()      
            {   
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(isChecked){
                         storage.saveUserName(Login.this, mUserName);
                         storage.savepass(Login.this, mPassword);


                    }
                }
            });
    }

outside:

protected void LoginService() {
    // TODO Auto-generated method stub




        mUserName = login_email_edit.getText().toString().trim();
        mPassword = login_password_edit.getText().toString().trim();

         if (chkRememberMe.isChecked()) {

            mUserName=storage.getUserName(Login.this);
            mPassword=storage.getpass(Login.this);

         }


    if (mUserName.length() == 0) {
        AlertDialog(" Enter  Email ", Login.this);
    } else if (isContainsEmpty(mUserName)) {
        login_submit_btn.setEnabled(true);
    AlertDialog("Valid Email Address", Login.this);
    } 

    else if(mPassword.length() == 0){
        AlertDialog("Password should not be blank", Login.this);
    }
    }

Can anybody figure out my mistake .@Thanks

4 Answers4

1

Your code doesn't seem to be right, you are saving the credentials but not removing them anywhere. Also what if I change the username and password and the remember me is already checked, your code doesn't save the credentials. Remove the setOnCheckedChangeListener, it is of no use.

This should be the process:

  1. When you enter your login activity, you should check if any credentials are already stored, if they are you should show them in your TextViews(UserName and Password fields) and the remember me checkbox should be checked by default.

  2. Now if there are no credentials stored previously (e.g. first time login) you don't show anything and when the user pressed login button and the login is successfull

    2.1. If the remember me was checked then you should save the credentials.

    2.2. else if it was unchecked clear the credentials

EDIT:

remove setOnCheckedChangeListener

in the onCreate method after

email=storage.getUserName(Login.this);
password=storage.getpass(Login.this); 

Put

login_email_edit.setText(email); 
login_password_edit.setText(password); 

Now inside login service

if(chkRememberMe.isChecked()) {
    storage.saveUserName(Login.this, mUserName);
    storage.savepass(Login.this, mPassword);
}else
    {
    storage.saveUserName(Login.this, "");
    storage.savepass(Login.this, "");
}

delete the app and install again

Naveen
  • 1,703
  • 13
  • 22
  • Thanks! All the things i have to do in OnCreate method –  May 20 '13 at 07:37
  • yes getting the credentials must be done in OnCreate but saving and removing the credentials must be done after a login press. – Naveen May 20 '13 at 07:50
  • in OnCreate i am calling email=storage.getUserName(Login.this); password=storage.getpass(Login.this); and in side login service assigning login_email_edit.setText(email); login_password_edit.setText(password); Still not working –  May 20 '13 at 08:10
  • you are doing this wrong, think about what is required here. Put login_email_edit.setText(email); login_password_edit.setText(password); in the `onCreate` method after email=storage.getUserName(Login.this);password=storage.getpass(Login.this); – Naveen May 20 '13 at 08:27
  • yes i tried this ..still it is not working actually i am clearing the session during logout ..editor.clear ,Is there any problem regarding that!! –  May 20 '13 at 08:39
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/30243/discussion-between-naveen-and-priya2134412) – Naveen May 20 '13 at 08:43
0

I do the same function too.

here is my code for reference. See if this can help you :D

SharedPreferences mSharedPreferences = getSharedPreferences("myapp_uid", 0);
SharedPreferencesEditor mSharedPreferencesEditor = mSharedPreferences.edit();
App.mSharedPreferencesEditor.putString("index", "value");
if(!App.mSharedPreferencesEditor.commit()){
    // Error message here 
}

Furthermore, I store it in class as static method.

public static boolean setPref(String index, String value){
  App.mSharedPreferencesEditor.putString("index", "value");
  return App.mSharedPreferencesEditor.commit();
}

public static String getPref(String index){
 .....
}

:: Edited

inside

boolean isChecked = true;

    login_submit_btn.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    LoginService();
                }
            });
    }

outside

  protected void LoginService() {
    // TODO Auto-generated method stub
        mUserName = login_email_edit.getText().toString().trim();
        mPassword = login_password_edit.getText().toString().trim();

         if (chkRememberMe.isChecked()) {

           storage.saveUserName(Login.this, mUserName);
           storage.savepass(Login.this, mPassword);

         } else {

           storage.saveUserName(Login.this, "");
           storage.savepass(Login.this, "");

         }


    if (mUserName.length() == 0) {
        AlertDialog(" Enter  Email ", Login.this);
    } else if (isContainsEmpty(mUserName)) {
        login_submit_btn.setEnabled(true);
    AlertDialog("Valid Email Address", Login.this);
    } 

    else if(mPassword.length() == 0){
        AlertDialog("Password should not be blank", Login.this);
    }
    }
Jeff Lee
  • 783
  • 9
  • 17
  • Do you have any error trace?? Or there is not error but not work?? – Jeff Lee May 20 '13 at 07:25
  • mUserName=storage.getUserName(Login.this); mPassword=storage.getpass(Login.this); You should put it in side onCreate?? Then the prev. login username and password will show after the application just load. – Jeff Lee May 20 '13 at 07:30
  • in OnCreate i am calling email=storage.getUserName(Login.this); password=storage.getpass(Login.this); and in side login service assigning login_email_edit.setText(email); login_password_edit.setText(password); Still not working –  May 20 '13 at 08:11
  • Can you post the custom method inside class Storage? Did you commit after you putString and using the editor? – Jeff Lee May 20 '13 at 08:15
  • Actually during logout i am clearing the session is there any problem on that –  May 20 '13 at 08:26
  • I dont think the session affect the storage problem. I make some change on your code, If the code in storage is correct. Above code show work :D – Jeff Lee May 20 '13 at 08:36
  • when to get the username and password –  May 20 '13 at 08:45
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/30244/discussion-between-jeff-lee-and-priya2134412) – Jeff Lee May 20 '13 at 08:48
0

I use Sharedpreference for this same functionality,

EditText login_email_edit=(EditText)findViewById(R.id.editText1);
    Button login_submit_btn=(Button)findViewById(R.id.button1);
    final CheckBox chkRememberMe=(CheckBox)findViewById(R.id.checkBox1);


    SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
     editor = pref.edit();

     if(pref.getString("key_username", null)!=null)
     {

         text.setText(pref.getString("key_username", null));//Here we retrieve username from shared preference and set it to edittext. 

     }

     login_submit_btn.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                          if(chkRememberMe.isChecked())
                    {

                         editor.putString("key_username", text.getText().toString()); 
                         editor.commit(); 
                         LoginService();//Now your username is stored in shared preference

                    }

                    else
                    {
                        //Username is not stored.because remember me is unchecked
                        LoginService();
                    }




                }
            });
Basim Sherif
  • 5,384
  • 7
  • 48
  • 90
  • After Login Every thing working fine after switchoff and switch on the device without logout once again asking login details.how to handel please helpme – Harsha Oct 17 '13 at 05:07
  • am using one global boolean variable based on that status i can check if logged in or not – Harsha Oct 17 '13 at 09:21
  • @Harsha : don't use global variable, just check whether the sharedpreference values for username and password are null or not. if its null, the user is not logged in. Otherwise there will be username and password stored in sharedpreference. So the user is logged in. – Basim Sherif Oct 18 '13 at 03:59
0

COMPLETE REMEMBER ME FUNCTIONALITY USING SHARED PRFERENCES

xml:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context=".MainActivity">

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

        <EditText
            android:id="@+id/etUserName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:hint="Username"
            android:padding="10dp" />

        <EditText
            android:id="@+id/etPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Password"
            android:padding="10dp" />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@id/etPassword"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/ivRememberMe"
                android:layout_width="35dp"
                android:layout_height="35dp"
                android:layout_centerVertical="true"
                android:src="@drawable/holo_circle" />

            <TextView
                android:id="@+id/tvRememberMe"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="6dp"
                android:layout_toRightOf="@+id/ivRememberMe"
                android:text="Remember Me"
                android:textAppearance="?android:attr/textAppearanceSmall" />
        </RelativeLayout>

        <Button
            android:id="@+id/btnSignIn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dp"
            android:text="Sign in"
            android:textColor="@android:color/white" />
    </LinearLayout>

</RelativeLayout>

Login class:

    public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private ImageView ivRememberMe;
    private Button btnLogin;
    private EditText etUserName, etPassword;
    private String userName, password;
    private static boolean rememberMe;
    String USERNAME = "username";
    String PASSWORD = "password";
    String REMEMBER_ME = "remember me";

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

        initValues();
    }

    private void initValues() {
        try {
            btnLogin = (Button) findViewById(R.id.btnSignIn);
            btnLogin.setOnClickListener(this);

            etUserName = (EditText) findViewById(R.id.etUserName);
            etPassword = (EditText) findViewById(R.id.etPassword);

            //Persist credentials, if remember me is checked
            SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
            if (pref.contains(USERNAME) && pref.contains(PASSWORD)) {
                etUserName.setText(pref.getString(USERNAME, ""));
                etPassword.setText(pref.getString(PASSWORD, ""));
                if (pref.getBoolean(REMEMBER_ME, true)) {
                    ((ImageView) findViewById(R.id.ivRememberMe)).setImageResource(R.drawable.checkbox_marked_circle);
                }
            }
            ivRememberMe = (ImageView) findViewById(R.id.ivRememberMe);
            ivRememberMe.setOnClickListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onClick(View v) {
        try {
            switch (v.getId()) {
                case R.id.btnSignIn:
                    validateCredentials();
                    onLogin();
                    break;
                case R.id.ivRememberMe:
                    rememberMe = !rememberMe;
                    ((ImageView) findViewById(R.id.ivRememberMe)).setImageResource(rememberMe ? R.drawable.checkbox_marked_circle : R.drawable.holo_circle);
                    checkPersistCredentials(etUserName.getText().toString().trim(), etPassword.getText().toString());
                    break;
                default:
                    break;

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void validateCredentials() {
        try {
            userName = etUserName.getText().toString();
            password = etPassword.getText().toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void onLogin() {
        //implement your login logic
    }


    private void checkPersistCredentials(String userName, String password) {
        rememberMe(userName, password, this);
    }

    public void rememberMe(final String username, String password, Context context) {
        try {

            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            SharedPreferences.Editor edit = sharedPreferences.edit();
            if (rememberMe) {
                if (username.isEmpty() && password.isEmpty()) {

                } else {
                    edit.putString(USERNAME, username);
                    edit.putString(PASSWORD, password);
                    edit.putBoolean(REMEMBER_ME, true);
                    edit.commit();
                }
            } else {
                edit.clear();
                edit.commit();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
musica
  • 1,373
  • 3
  • 15
  • 34