How to save and get SharedPreferences in different activities? - android

I've been having issues understanding how to save and read SharedPreferences. I'm trying to save four separate SharedPreferences but as I couldn't figure out how to do it, I decided to try with a simple String.
In this code I'm trying to create and save a string in SharedPreferences
Button enrollNewStudent = (Button) findViewById(R.id.enrollStudentButton) ;
enrollNewStudent.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
SharedPreferences prefs = getSharedPreferences(getString(R.string.testing), MODE_PRIVATE);
SharedPreferences.Editor editor = getSharedPreferences(getString(R.string.testing), MODE_PRIVATE).edit();
editor.putString("name", "Dave");
editor.commit();
startActivity(new Intent(MainActivity.this, AddNewStudent.class));
}
});
And in this next part I'm trying to read the SharedPreferences and have a TextView set to it in a second activity.
Context context = this;
SharedPreferences sharedPref = getSharedPreferences(getString(R.string.testing),MODE_PRIVATE);
String toPutInTextView = sharedPref.getString(getString(R.string.testing), null);
TextView textView = findViewById(R.id.exampleTextView);
textView.setText(toPutInTextView);
When I run this app and click the button to switch to the second activity the TextView on the second activity is blank.
Does anybody see a problem with this? I've been trying to piece together what I need to do from the android developers website and from other questions here but I just cannot get this working. This is for a university project.

The problem is: sharedPref.getString(getString(R.string.testing), null) is pulling using the string getString(R.string.testing) as the key. However, the key you used when you called "putString()" was "name". So you need to use "name" as your key for your getString() call.
Try:
String toPutInTextView = sharedPref.getString("name", "<default_value>");

Related

Android Log in with CheckBox

