Storing and reading DatePicker values from shared preferences not working - java

I'm trying to allow a user to select a date. This date is then saved into shared prefences, and is used as the countdown date for a countdown timer on the next activity. I am able to save the "name" of the event but not the date, the values returned are just the default.
Storing Date:
SharedPreferences sharedPreferences = getPreferences(MODE_APPEND);
SharedPreferences.Editor editor = sharedPreferences.edit();
DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker1);
int day = datePicker.getDayOfMonth();
int month = datePicker.getMonth() + 1;
int year = datePicker.getYear();
editor.putString("day", String.valueOf(day));
editor.putInt("month", month);
editor.putInt("day", year);
editor.commit();
Retrieving date:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = getPreferences(MODE_APPEND);
SharedPreferences.Editor editor = sharedPreferences.edit();
String dayEvent = prefs.getInt("day",0);
int monthEvent = prefs.getInt("month",0);
int yearEvent = prefs.getInt("year",0);
String eventString = (dayEvent + "-" + monthEvent+ "-" + yearEvent);
TextView testDate= (TextView) findViewById(R.id.testDate);
testDate.setText(eventString);
return eventString;
The output being 0-0-0 from May 1st 2017, being selected.
I'm not sure if it matters, but these two are in separate classes.
Thanks
Shared Preferences:
SharedPreferences prefs = this.getSharedPreferences("Date_PREF", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = getPreferences(MODE_APPEND);
SharedPreferences.Editor editor = sharedPreferences.edit();

When you save your preferences you should pass a name :
SharedPreferences prefs = getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE);
// open editor and commit() or apply()
Then to retrieve the data you get the shared preference the exact same way.
You can also use the getDefaultSharedPreferences which are common to all your activities :
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
EDIT :
Without using default shared pref
Save
SharedPreferences prefs = getSharedPreferences("DATE_AND_STUFF", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("key", "value");
editor.apply();
Retrieve
SharedPreferences prefs = getSharedPreferences("DATE_AND_STUFF", Context.MODE_PRIVATE);
String value = prefs.getString("key", "defaultValue");
Using default shared pref
Save
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(FirstActivity.this);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("key", "value");
editor.apply();
Retrieve
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(SecondActivity.this);
String value = prefs.getString("key", "defaultValue");
Hope it will help !

Related

SharedPreferences return nothing after app restart

i save my token in Shared Preferences with this Set Token method
public static void setToken(Context ctx, String token) {
SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
editor.putString(PREF_TOKEN, token);
editor.apply();
}
and get token with this get Token method in all my project
public static String getToken(Context ctx) {
return getSharedPreferences(ctx).getString(PREF_TOKEN, "456");
}
my problem is when app is restarted, get Token method return "456"
home activity token log :
eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjBkM2JlODBlMTg4Mzc4NTNjY2VjYjU2Nzg1NzAxYjNhM2NhZGJiOWFhYTZjYWIwNDQ3YjA4MzJmMzRkNmMxMzM5MzAyMWE2OWQ4NDk2ZTY1In0.eyJhdWQiOiIxIiwianRpIjoiMGQzYmU4MGUxODgzNzg1M2NjZWNiNTY3ODU3MDFiM2EzY2FkYmI5YWFhNmNhYjA0NDdiMDgzMmYzNGQ2YzEzMzkzMDIxYTY5ZDg0OTZlNjUiLCJpYXQiOjE1NjAzMTY5MTQsIm5iZiI6MTU2MDMxNjkxNCwiZXhwIjoxNTkxOTM5MzE0LCJzdWIiOiI1Iiwic2NvcGVzIjpbXX0.RovbkU1XXCuOcUvAzutW9Btm64BlYc8jAZTTeiPue43-YUMv2Ftr2m40I6yVH0JPdCGHwbtIruJRHeM8fx1ua4pryBQIxgdCvB-S5FiioOPR_zrG-II_pEquUQoz3wEpxmwG1KDmYOWfENA7El6v8e3mnyg54o9ikcYCFLgoV3V5kcdhX4RZRWeRE8ED76m1YhImjuIAkSV88tmtrzt1E7dWM_lfWDLGOsrPnOLFdzEGDozGHcMU6D5-qN9CroBGzrlLD4ngvk1yV1cypSLgsM9yuJ3b9MJJhcs5v_mrm5McT6aipcM6ghKdClGF7_SBAjREPJGxPD7-KY5sH4L9NkpsxH4SQL9fxKpE_Z2B_PCKVaCGtSBQ0E1dURFIkJfUWhFsRZea1DBXQkZTDcAnxj9WA2ZDqWe_Ve-fPDyhmnfObHfeJ0NRtm-Wgq6R-F5PwlF_SjxgrhXhKsAd4knvvkP-o06e_d3fb-8mUedmQQroI9VXci6kE5gJhqUWjX5OpCLWBCFY12Y5Vntg2R-G_sLPJXewkM7TcXlc381V212bJElFThgurWfm4zRfWA5L8VV8d_xms3f852rOg2z6xh0dNt5zeqp3b8IS68k1wTzBPGobJZSvr5ZDd_xZYpJREsDeLh8Osr7hP3V3zUWIMGdEyKUL3ITCL7FMAtj9VFA
After restart :
token=456
Simple mistake, you have to replace this line
SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
to below one
SharedPreferences.Editor editor = getSharedPreferences(KEY_PREFS_NAME, context.MODE_PRIVATE).edit();
Where KEY_PREFS_NAME is the name of your preference
Try this to save it:
public void saveToken(String token){
SharedPreferences sharedPreferences = getSharedPreferences(PREF_TOKEN, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(TOKEN, token).apply();
}
and this to get back:
public String getToken(){
SharedPreferences sharedPreferences = getSharedPreferences(PREF_TOKEN, Context.MODE_PRIVATE);
return sharedPreferences.getString(TOKEN, "")
}
Hope it helps!

How to use SharedPreferences from differents activities? [duplicate]

This question already has answers here:
sharedpreferences between activities
(3 answers)
Android Shared preferences with multiple activities
(3 answers)
Closed 4 years ago.
I have searched how to use SharedPreferences in Android and ran into a problem.
I save some Strings in the SP and I save the data in Main Activity this way:
in OnCrete function I define:
sp = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
SharedPreferences.Editor editor = sp.edit();
and then I save the strings to SharedPreferences in the following way:
mail = edmail.getText().toString();
pass = edpass.getText().toString();
color = edcolor.getText().toString();
phone = edphone.getText().toString();
SharedPreferences.Editor editor = sp.edit();
if (mail.equals("") || pass.equals("") || color.equals("") || phone.equals("")||img.getDrawable() == null
)
Toast.makeText(getApplicationContext(), "you have to fill all the fields", Toast.LENGTH_SHORT).show();
else {
editor.putString("mail", mail);
editor.putString("phone", phone);
editor.putString("color", color);
editor.putString("password", pass);
editor.apply();
Toast.makeText(getApplicationContext(), "Signed up", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, Main2Activity.class);
intent.putExtra("img",bitmap);
startActivity(intent);
}
In the second activity I am trying to retrieve the data:
#Override
public void onClick(View v) {
Intent intent=getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("img");
imgv.setImageBitmap(bitmap);
LoadPreferences();
//txtmail.setText(value);
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String data = sharedPreferences.getString("mail", null) ;
Toast.makeText(this,data, Toast.LENGTH_LONG).show();
}
The toast presents the default value instead the real value.
You saved your data in MyPref file which is a different shared preference file as compared to PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
so use
SharedPreferences sharedPreferences = getSharedPreferences("MyPref", 0);
instead of
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
getSharedPreferences("MyPref", 0); will always creates a new file if does not exist whereas the getDefaultSharedPreferences gives you a pref file which is can be used by whole app whit mentioning any name
Change your loading declaration:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
To:
SharedPreferences sp = getApplicationContext().getSharedPreferences("MyPref", 0);

Put username to other activity with sharedpreference

I have value 'username' in MainActivity, get from login session.
How i can put this 'username' to other activity?
I use sharedpreference.
Can you help me? Pleasee
Try this:
To write the username:
SharedPreferences settings = getSharedPreferences("preferences", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("username", username);
editor.commit();
To get the username:
SharedPreferences settings = getSharedPreferences("preferences", 0);
String username = settings.getString("username", ""); //sets to "" if fails
Or you can pass it through the intent using a bundle:
Bundle bundle = new Bundle();
bundle.putString("username", username);
Intent intent = new Intent(this, JoinChatActivity.class);
intent.putExtras(bundle);
startActivity(this, NewActivity.class);
Try this:
First you initialize the SharedPreferences in Top like this
SharedPreferences sharedPreferences;
after that get the value json like(username) and put the value SharedPreferences
username= obj1.getString("username");
// Using shared preference storing the data in key value pair
sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", username);
editor.apply();
And get the value in next activity like this
SharedPreferences pref = getSharedPreferences("MyPref", 0);
String username= pref.getString("username", null);
Pass the value in parameter like this
params.put("username", username);
i think it helps you
Or you can transfer the value using Intent. for example:
This is MainActivity.class
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = new Intent (getApplicationContext(), MainActivity.class);
intent.putExtra("userName", username);
getApplicationContext().startActivities(new Intent[] {intent});
}
Other.class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_detail);
Intent intent = this.getIntent();
String username = intent.getExtras().toString("userName");
}

