Store and retrieve strings in ArrayAdapter with SharedPreferences - java

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

Related

Firebase Auth: getCurrentUser from different Activities?

I have an app with a login screen. Now, i just want to get the DisplayName of the user which is signed in in another Activity. How can I get this name?
Use getCurrentUser():
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// Name, getEmail or etc
String name = user.getDisplayName();
Log.d("TAG" + name) // the name ...
}
https://firebase.google.com/docs/auth/android/manage-users#get_the_currently_signed-in_user
Using SharedPreferences or Bundle you can get it.
private void onAuthSuccess(FirebaseUser currentUser) {
userId = currentUser.getUid();
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPref.edit();
if (currentUser.getDisplayName() != null){
editor.putString("userName", currentUser.getDisplayName());
} else if (currentUser.getEmail() != null){
editor.putString("useremail", currentUser.getEmail());
}
editor.putString("userId", currentUser.getUid());
editor.commit();
}
Another Activity you can get it below
SharedPreferences sharedPref =
PreferenceManager.getDefaultSharedPreferences(this);
String displayUser = sharedPref.getString("userName",null);
String displayEmail = sharedPref.getString("useremail",null);

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

Can we share or transfer data from one Activity to another Activity using SharedPreference?

I have to just transfer save file path from one activity to another activity but when it comes to show the data it display null value.
Following is the code to store data in SharedPreference:-
SharedPreferences pref= getApplicationContext().getSharedPreferences("Recorder",0);
SharedPreferences.Editor editor = pref.edit();
editor.putString("file_name",DateFormat.format("yyyy-MM-dd_kk-mm-ss", new Date().getTime())+".mp4");
editor.putString("file_path",Environment.getExternalStorageDirectory()+"/"+DateFormat.format("yyyy-MM-dd_kk-mm-ss", new Date().getTime())+".mp4");
Retrieving data from sharedPreference:-
file_name = (TextView) findViewById(R.id.file_name);
file_path = (TextView) findViewById(R.id.file_path);
pref = getApplicationContext().getSharedPreferences("Recorder",0);
editor = pref.edit();
String fileName = pref.getString("file_name",null);
String filePath = pref.getString("file_path",null);
if(fileName != null){
file_name.setText(fileName);
}else{
file_name.append("");
}
if (filePath != null){
file_path.setText(filePath);
}else{
file_path.append("");
}
You have to apply the editor by
editor.commit():
or
editor.apply();
editor.apply() is missing. You are not committing the save.
Why do you need to overload the system ? you have a mechanism for passing data between activities, just send the path of the file within the intent.
In ActivityA :
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putExtra("filePath", "...");
startActivity(intent);
In ActivityB :
String filePath = getIntent().getExtras().getString("filePath");
Yeah you can make use of SharedPreference to Store the information.
To pass the data from one activity to another its better to use intent.
Intent intent = new Intent(CurrentActivity.this, AnotherActivity.class);
intent.putExtra("file_name","name");
intent.putExtra("file_path","path");
startActivity(intent)
In another Activity,
String fileName = getIntent().getStringExtra("file_name");
String filePath = getIntent().getStringExtra("file_path");
If you are using SharedPreffernces just to share data between activities, then it's overkill.
In case data should be available after app restart your solutions is good. But if you need it only at runtime, it's better to use Intent as mentioned in other answers.
Personally, I would prefer to store it in some static variable.
editor.commit() is missing.
Better way is to use bundle that could be set in intent and use this intent to start another activity and then fetch values from intent's bundle.
Yes you can make use of SharedPrefernces. try below code
public static final String MYPREFERNCES_Example = "mysharedpref";
SharedPreferences.Editor editor ;
SharedPreferences sp;
sp = getSharedPreferences(MYPREFERNCES_Example Context.MODE_PRIVATE);
editor=sp.edit();
Intent i_login = new Intent(LoginActivity.this, HomeActivity.class);
editor.putString("yourownkey1", yourvalue);
editor.putString("yourownkey2", yourvalue);
editor.putString("yourownkey3", yourvalue);
startActivity(intent)
and in next activity
sp = getSharedPreferences(MYPREFERNCES_Example, 0);
editor = sp.edit();
String fn = sp.getString("yourownkey1", "");
String ln = sp.getString("yourownkey2", "");
String fbemail = sp.getString("yourownkey3", "");

Storing and reading DatePicker values from shared preferences not working

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 !

Categories