How to make an android app remember my username? - android

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

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

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.

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();
}

Related

unable to update values using shared preferences

I am unable to to show updated values in edit text. I have database on server. I am updating user values using retrofit. On server values updates successfully but when i revisit the profile page it shows the values populated from shared preferences. On login i save values in shared preferences and throughout application uses these values.
The code for saving and retrieving the values is below:
Get and set email address in shared preferences
public void putEmail(String loginorout) {
SharedPreferences.Editor edit = app_prefs.edit();
edit.putString(EMAIL, loginorout);
edit.apply();
}
public String getEmail() {
return app_prefs.getString(EMAIL, "");
}
Retrieve values from shared preferences
accountETSU1.setText(preferenceHelper.getEmail());
It's more simple if you create a object called PreferenceHelper, in that object you create a static string for the name of the email like:
final String emailUser = "emailUser";
With that string you create 2 functions one to write:
public void writeEmail(String : email, Context : context){
SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(emailUser, email);
editor.commit();
}
The other one to get :
public String getEmail(Context : context){
SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE);
String email = sharedPref.getString(emailUser, "");
return email;
}
Then call the object in your activity
Context context = this#YourActivity;
accountETSU1.setText(PreferenceHelper.getEmail(context));

How to redirect user based on the user's role to different activities in android

I'm new to android development. I would like to create an app with at least 2 user roles. I want the users to be redirected to different activities after their login. I read that it is possible to do that using firebase, but I would not like to use it in my application, since I already started building the app and used retrofit and shared preferences so far. I also found another question her asking the same question and someone answered that it is possible to do so with sessionManager class.
Their answer was:
"Well, I would like to provide my own answer. I actually used Shared Preferences. Its much simple and could globally use the values we put in it. Below is the code:
1. Create a separate class and name it as you wish(I prefer SessionManager here)
public class SessionManager {
// Shared Preferences
SharedPreferences sharedPrefer;
// Editor for Shared preferences
SharedPreferences.Editor editor;
// Context
Context context;
// Shared Pref mode
int PRIVATE_MODE = 0;
// Shared Pref file name
private static final String PREF_NAME = "MySession";
// SHARED PREF KEYS FOR ALL DATA
// User's UserId
public static final String KEY_USERID = "userId";
// User's categoryId
public static final String KEY_CATID = "catId";
// User's categoryType[Teacher, Student, etc.,]
public static final String KEY_CATTYPE = "categoryType";
// User's batchId[like class or level or batch]
public static final String KEY_BATCHID = "batchId";
// Constructor
public SessionManager(Context context) {
this.context = context;
sharedPrefer = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = sharedPrefer.edit();
}
/**
* Call this method on/after login to store the details in session
* */
public void createLoginSession(String userId, String catId, String catTyp, String batchId) {
// Storing userId in pref
editor.putString(KEY_USERID, userId);
// Storing catId in pref
editor.putString(KEY_CATID, catId);
// Storing catType in pref
editor.putString(KEY_CATTYPE, catTyp);
// Storing catType in pref
editor.putString(KEY_BATCHID, batchId);
// commit changes
editor.commit();
}
/**
* Call this method anywhere in the project to Get the stored session data
* */
public HashMap<String, String> getUserDetails() {
HashMap<String, String> user = new HashMap<String, String>();
user.put("userId",sharedPrefer.getString(KEY_USERID, null));
user.put("batchId",sharedPrefer.getString(KEY_BATCHID, null));
user.put("catId", sharedPrefer.getString(KEY_CATID, null));
user.put("catType", sharedPrefer.getString(KEY_CATTYPE, null));
return user;
}
}
2. Calling the above methods on some other classes inside the project:
Storing the data in session
SessionManager session = new SessionManager(getApplicationContext());
session.createLoginSession(userId, categoryId, categoryType, batchId);
Retrieving the data from session
SessionManager session = new SessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
String userId = user.get("userId").toString();
String categoryId = user.get("catId").toString();
String categoryType = user.get("catType").toString();
String batchId= user.get("batchId").toString();
" - #sam
I'm a bit confused with this answer. I understand the code, but I'm clueless on how could this be used to redirect the users to different activities. Any help and explanation on how to do so would be highly appreciated!
To set a Shared Preference use this code below:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("ID_NAME_EXAMPLE","STRING_TO_SAVE");
editor.apply();
To access the Shared Preference use this:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("ID_NAME_EXAMPLE", "DEFAULT_VALUE_IF_NONE");
So for example you can have a Shared Preference saved as WHICH_ACTIVITY
editor.putString("WHICH_ACTIVITY","one");
editor.apply();
Then accesses it when user signs in as
String name = preferences.getString("WHICH_ACTIVITY", "zero");
if(name.equals("zero")){
startActivity(0);
}
else if(name.equals("one")){
startActivity(1);
}

How to read from SharedPreference file android

