What the code should do: in the first fragment I have several EditText boxes, so people can fill in there name. In the second fragment I want the names to display in a TextView box. I thought using Shared Preferences was a good thing (correct me if I'm wrong).
In my first fragment I have this code:
public static String filename = "player1";
SharedPreferences someData;
[...]
someData = getActivity().getSharedPreferences(filename, 0);
String player1 = etPlayer1.getText().toString();
SharedPreferences.Editor editor = someData.edit();
editor.putString(player1, "player1");
editor.commit();
In my second fragment:
public static String filename = "player1";
SharedPreferences someData;
[...]
points1 = (TextView) getView().findViewById(R.id.tvPoints1);
someData = getActivity().getPreferences(0);
String dataReturned = someData.getString("player1", "Player 1");
points1.setText(dataReturned);
You may use an Intent or a Bundle. Shared Preferences are for storing long term data.
See this answer https://stackoverflow.com/a/10960855/826657
and this one for how to share data using a Bundle https://stackoverflow.com/a/16500141/826657
& this resource
http://developer.android.com/guide/components/fragments.html
Please pass your data (specially if complex) in a Bundle as explained here: Best practice for instantiating a new Android Fragment
Do not use shared preferences to do that.
There are many ways to pass data between activity and fragment. See this response here : data sharing between fragments and activity in android
Related
*I'm new in learning android
I'm searching for any website that show on how to accept user detail for example name and age, and display it in another activity using sharedpreferences in newer version of code? Do you have any? The another activity will have a Back button pointing to the first activity. All I found was in older version and not matched in my Android Studio so, I've cancelled the program. Anyone?
In the first activity, you can save the user name and age like this:
private void saveUserInformation(String userName, int age) {
//In this activity save the name in the shared preference
SharedPreferences sharedPreferences = getSharedPreferences("myAppPrefs", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("user_name", userName).putInt("user_age", age).apply();
}
In the second activity, to get the user information, do this:
private void getUserInformation() {
//In the second activity or any other activity, you can get the userName and age like thi
SharedPreferences sharedPreferences = getSharedPreferences("myAppPrefs", Context.MODE_PRIVATE);
String userName = sharedPreferences.getString("user_name", null);
int userAge = sharedPreferences.getInt("user_age", 0);
}
From your question and comment in other answers, i guess you need more explanation on how a shared preference works. When you save data in a sharedpreference, it gets saved in a file on the user device. After saving you can access that data from any activity as long as the activity has access. All you just have to do is put it in a shared preference using a unique key and get it where you need it using that same unique key. Hope it helps. If i my answer helps, don't forget to upvote. Thanks.
this is how you create a sharedpref
SharedPreferences sp=getSharedPreferences("MYPREFNAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sp.edit;
this is how you put data in it
editor.putString(key,string);
this.is how you retrieve that string back
sp.getString(key,DefaultString);
//in your first activity use
SharedPreferences sharedPreferences=getSharedPreferences("your_packagename", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("name","name_value").apply();
sharedPreferences.edit().putInt("age",age_value).apply();
//and now in your second activity to retrieve data
SharedPreferences sharedPreferences=getSharedPreferences("your_packagename", Context.MODE_PRIVATE);
String name=sharedPreferences.getString("name","");
int age =sharedPreferences.getInt("age",0);
This question already has answers here:
TextView that gets Value from SharedPreferences shows nothing, though there should be default values
(4 answers)
Closed 6 years ago.
I am having an issue with SharedPreferences that is kind of weird.
I have an Activity that holds a Fragment in a ViewPager. The fragment shows an icon and text. You can change the icon (check mark or cross, check mark is default) and text displayed in this fragment from another activity.
Now I want to save the text and chosen icon, so the fragment is shown with the same text and icon, even when you close the app and restart it later.
So I tried to achieve this with SharedPreferences, but when I tried it, my fragment showed me no text though I have default values set and the icon is always the cross, no matter what it was before and though the default icon should be the check mark.
I am saving the values in onActivityCreated() of my Fragment when it is created with the data the user inputted in the activity before.
Saving:
SharedPreferences sharedPref = getActivity().getApplicationContext().getSharedPreferences("com.fragmentdata.myapp", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
//Here I am getting the values I want to save from a bundle, city and country...
editor.putString("savedCity", city);
editor.putString("savedCountry", country);
editor.putString("fragmentSaved", "yes");
editor.apply();
Then, I am getting the values in onCreate() of my Activity that holds the Fragment:
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("com.fragmentdata.myapp", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
//adding fragment that was created with user input
String ifAdded = sharedPref.getString("addedFragment", "no");
if(ifAdded.equalsIgnoreCase("yes")){
Bundle extras = getIntent().getExtras();
StatusFragment newFragment = new StatusFragment();
newFragment.setArguments(extras);
mSectionsPagerAdapter.addFragment(newFragment, extras.getString("city"));
editor.putString("addedFragment", "no");
editor.apply();
}
//Adding a saved fragment after restart
String storedSave = sharedPref.getString("fragmentSaved", "no");
if (storedSave.equalsIgnoreCase("yes")){
String storedCity = sharedPref.getString("savedCity", "somecity");
String storedCountry = sharedPref.getString("savedCountry", "somecountry");
Bundle saves = new Bundle();
StatusFragment savedFragment = new StatusFragment();
saves.putString("city", storedCity);
saves.putString("country", storedCity);
savedFragment.setArguments(saves);
mSectionsPagerAdapter.addFragment(savedFragment, saves.getString("city"));
}
In the activity where the fragments data is created, I have this:
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("com.fragmentdata.myapp", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("addedFragment", "yes");
editor.apply();
fragmentHolder.putExtras(bundle);
startActivity(fragmentHolder);
bundle has the values the user typed in, and fragmentHolder is the activity that holds the fragment.
I searched for answers in different questions here on stackoverflow, but none of them worked for me, like:
Cannot get value from sharedpreferences
Shared Preferences get lost after shutting down device or killing the app
Shared Preferences reset data when app is force closed or device is restarted
SharedPreferences return only default value
SharedPreferences return only default value
Shared preference always taking default value
SharedPreferences keep getting default value
Sorry if I it is perhaps something trivial, but I haven't worked with Fragments much and I am using SharedPreferences the first time now.
I would be grateful for every helpful answer.
The problem is solved now. I had to use getActivity().getApplicationContext().getSharedPreferences("com.fragmentdata.myapp", Activity.MODE_PRIVATE); and some of my variables in the bundles and preferences got mixed up. I corrected this and now it works fine :) Thanks for your answers.
You are mixing up things that are stored in your SharedPreference and inside your applications resources (strings.xml)
editor.putString(getString(R.string.pref_fragment_saved), "Yes");
This line saves the string inside your preference XML, but then you try to read it as
getResources().getString(R.string.pref_fragment_saved).equals("Yes")
Which actually just reads the value R.string.pref_fragment_save from your strings.xml
The correct way of reading what you saved would be
getActivity().getPreferences(Context.MODE_PRIVATE).getString(getResources().getString(R.string.pref_fragment_saved), "defaultValue")
Or a bit cleaner:
SharedPreferences prefs = getActivity().getPreferences(Context.MODE_PRIVATE);
String key_frag_saved = getResources().getString(R.string.pref_fragment_saved);
String storedString = prefs.getString(key_frag_saved, "defValue");
if ( storedString.equalsIgnoreCase("yes") ) {...}
And the same way you would read the other saved values from your SharedPreference object instance.
You wanted to use this
SharedPreferences sharedPref = ...;
extras.putString("city", sharedPref.getString(getResources().getString(R.string.pref_saved_city), ""));
in your onCreate method
I want to know if there is a way to pass all the extras to the new intent.
Is it possible? And is it a good idea?
The reason is that I want to save the login state as a json string, and pass it in between Activities. I don't want to store data with SQLite or anything. Can I bypass all the intent extras to the new intent ?
please consider Shared Preference :
// Declaration
public static String KEY = "SESSION";
public static void saveUserName(String username, Context context) {
Editor editor = context
.getSharedPreferences(KEY, Activity.MODE_PRIVATE).edit();
editor.putString("username", username);
editor.commit();
}
public static String getUserName(Context context) {
SharedPreferences savedSession = context.getSharedPreferences(KEY,
Activity.MODE_PRIVATE);
return savedSession.getString("username", "");
}
You can store the login credentials to preference and retrieve them as well in any of your activity.
SaveUsername("Your text to save", Your_activity.this);
And to retrieve the value
String mUserName = getUserName(YourActivity.this);
It is recommended to have all your preference methods in your utils class to keep the code organized.
You can read more here
yes you can use Shared Preference to save the Login session of user here is handy example of managing session using shared preference http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/ I used it earlier and suggest you to have a look at it.
Any of the two may help you.
Saving it in the sharedPreference file.
If you want them to be accessable throught the application you can use the applicationClass, like a global singleton.
I need to send data Date Display to next Activity and keep that data
private void updateDisplay()
{
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(ShowdatanameActivity.this);
SharedPreferences.Editor editor = app_preferences.edit();
mDateDisplay.setText(new StringBuilder().append(mMonth + 1).append("-").append(mDay).append("-").append(mYear).append(" "));
editor.putString("key1", mDateDisplay);
editor.commit();
Intent myIntent = new Intent(ShowdatanameActivity.this,Showdata_result_resume.class);
startActivity(myIntent);
}
Well that's true you can acces to Data/Calendar object from every place of your application. But if you insist:
You've put your string to SharedPreferences under "key1" so in other activity you have to call:
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences("KEY_FOR_YOUR_DATA",ShowdatanameActivity.this);
String data = app_preferences.getString("key1","");
So when you call SharedPreferences you also need key for them. It's some kind of "database version", you can write anything there (i use for example PREFS-KEYv1, and when I need new one I'm incrementing to v2). And don't use same key everywhere it's bad practice.
The other method you could use to send your String to other activity is via intent.
intent.putExtra("key1",yourStringVariable);
and Showdata_result_resume in onCreate after setContent you can get it by:
String data = intent.getExtras().getString("key1");
Using code like this to make preferences code portable between various apps and classes.
from a fragment I get the sharedpref like this. Notice how I have the preferences named in a resource and I use getActivity to get to the preferences.
sharedPref = getActivity().getSharedPreferences(
getString(R.string.preferences), Context.MODE_PRIVATE);
From the main activity I get the sharedpref like this. Notice how I have the preferences named in a resource.
sharedPref = getSharedPreferences(getString(R.string.preferences),
Context.MODE_PRIVATE);
the resource which is shared by all classes in the app.
<string name="preferences">com.gosylvester.hilbilyfashliegt.prefrences</string>
<string name="about_firstrun">com.gosylvester.hilbilyfashliegt.firstrunabout</string>
now to get the data from any class I referer to it with an R string resource.
_Checked = sharedPref.getBoolean(getString(R.string.about_firstrun),
false);
Good Luck
My question is how to pass data like String between two activities. Normally I would do this:
Intent i = new Intent(thisclass.this,NextClass.class);
Bundle b = new Bundle();
i.putExtras(b);
b.putString("Name",Name);
StartActivity(i);
But this would make my Activity close and will open the next Activity, no? Is there any way that I can only pass data without opening the other activity?
I think you are looking for something with the SharedPreference see the documentation : SharedPreference
if it is what are looking for.
Try this:
Global:
private SharedPreferences pref;
onCreate:
pref = this.getSharedPreferences("SharedPreference", Context.MODE_PRIVATE);
The place where you gonna save your data:
String data = "yourData"
pref.edit().putString("myData", data).commit();
And the other Activity:
Global:
private SharedPreferences pref;
onCreate:
pref = this.getSharedPreferences("SharedPreference", Context.MODE_PRIVATE);
The place where you gonna take your data:
String dataFromFristActivity = pref.getString("myData", null);
Your calling activity does not close but is paused.
I am with #Egor on this. The called activity does not yet exist. Unless u are trying to send data between activities in two different apps. That is a whole different can of worms.