Parth Mahajan
Parth Mahajan

Reputation: 119

How to make an android app remember my username?

I made a chat room app which asks the user to enter its username every time i open it. How can i make it remember me? I am using fire-base for the back end.

See Code Here

Upvotes: 1

Views: 2000

Answers (3)

nullvoid
nullvoid

Reputation: 131

SharedPreferencec prefs = getSharedPreferences("username",Context.MODE_PRIVATE);
SharedPreference.Editor editor = prefs.edit();
if (!prefs.getString("username",null)
   //do the chatting
else {
   //show dialog to get username
   //now save it in shared preferences
   editor.putString("username",username);
   editor.commit();
}

Upvotes: 0

Abhi
Abhi

Reputation: 2285

You can use shared preference. Say you are saving username in String called User. To save username:

SharedPreferences shareit = getSharedPreferences("KEY",Context.MODE_PRIVATE);
                    SharedPreferences.Editor eddy = shareit.edit();
                    eddy.putString("AKEY", User);
                    eddy.commit();

And everytime user login:

SharedPreferences sharedPreferences = getContext().getSharedPreferences("KEY", Context.MODE_PRIVATE);
    String getName = sharedPreferences.getString("AKEY", "");

String getName will have the value of your username. The "KEY" and "AKEY" used above are to give special id to different values saved via shared preference.

Upvotes: 2

eLemEnt
eLemEnt

Reputation: 1801

Create Shared Preference class where first time when user enter his/her username store it.

You can read more about Shared Preference here

The for you as follows

public class SharePref {

    public static final String PREF_NAME = "chatroom.shared.pref";
    public static final String PREF_KEY = "chatroom.shared.username";

    public SharePref() {
    }

    public void save(Context context, String text) {
        SharedPreferences sharePref;
        SharedPreferences.Editor editor;
        sharePref = context.getSharedPreferences(PREF_NAME,Context.MODE_PRIVATE);
        editor = sharePref.edit();
        editor.putString(PREF_KEY,text);
        editor.apply();
    }

    public String getData(Context context) {
        SharedPreferences sharePref;
        String text;
        sharePref = context.getSharedPreferences(PREF_NAME,Context.MODE_PRIVATE);
        text = sharePref.getString(PREF_KEY,null);
        return text;
    }
}

Now in your MainActivity you can check if you have already stored the username for user

inside your onCreate()

    SharePref sharePref = new SharePref();
    String UserName = sharePref.getData(mContext);
    if(UserName == null) {
       String value = //username value;
       SharePref sharePref = new SharePref();
       sharePref.save(context,value);
    }
    else {
          // you already have username do your stuff
    }

Hope this will help

Upvotes: 2

Related Questions