My first application in android studio and i want to do this:
Description:
username:username (TextBox)
password:password (TextBox)
Keep me logged in -->CheckBox
LOGIN -->BUTTON
The first time where the user enters your username and password and click to Keep me logged in the application must be remember the username and password without the user writes again in the second time.
Could anyone give me some idea how this implement in android, I found many examples but nothing work.
You could use SharedPreferences to remember the user preference. Here it is a boolean.
SharedPreferences prefs = getDefaultSharedPreferences(this);
boolean keepLoggedIn = prefs.getBoolean(KEY_KEEP_LOGGED_IN, false);
//After user makes the selection on the checkbox,
SharedPreferences.Editor editor = getDefaultSharedPreferences(this).edit();
editor.putBoolean(KEY_KEEP_LOGGED_IN, true);
editor.commit();
I did something very similar to this recently
First, make sure to initialize your fields in question
AutoCompleteTextView mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
EditText mPasswordView = (EditText) findViewById(R.id.password);
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
Set your onClick event:
mEmailSignInButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
attemptLogin();
}
});
In order for the user password to be remembered, you have to save them somewhere. I stored them in shared preferences, but you can use a more secure method depending on your application or even encrypt before storing them http://developer.android.com/guide/topics/data/data-storage.html#pref
//Initialize the shared preferences, set in private mode
SharedPreferences sharedPref = getSharedPreferences("userDetails", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
//Put the strings in the editor
editor.putString(getString(R.string.userAccount), email);
editor.putString(getString(R.string.password), password);
Now in onCreate or your other favorite android start method (depending on if you're using a fragment or activity), retrieve them
//Initialize the shared preferences, set in private mode
SharedPreferences sharedPref = getSharedPreferences("userDetails", MODE_PRIVATE);
//Retrive the values
sharedPref.getString(getString(R.string.userAccount), "")
sharedPref.getString(getString(R.string.password), "")

How to display saved textview onto image button

Functionality Description:
Image Button(calls on a secondary application) that allow users to enter and input text, handwritten as well as keyboard input. User will then have the option to save the text. When, user exit the secondary application, the image button is supposed to displayed the saved text.
Genuine Issue:
Have intended to use shared preferences method but the saved text is still not displayed. Can anyone please help. Following is the code used.
Code:
//EDITED VERSION TO CALL OUT THE SECONDARY APPLICATION FOR USER TO INPUT TEXTandr
private void addListenerOnButtonMyScript() {
// TODO Auto-generated method stub
imageButton = (ImageButton) findViewById(R.id.imageButton_myscript);
imageButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Log.i("SingleViewActivity:onCreate:addListenerOnButtonMyScript" + ":onKey" , "Initiate myScript:");
final Intent intent = new Intent();
intent.setClassName("com.visionobjects.textwidget.sample", "com.visionobjects.textwidget.sample.SampleActivity");
startActivity(intent);
SharedPreferences pref = getSharedPreferences(getString(R.string.pref_text),MODE_PRIVATE);
Log.i("Calling on Shared Preferences" , "Shared Preferences to pref_text:" + getString(R.string.pref_text) );
SharedPreferences.Editor editor = pref.edit();
editor.putString(getString(R.string.pref_text),"");
editor.commit();
}
});
}
//EDITED VERSION TO CALL ON SHARED PREFERENCES FUNCTION TO DISPLAY EDITED TEXT FROM MY_SCRIPT-20/10/2014
private void loadSavedPreferences(){
SharedPreferences pref = getSharedPreferences(getString(R.string.pref_text),MODE_PRIVATE);
SharedPreferences.Editor editor= pref.edit();
editor.commit();
}
Strings.xml
<resources>
<string name="app_name">SalesBase</string>
<string name ="pref_text">StandardPreferences</string>
<string name="contacts_default">Contacts Details\n名字:HARRY\n公司:BARTENDER\n路名:123, Road Name\nZip:Zip\nState:State\nMobile:012-345-6789\nOffice:12-345-678\n</string>
</resources>
You are using wrong code to load the data. If loadSavedPreferences() is your final code to get data then you will not get any data. Try this
private void loadSavedPreferences(){
SharedPreferences pref = getSharedPreferences(getString(R.string.pref_text),MODE_PRIVATE);
String data = prefs.getString(getString(R.string.pref_text), "");
}
However, I would suggest you to use different keys for preference name and the data you are trying to save.
SharedPreferences pref = getSharedPreferences(getString(R.string.pref_text),MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
Use a different key where you are saving the data in this line and obviously value is the data you want to save. Use something like this.
editor.putString(key,value);
editor.commit();
And when you want to show the data then use the same key to get the data.
String data = prefs.getString(key, "");
Have a look at this as well.
Android Shared preferences example

How can I use sharedPreferences Date Diaplay sent next Activity

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

Can i use a button to save data in sharedPreferences and another to retrieve it?

Lets say i have an TextView that i want the user to view and then hit a save button. Then Hit display button and input the text into an editText field.
Here's what Im trying but its not working
To Save info from a TextView...
case R.id.save:
SharedPreferences firsttunesettings = getSharedPreferences("tune1", 0);
SharedPreferences.Editor editor = firsttunesettings.edit();
editor.putString("rh1", rh1.getText().toString());
editor.commit();
then to show the data in an EditText....
case R.id.display:
SharedPreferences firsttunesettings = getSharedPreferences("tune1", 0);
rh1.setText(firsttunesettings.getString("rh1", ""));
The code doesnt throw any errors, it just doesnt seem to do anything. Any help is appreciated. Thanks.
you need this:
SharedPreferences firsttunesettings = getApplicationContext().getSharedPreferences("tune1", 0);
and
SharedPreferences firsttunesettings = getApplicationContext().getSharedPreferences("tune1", 0);
rh1.setText(firsttunesettings.getString("rh1", ""));
the SharedPreferences needs the context of the aplication.
the rest of the code looks good to me.
edit:
try placing your values to save first on temporary variables like this:
String temp = firsttunesettings.getString("rh1", ""); and then:
rh1.setText(temp);
im running out off ideas since the code you posted should work fine.
edit#2:
also I declare the variables i use on shared preferences like this:
private static final String RH1 = "RH1";
and use it like this:
editor.putString(RH1, rh1.getText().toString());
and
String temp = firsttunesettings.getString(RH1, "");
this should do the trick.

SharedPreferences

I'm creating a SharedPreferences and it's working only if I start Activity like this:
myIntent.putExtra("prefName", MYPREFS);
startActivity(myIntent);
But my SharedPreferences is not working after I save it and hit back a few times, to go at menu page and go to the page where I want to get my preferences.
Anyone can help me with that?
Code below:
This is where I save my preferences:
String MYPREFS = "MyPref";
SharedPreferences mySharedPreferences;
SharedPreferences.Editor myEditor;
Inside onCreate:
mySharedPreferences = getSharedPreferences(MYPREFS,0);
myEditor = mySharedPreferences.edit();
Inside button onClickListener:
myEditor.putString("address", AddressET.getText().toString());
myEditor.putString("contact", ContactET.getText().toString());
myEditor.commit();
Intent myIntent = new Intent(myContext, nok_individual_particular.class);
myIntent.putExtra("prefName", MYPREFS);
startActivity(myIntent);
This is the activity I pass to:
SharedPreferences mySharedPreferences;
Inside onCreate:
Intent myReceivingIntent = getIntent();
String myPREFName = myReceivingIntent.getStringExtra("prefName");
mySharedPreferences = getSharedPreferences(myPREFName, 0);
applySavedPreferences();
In the applySavedPreferences method:
String addressValue = mySharedPreferences.getString("address", "Jack Smith");
String contactValue = mySharedPreferences.getString("contact", "Jack Smith");
addressTV.setText(addressValue);
contactTV.setText(contactValue);
SharedPreferences: This is how it works
To save your data:
SharedPreferences sPrefs = getSharedPreferences("prefsName", 0);
SharedPreferences.Editor editor = sPrefs.edit();
editor.putString("valueName", "value");
editor.commit();
To retrieve your data:
SharedPreferences sPrefs = getSharedPreferences("prefsName", 0);
String strMyData = sPrefs.getString("valueName", "default value");
The example above is how to set a string and retrieve it.
You are not using SharedPreferences. In your example, you are passing an extra to an activity, but this only makes available the value to the new activity, it doesn't save the value to SharedPreferences.
To use SharedPreferences, you have to do the following:
Save
PreferenceManager.getDefaultSharedPreferences(this).edit().putString("prefName", "String to save").commit();
Get
String value = PreferenceManager.getDefaultSharedPreferences(this).getString("prefName"), "default value");
After mySharedPreferences.edit();
mySharedPreferences.commit();
should be your last line. This enables u to save and close the SharedPreferences file you have edited.
Well, you don't need to pass the sharedprefs in an intent and all. It will be available throughout your application in all activities.
Just call SharedPreferences my_prefs= getSharedPreferences("Pref_name", 0); and then u have a reference to that SharedPreferences file and then u can retrieve values from it.
I prefer using SharedPreferences to save my data and use it throughout my classes , plus they will be saved to the device , making them available even after the app is killed ... Here is an example for ya !
//Some String that I should remember, I am just using the package name for now
String app = this.getPackageName();/*This is going to be used more like a file to save my stuff to*/
//Setting our sharedpreferences
SharedPreferences sha = sha = getApplicationContext().getSharedPreferences(app, SherlockActivity.MODE_PRIVATE);
String myString = "This is the String that you want to save so you can use among your classes"
//Now we call in an editor for that SharedPreferences so we can write and delete stuff from it .
Editor edit = sha.edit();
//Now we insert our String.
edit.putString("Something_you_can_remember" , myString);//You will need the "Something_you_can_remember" a few lines ahead , so remember it !
edit.apply(); //Or we can use edit.commit() , but I prefer apply()
//Now our String is saved ! So lets read it !
String whatever = sha.getString("Something_you_can_remember" , "The String incase myString didn't even exist , saves you from a NullPointerException");
//Here we go ! Now we have our String saved and can be readable among the classes !
//Also , if you wanted to delete that String or whatever you "put" in there , you can call
edit.remove("Something_you_can_remember"); //or edit.clear() to remove all the values stored !
Hope this helps !
Save
SharedPreferences sp = getSharedPreferences("key", 0);
SharedPreferences.Editor sedt = sp.edit();
sedt.putString("valueName", "String to save");
sedt.commit();
Get
SharedPreferences sp = getSharedPreferences("key", 0);
String valueName = sp.getString("valueName","");
You do not need to pass SharedPrefences through intents, as SharedPreferences are available to the whole application and any activity has access to it.
You can refer to below example:
Either create SharedPreferences by giving them your choice of name:
SharedPreferences pref = getSharedPreferences("MyPref", MODE_PRIVATE);
OR use default SharedPreferences:
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Use your preference file anywhere in your code by getting them through any of the above methods. No need to pass to different activities.
Once you call any of the above method, if the preference file of that name does not exist for your application, android will create one for you.

Categories

Resources