unable to update values using shared preferences - android

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

Related

Saved Location on Preferance is allways null

I try to save a location on my Preference. SavedLocation class store three variables: name, location and the location type. All look great until I try to read saved dates from Preference. The name and location type are stored perfectly but stored location is null. In debug savedlocation contain all wanted variable but look like ed.putString(SAVED_LOCATIONS, gson.toJson(savedLocations, savedLocationsType));
not write correct my dates.
private void saveLocation(SavedLocation savedlocation, Context context) {
Gson gson = new Gson();
Type savedLocationsType = new TypeToken<ArrayList<SavedLocation>>() {}.getType();
ArrayList<SavedLocation> savedLocations = getSavedLocations(context);
savedLocations.add(savedlocation);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor ed = prefs.edit();
ed.putString(SAVED_LOCATIONS, gson.toJson(savedLocations, savedLocationsType));
ed.apply();
}
SavedLocation class is alike:
public SavedLocation(String name, Location location, LocationType type) {
this.name = name;
this.location = location;
this.type = type;
}
Any suggestion?
Try this
Create variable for SharedPreferences and Editor.
SharedPreferences pref;
Editor editor;
String PREF_NAME="my_location"
Now get preference
pref = this.getSharedPreferences(PREF_NAME, 0);
editor = pref.edit();
Now add location to preference
editor.putString(SAVED_LOCATIONS, gson.toJson(savedLocations, savedLocationsType));
editor.commit();
Then fetch the data
String location=pref.getString(savedLocations, "defaultvalue");

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

Displaying messages from multiple notifications -Android

I am using Firebase to send notifications to my App, when I receive the notification I store the message in my shared preferences and then display the message in an activity. However, as of right now I am only saving the latest notification message in the shared preferences. How do I save all the messages from the notifications in the shared preferences?
I hope that you have some unique id for the message you are receiving from firebase. Now when you save the message in the shared preference use that unique id from the payload as the key. In your case, the MESSAGE_KEY is the same that's why it gets overwritten with the latest one. Just make the MESSAGE_KEY unique in the saveKeyMessage function and new shared preference instance will be created for each notification you receive. OR You can use the following code to set the key as the unique key for you shared preference generation.
public boolean saveKeyMessage(String message){
SharedPreferences sharedPreferences =
mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Log.d("MainActivity", "Current Timestamp: " + format);
editor.putString(unique_message_id, message);
editor.apply();
return true;
}
You can use the following code to display all shared preference instances
SharedPreferences prefs =
mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
Map<String, ?> allPrefs = prefs.getAll(); //your sharedPreference
Set<String> set = allPrefs.keySet();
for(String s : set){
LOG.d(TAG, s + "<" + allPrefs.get(s).getClass().getSimpleName() +"> = "
+ allPrefs.get(s).toString());
Hope this solves you problem! Cheers!
Use HashSet to store messages into SharedPreferences.
#. Store messages into SharedPreferences:
public static final String KEY_MESSAGES = "messages";
............
.................
public boolean saveKeyMessage(String message) {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
// Get existing messages
Set<String> messages = getMessages();
// Add new message to existing messages
messages.add(message);
// Store messages to SharedPreferences
editor.putStringSet(KEY_MESSAGES, messages);
editor.apply();
return true;
}
#. Get messages from SharedPreferences:
public Set<String> getMessages() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
// Get messages
Set<String> messages = sharedPreferences.getStringSet(KEY_MESSAGES, new HashSet<String>());
return messages;
}
#. Get last message from SharedPreferences:
public String getLastKeyMessage() {
ArrayList<String> messageList = new ArrayList<String>(getMessages());
return messageList.get(messageList.size() - 1);
}
Hope this will help~

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

how to put multidimensional array in shared preferences in android

basically my array is in this format an i want to store this in shared preferences
but dont know how will someone give me idea or code
i am working with dynamic content
String[][] my_date;
my_date = new String[][] {
{"14","26"},
{"12","16","24","27"},
{"17"},
{"8","13","18"},
{"14"},
{},
{"29"},
{"15","18"},
{},
{"2","3","6","8","23"},
{"4","6","24"},
{}
};
You can use ObjectSerializer. [ https://github.com/apache/pig/blob/89c2e8e76c68d0d0abe6a36b4e08ddc56979796f/src/org/apache/pig/impl/util/ObjectSerializer.java ] this awesome class allows you to easily serialise every kind of object to a String, that then you can save wherever you like. Example, having a sharedPreferences instance already created:
sharedPreferences.edit().putString( YOUR_OBJECT_KEY, ObjectSerializer.serialize(object) ).commit();
to get your object out from shared, you can call
object = (Object) ObjectSerializer.deserialize(sharedPreferences.getString( YOUR_OBJECT_KEY, null));
Note that if you care about performances (need to store huge amounts of data / heavy data - eg. images) both shared preferences and the mentioned approach may not be optimal
You can use putStringSet in preferences
example preferences.putStringSet("key", Set);
I have this class i made
public class SavedPreference
{
static final String PREF_USER_NAME = "username";
static final String PREF_PASS = "password";
static SharedPreferences getSharedPreferences(Context ct)
{
return PreferenceManager.getDefaultSharedPreferences(ct);
}
public static void setUserName(Context ctx, String userName)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.putString(PREF_USER_NAME, userName);
editor.commit();
}
public static void eraseSavedPreference(Context ctx)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.clear();
editor.commit();
}
public static String getUserName(Context ctx)
{
return getSharedPreferences(ctx).getString(PREF_USER_NAME, "");
}
}
In your Case:
In the setUserName you can change the code in there where you add the 2d array of yours and iterate them and add them using putString
Same as getting them as well

Categories

Resources