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~
Related
I'm new with HashMap, how can I save permanently and add other items when I reopen the application?
For example:
private HashMap<String, Recognition> registered = new HashMap<>();
public void register(String name, Recognition rec) {
registered.put(name, rec);
}
I can see all items inside registered using:
for (Map.Entry<String, Recognition> entry : registered.entrySet()) {
final String name = entry.getKey();
... }
But when I close and reopen app, I can't see all objects saved inside registered.
I see lot of people using SharedPreferences, but I don't know how to add items inside the pre-saved hashmap.
You can do it indirectly this way:
//writing into file
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString( key, hashmap.getValue() );
editor.commit();
//reading from file
SharedPreferences pref = getPreferences(Context.MODE_PRIVATE);
for( i = 0;i < size;i++) )
pref.getString( i , defaultValue );
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));
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();
}
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.
I need to know how can shared preference can be used to keep my data persistent and also update the values.I have written some code.
MainActivity.java
SharedPreferences sPrefs= this.getSharedPreferences(mypreference, Context.MODE_PRIVATE);
if(sPrefs.contains("userData"))
{
retreivepreviousdata=gson.fromJson(sPrefs.getString("userData",""),DataStore.class);
userDataStore.getDataStore().addAll(retreivepreviousdata.getDataRetrieve());
}
userDataStore.getDataStore().add(usrData);
SharedPreferences.Editor prefEditor = getSharedPreferences(mypreference, Context.MODE_PRIVATE).edit();
String saveData = gson.toJson(userDataStore);
prefEditor.putString("userData", saveData);
prefEditor.apply();
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();`
SecondActivity.java
String mypreference="user_data";
SharedPreferences sPrefs= this.getSharedPreferences(mypreference, Context.MODE_PRIVATE);
DataStore dataPull=new DataStore();
Gson gson=new Gson();
String pull=sPrefs.getString("userData","");
dataPull=gson.fromJson(pull,DataStore.class);
System.out.println(dataPull.getDataStore().get(0).toString());
RecyclerView recyclerView=(RecyclerView)findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
MyRecyclerAdapter mAdapter=new MyRecyclerAdapter(dataPull);
recyclerView.setAdapter(mAdapter);
The problem with this code is the values entered are saved and persistent.But when i close,reopen the app and enter values the previous data gets override.
For Storing the value into SharedPreferences
SharedPreferences shared = getSharedPreferences("user_Info", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putString("key", value);
editor.commit();
For retrieving values from SharedPreferences just use this
SharedPreferences sharedPref = getSharedPreferences("user_Info", Context.MODE_PRIVATE);
String value = sharedPref.getString("key", "defaultValue");
If you want to store an ArrayList inside SharedPreferences, just convert it to a string. Then, you can "deconvert" it. E.G.
String toSave;
// Object is for your object type. Just get your objects converted to string, that's the point.
for(Object obj : arrayList){
toSave += obj.toString() + "\n";
}
SharedPreferences prefs = getSharedPreferences("PREFS_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("key", toSave);
editor.apply();
and...
SharedPreferences prefs = getSharedPreferences("PREFS_NAME",Context.MODE_PRIVATE);
String toGet = prefs.getString("key", "");
String[] parts = toGet.split("\n");
for(String s : parts){
arrayList.add(s); // or do whatever conversion you want to get your Object type
}