How to use SharedPreferences from differents activities? [duplicate] - java

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

Related

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

Can not access shared preferences data properly

I am trying to send one string through shared preferences to another activity. I want to call the same activity back.
I have multiple activities which calls one activity in common. So I want to Identify from which the common activity has been called and want to go back to the same activity from which it is called.
This I have done in 1st Activity:
SharedPreferences mPrefs = getSharedPreferences("Type", 0);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("gosend","1");
editor.commit();
In 2nd activity
SharedPreferences mPrefs = getSharedPreferences("Type1", 0);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("goride", "2");
editor.commit();
In common activity
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences mPrefs = getSharedPreferences("Type", 0);
activityType = mPrefs.getString("gosend", "1");
SharedPreferences mPrefs1 = getSharedPreferences("Type1",0);
goride = mPrefs1.getString("goride","2");
if(activityType.equals("1")) {
intent = new Intent(ChooseFromMapActivity.this, GoSend.class);
startActivity(intent);
}
if(goride.equals("2"))
{
intent = new Intent(ChooseFromMapActivity.this, GoRideActivity.class);
startActivity(intent);
}
}
});
}
Now when I am calling common activity from 1st activity , I am not returning back to the same rather 2nd activity is getting called.
whats going wrong??
Edit
I tried this : Still dose not work
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences mPrefs = getSharedPreferences("Type", 0);
activityType = mPrefs.getString("gosend", "0");
// SharedPreferences mPrefs1 = getSharedPreferences("Type1",0);
// goride = mPrefs1.getString("goride","0");
switch (activityType){
case "0":
intent = new Intent(ChooseFromMapActivity.this, GoSend.class);
startActivity(intent);
break;
case "1":
intent = new Intent(ChooseFromMapActivity.this, GoRideActivity.class);
startActivity(intent);
break;
}
}
you are calling the same sharepreference while writing both files
note from 1st activity
-->> SharedPreferences.Editor editor = mPrefs.edit();
note from 2nd activity
-->> SharedPreferences mPrefs = getSharedPreferences("Type1", 0);
and in your common activity...
-->SharedPreferences mPrefs = getSharedPreferences("Type", 0);
activityType = mPrefs.getString("gosend", "1");
SharedPreferences mPrefs1 = getSharedPreferences("Type1",0);
goride = mPrefs1.getString("goride","2");
you are referring to the same file as in your code, BUT really, what you were trying to do is to refer to 2 seperate sharepreference...
mPref & mPref1....
so, you have to decide to use either one, but not two...
EDIT --->> UPDATE CODE SUGGESTION.
in your Activity 1
SharedPreferences mPrefs = getSharedPreferences("Type", 0);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("gosend","1");
editor.commit();
in your Activity 2
SharedPreferences mPrefs = getSharedPreferences("Type1", 0);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("gosend", "2");
editor.commit();
==>> make sure the "gosend" values are the one you wanted. you are taking measure on the changes made to "gosend", because in your code, you wanted to test the "gosend" values, and open different activities based on the values.
in your common activity
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences mPrefs = getSharedPreferences("Type", 0);
activityType = mPrefs.getString("gosend", "0");
// SharedPreferences mPrefs1 = getSharedPreferences("Type1",0);
// goride = mPrefs1.getString("goride","0");
switch (activityType){
case "0":
intent = new Intent(ChooseFromMapActivity.this, GoSend.class);
startActivity(intent);
break;
case "1":
intent = new Intent(ChooseFromMapActivity.this, GoRideActivity.class);
startActivity(intent);
break;
}
}
}
** good luck, hope this help..
Try the following code in your common activity:
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences mPrefs = getSharedPreferences("Type", 0);
activityType = mPrefs.getString("gosend", "0");
SharedPreferences mPrefs1 = getSharedPreferences("Type1",0);
goride = mPrefs1.getString("goride","0");
if(activityType.equals("1")) {
intent = new Intent(ChooseFromMapActivity.this, GoSend.class);
startActivity(intent);
}
else if(goride.equals("2"))
{
intent = new Intent(ChooseFromMapActivity.this, GoRideActivity.class);
startActivity(intent);
}
}
});
}
Let me know is your problem is solved. Your default value matches with the required value so every time first if statement will become true.
Hope this helps.

Run activity only once, then always run the main one

As the title says, Scenario is:
On first time using the app, Show Screen A.
Once you are done with screen A, the button will lead to you Screen B.
From now on and forever, the Screen B will always be main "Screen"(Activity?) when you start the app.
I am trying this 2 days and i can't get it.
Somebody please explain a little detailed, or even better throw me a code.rar so i can research it. I'm going crazy with this!!!
Just declare your Activity A as a launcher Activity in your AndroidManifest.xml and inside your Activity A onCreate() you can simply do this
private SharedPreferences mSharedPreferences;
private Editor mEditor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
mSharedPreferences = getSharedPreferences("yourPrefsFileName", Context.MODE_PRIVATE));
mEditor = mSharedPreferences.edit();
if (mSharedPreferences.getBoolean("isfirstTime", true)) {
mEditor.putBoolean("isFirstTime",false);
mEditor.apply();
}else{
startActivity(new Intent(this, ActivityB.class));
overridePendingTransition(0, 0);
finish();
}
}
All you have to check like this
SharedPreferences prefs = getSharedPreferences("mySHaredpref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
boolean isFirst = prefs.getBoolean("isfirstTime", true);
if(isFirst) {
Intent intent = new Intent(this, ActivtyA.class);
editor.putBoolean(KEY_IS_FIRST_TIME, false);
editor.commit();
startActivity(intent);
}
else{
Intent intent = new Intent(this, MainActivty.class);
startActivity(intent);
}
public class FirstActivity extends Activity {
public void onCreate(Bundle saved){
super.onCreate();
SharedPreferences prefs = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
if (!prefs.getBoolean("firstStart", true)){
startActivity(this, SecondActivity.class);
finish(); // Finish the current one, is like forwarding directly to the second one
}
}
}
Whenever you are done with showing the first activity simple set the shared prefs boolean flag to false:
prefs.getEditor.setBoolean("firstStart", false).commit();
SharedPreferences sp = getSharedPreferences("checking",MODE_PRIVATE);
String data = sp.getString("check", "");
if (data.equals("success")) {
//one time proccess code
//with follow code
SharedPreferences sp= getSharedPreferences("checking",MODE_PRIVATE);
Editor e1 = sp.edit();
e1.putString("check","success");
e1.commit();
} else {
// code for main
Intent intent = new Intent(this, MainActivty.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