My SharedPreferences disappear when I do remove some keys in Android

I store some user info, and if it's first time launching the app in SharedPreferences. When user logs out, I remove keys which hold the user info. However, when I do that, it also removes the key where I hold the boolean for app launch for some reason. Why that happens? Source:
On app start:
SharedPreferences prefs = getSharedPreferences("prefs",MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
if (prefs.getBoolean("isFirstLaunch",true)){
editor.putBoolean("isFirstLaunch",false);
editor.apply();
Intent intentIntro = new Intent(this,TutorialActivity.class);
startActivity(intentIntro);
}
On logout:
SharedPreferences newPrefs = getSharedPreferences("prefs",MODE_PRIVATE);
SharedPreferences.Editor neweditor = newPrefs.edit();
neweditor.remove("authKey");
neweditor.remove("forget");
neweditor.apply();
Intent intent = new Intent(MainActivity.this, LandingActivity.class);
startActivity(intent);

Store and retrieve strings in ArrayAdapter with SharedPreferences

I need to save and retrieve two strings in an ArrayAdapter of my NavigationDrawer.
First of all. I declared this:
private static SharedPreferences prefs;
then in the getView() method
SharedPreferences.Editor editor = context.getSharedPreferences("MYPREFS", context.MODE_PRIVATE).edit();
editor.putString("username", NameStr);
editor.putString("photo", urlProfile);
editor.commit();
In this way i'm going to save the strings i need. But i'm not exactly sure because i never use the Sharedpreferences in an Adapter. How can i retrieve the datas? Where have i to put it? thanks
EDIT:
to achieve the strings i wrote in getView()
Intent intent = ((Activity) context).getIntent();
NameStr = intent.getStringExtra("username");
urlProfile = intent.getStringExtra("photo");
where the two strings comes from another activity.
EDIT2: SOLUTION
Dexter got the solution and it works perfectly:
SharedPreferences sharedPreferences = context.getSharedPreferences("MYPREFS",context. MODE_PRIVATE);
if(sharedPreferences == null) return;
NameStr = sharedPreferences.getString("username", "");
urlProfile = sharedPreferences.getString("photo", "");
SharedPreferences.Editor editor = sharedPreferences.edit();
Intent intent = ((Activity) context).getIntent();
if(NameStr == null || NameStr.equals("")) {
NameStr = intent.getStringExtra("username");
editor.putString("username", NameStr);
}
if(urlProfile == null || urlProfile.equals("")) {
urlProfile = intent.getStringExtra("photo");
editor.putString("photo", urlProfile);
}
editor.apply();
all of this in the Adapter construction!
You can retrieve the data using :
SharedPreferences sharedPreferences = context.getSharedPreferences("MYPREFS", context.MODE_PRIVATE);
String username = sharedPreferences.getString("username", "");
String photo = sharedPreferences.getString("photo", "");
Also prefer using editor.apply()

Categories