In my MainActivity, I have written some code which I assume creates a file and saves a value in that file.
public static final String WHAT_I_WROTE = null;
public void sendMessage(View view) {
EditText editText = (EditText) findViewById(R.id.editText);
String message = editText.getText().toString();
//creates new SharedPreference?
SharedPreferences saver = getSharedPreferences("saved_text", Context.MODE_PRIVATE);
//writes to the preferences file called saved_text?
SharedPreferences.Editor writer = saver.edit();
writer.putString(WHAT_I_WROTE, message);
writer.commit();
}
In another activity, I want to be able to read the message and display it but when I try this, it cannot resolve the symbol "saver".
String text_for_display = saver.getString(WHAT_I_WROTE);
What is the mistake I have made here and how do I correct it to read the saved string?
Thanks.
In another activity you have to again initalize the Shared preference.
SharedPreferences saver = getSharedPreferences("saved_text", Context.MODE_PRIVATE);
String text_for_display = saver.getString(WHAT_I_WROTE),"any_default_value";
WHAT_WROTE = "anyText"
Add this to the other activity you have:
SharedPreferences saver = getSharedPreferences("saved_text", Context.MODE_PRIVATE);
then read it like this
String myValue = saver.getString("saved_text", "default_value");
Setting values in preference is like,
SharedPreferences.Editor editor = getSharedPreferences("saved_text", MODE_PRIVATE).edit();
editor.putString("WHAT_I_WROTE", message);
editor.commit();
Retrieve the data like,
SharedPreferences prefs = getSharedPreferences("saved_text", MODE_PRIVATE);
String text_for_display = prefs.getString("WHAT_I_WROTE", null);
Don't forget to put "context" before "getSharedPreferences" if necessary.

Similar like Php session for Android Studio

I'm newbie for Android Studio & Java, i'm PHP user.
Just want to know how to do like PHP session in Android Studio.
No matter which Activity i go to, i can easily get the session value example like the User ID. (session["USERID"])
now the method i using is putting extra everytime i call for another activity.
i'm sure there will be a better way to do this.
anyone have any good suggestion?
PS: I google around and it keep return me PHP session tutorial/example/etc but not for Android Studio....(may be i enter work #keyword or sentence)
Thank You Very Much
Thanks to fillobotto & Arshid KV
here is my code
first_main activity
sharedpreference = getSharedPreferences(BIZInfo, Context.MODE_PRIVATE);
sharedpreference.edit().putString(userid, "12345");
sharedpreference.edit().commit();
second_main activity
sharedpreference = PreferenceManager.getDefaultSharedPreferences(this);
String restoredText = sharedpreference.getString("text", null);
if (restoredText != null) {
sp_name = sharedpreference.getString("userid", "No name defined");
}
Log.i("TAG", "onCreate: [" + sp_name + "]");
log show empty value/nothing...
what went wrong!?
You can use SharedPreferences as session in php
Demo code :-
Setting values in Preference:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Arshid");
editor.putInt("Age", 22);
editor.commit();
Retrieve data from preference:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int Age = prefs.getInt("Age", 0); //0 is the default value.
}
You were really near to the solution. This is what I use:
public static String getSession(Activity context) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
return sharedPreferences.getString("session", null);
}
public static void setSession(Activity context, String session) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("session", session);
editor.apply();
}
I'm actually passing the Activityto get SharedPreferences, but in this way you will obtain an instance of the object which is not activity-related.

How to store and retrieve integer using Android Shared Preferences

I am trying to save an integer value and retrieve the value using a same button using shared preferences.
To be more precise, when i click a button the value should be incremented(i++) and then it should be stored. When i close and open the application, it should retrieve the same value from where i left it. How do i do this?
I am using eclipse.
This works for me
public class OnPreferenceManager {
private SharedPreferences.Editor editor;
private SharedPreferences prefs;
private String startHour = "startHour";
private OnPreferenceManager() {}
private OnPreferenceManager(Context mContext) {
prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
editor = prefs.edit();
}
public static OnPreferenceManager getInstance(Context mContext)
{
OnPreferenceManager _app = null;
if (_app == null)
_app = new OnPreferenceManager(mContext);
return _app;
}
public void setStartHour(int hour){
editor.putInt(startHour, hour);
editor.apply();
}
public int getStartHour(){
int selectionStart = prefs.getInt(startHour, -1);
return selectionStart;
}
}
When you need to set integer just write as below
OnPreferenceManager.getInstance(this).setStartHour(theValueYouWantToStore);
And to retrieve write
OnPreferenceManager.getInstance(this).getStartHour()
You can use shared preferences as below.
//To save integer value
SharedPreferences preference = getSharedPreferences("YOUR_PREF_NAME", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("YOU_KEY",you_int_value);
editor.commit();
//To retrieve integer value
SharedPreferences settings = getSharedPreferences("YOUR_PREF_NAME", 0);
int snowDensity = settings.getInt("YOU_KEY", 0); //0 is the default value
Check this gist https://gist.github.com/john1jan/b8cb536ca51a0b2aa1da4e81566869c4
I have created a Preference Utils class that will handle all the cases.
Its Easy to Use
Storing into preference
PrefUtils.saveToPrefs(getActivity(), PrefKeys.USER_INCOME, income);
Getting from preference
Double income = (Double) PrefUtils.getFromPrefs(getActivity(), PrefKeys.USER_INCOME, new Double(10));

Categories

Resources