how to persist data in editText using Shared Preferences in android - java

I have simple editText in which user enters number or string.
I want to persist that number or string when user again enters the app.

1.first save this into preference like this
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString(MY_NAME, edittext.getText().toString());
prefsEditor.putString(MY_WALLPAPER, "f664.PNG");
prefsEditor.commit();
2.Now second time you will get through whenever you get use this
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String prefName = myPrefs.getString(MY_NAME, 0);
String wallPaper = myPrefs.getString(MY_WALLPAPER, null);

It looks like you could do something similar to this: Counting Chars in EditText Changed Listener
Then, once you have detected that the text has changed, you can save it to your SharedPreferences.
Alternatively, if you only want to persist when the user leaves/enters the app, then you could just override the onPause() method of your Activity to save to your SharedPreferences. Just use <EditText>.getText() to get the String entered and then save that. Override onResume() and then use <EditText>.setText(<String from SharedPreference>) to restore it upon entering your app.
I'm assuming you know how to use SharedPreferences, but let me know if you don't.

This code will persist the data when the user removes focus from the EditText Box using the OnFocusChangeListener;
EditText userInput = (EditText)findViewById(R.id.ID_HERE);
SharedPreferences pref = this.getPreferences(this.MODE_PRIVATE);
String data_key = "data";
View.OnFocusChangeListener persistData = new View.OnFocusChangeListener(){
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(!hasFocus){
EditText e = (EditText)v;
SharedPreferences.Editor edit = pref.edit();
edit.putString(data_key,e.getText().toString());
edit.commit();
}
}
};
userInput.setOnFocusChangeListener(persistData);

Related

SharedPreferences If/Else Statement does not work correctly when I force close app

Summary of problem: When I force close the app by opening task window and swiping it closed my if/else statement is not working properly. I have the Name Selection Activity as the Default Launcher Activity. The name selection Activity should only pop up if there are no Shared Prefs, meaning the user has not selected a name yet from the spinner. But even after the user has selected a name and it is stored in Share Prefs, when I force close the app I still get returned to the name selection activity
What I have tried I have tried if (stringNamePackage.equals("")) and if (stringNamePackage == "") and if (NAME.equals("")) and if (NAME == "") At first I thought it was because maybe my Shared Prefs was not saving the name correctly but it is not that, the name still appears correctly when I force close it. But when I try to add the if/else statment it always just sends me back to the name selection activity regardless if I have a name saved in Shared Prefs or not. I have spent 4 hours trying to get this to work and I am at my wits end. I also spent hours looking at different stack articles of how to save and retrieve Shared Pref data. I even tried how to check the SharedPreferences string is empty or null *android and it is still not working.
NameSelectionActivity
public class NameSelection extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
Spinner nameSpinner;
String stringNamePackage;
Button bSaveSelection;
Context context;
public ArrayAdapter<CharSequence> adapter;
public static String SHARED_PREFS = "sharedPrefs";
public static String NAME = "name";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_name_selection);
context = this;
nameSpinner = findViewById(R.id.horizonNameSpinner);
stringNamePackage = "";
//Create the list to populate the spinner
List<String> nameList = new ArrayList<>();
nameList.add("01");
nameList.add("02");
nameList.add("03");
//Array Adapter for creating list
//adapter = ArrayAdapter.createFromResource(this, R.array., android.R.layout.simple_spinner_item);
adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, nameList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
nameSpinner.setAdapter(adapter);
nameSpinner.setOnItemSelectedListener(this);
//If User has not selected name, start this activity to allow user to pick Name, else, send user to Main Activity
//else start MainActivity
if (stringNamePackage .equals("")) {
Toast.makeText(this, "Welcome, please select Name", Toast.LENGTH_LONG).show();
} else {
Intent sendToMainActIntent = new Intent(this, MainActivity.class);
startActivity(sendToMainActIntent);
}
//Save Selection Button Code
bSaveSelection = findViewById(R.id.bSaveSelection);
bSaveSelection.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), MainActivity.class);
//Saves name to SharedPrefs
saveName();
//Sends user to MainActivity
startActivity(myIntent);
finish();
}
});
}
//Stores name selected in SharedPreferences
public void saveName() {
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = app_preferences.edit();
editor.clear();
//Stores selection in stringNamePackage
editor.putString(NAME, stringNamePackage );
editor.commit();
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//Put user selection into String text
String text = adapterView.getItemAtPosition(i).toString();
stringNamePackage = text;
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
Main Activity
The purpose of this activity case is to send the user back to the name Selection screen when they hit the "Test" button which will erase the shared prefs and hence, trigger the if/else statement and making the user pick a name. This is how I get and set the Name in Main Activity:
in onCreate
Getting name
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(context);
nameSharedPref = app_preferences.getString(NAME, "");
name.setText(nameSharedPref);
Clearing Name
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = mPrefs.edit();
editor.clear();
editor.commit();
finish();
What I expect: I expect the user to have to pick a name the first time they boot up the app. Then, every time they open the app an if/else statement will check if the user has a name or not in Shared Prefs. If they have a name they will go directly to the Main Activity. If they don't then they will go back to the Name Selection Activity.
To get data and store data to your SharedPreferences you use this:
SharedPreferences sharedPreferences = getSharedPreferences(getPackageName(), Context.MODE_PRIVATE);
PreferenceManager.getDefaultSharedPreferences(context) is used to build "Settings" screens or similar, the first one you use it to store/retrieve arbitrary data not necessarily binded to UI.
Even more if you want to organize your SharedPreferences you could append to getPackageName() different keys like:
getSharedPreferences(getPackageName() + ".booleans", Context.MODE_PRIVATE);
getSharedPreferences(getPackageName() + ".flags", Context.MODE_PRIVATE);
getSharedPreferences(getPackageName() + ".keys", Context.MODE_PRIVATE);
each one of them is different file that stores shared preferences, you can ommit the prepending dot ., but for naming consistency it'll be better to keep it, there is no really need for the extra keys, but if you have some sort of OCD, that might be "relaxing" ;-).
Then you can use your Android Studio's Device Explorer to browse the shared preferences, they are located under "data/data/your.package.name/shared_prefs"

Permenantly storing a string, by a user?

On my main activity I'm looking into a variable, if the variable contains a string ("example string") then it will go to the home-screen. if the variable contains nothing ("") it will redirect them to a page where they can enter a value via an editText and then permanently store it. So the next time they open the app, it will have this permanent string (until the app is deleted) and therefore it will just go to the home-screen.
From research i understand that i may have to use Shared Preferences. I have tried this already and I think im not doing something right.
Please could someone illustrate with a code example of what needs to be done for the code i have posted.
MainActivity.class
//this class uses the string, to see if its blank or contains a string
public class MainActivity extends Activity {
public static final String Verified = ""; //Originally comes blank
private EditText NumberET; //editText for user to enter a string
//the string verified is used in the main activity to determine which xml file to open.
Verified.class
// this is the class used to enter the string and permanently store it
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.verified);
Button VerifyCompleteButton = (Button) findViewById(R.id.VerifyCompleteButton);
VerifyCompleteButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
String Verified;
String Number;
Bundle bundle = getIntent().getExtras();
Verified = bundle.getString("Verified");
NumberString = bundle.getString("NumberString")
Verified = NumberString.toString(); //set String Verified permenantly
}
});
You may use like this , Very much similar to above answer
For Saving String
SharedPreferences sharedPref = getSharedPreferences("App_Name_Prefs",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("Verified", Verified);
editor.commit();
For getting string
SharedPreferences shared = getSharedPreferences("App_Name_Prefs",
Context.MODE_PRIVATE);
String keyReturn = shared.getString(key, "");
Log.d("return value" , "Verified is " + verified);
Great example of using SharedPreference can be found on Google's Android developer website.
Saving data:
SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("KEY", "VALUE");
editor.commit();
Get data:
SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE);
String savedValue = context.getString("KEY", "");
Things to look after:
Make sure your [key] is the same for saving and getting. The shared preferences is a basically a hashmap/dictionary.
When getting use the second parameter to set a default return value when setting isn't found or set yet.

Using SharedPreferences between Activity

I have a configuration page which has a form on it. When the button is pressed, I want to save that value to a SharedPreference. This SharedPreference value then needs to be accessed from elsewhere in my app.
I am trying to save the value like the below. I want to save the collectionID so I can use it elsewhere
public class ConfigPage extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
Button mButton;
EditText mEdit;
String collectionID;
String key = "GregKey";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.config);
getActionBar().hide();
mButton = (Button)findViewById(R.id.setCollection);
mEdit = (EditText)findViewById(R.id.collectionName);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
collectionID = mEdit.getText().toString();
Log.d("EditText", collectionID);
SharedPreferences settings =
getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, collectionID);
editor.commit();
}
});
}
}
Once it has been saved, I then need to access it in another class, however I can't figure out how to do this. The example above crashes the application at the moment so something isn't quite right
I want to save the collectionID so I can use it elsewhere
Use mButton Button onClick event for saving EditText text in SharedPreferences as :
mButton.setOnClickListener( new View.OnClickListener()
{
public void onClick(View view)
{
collectionID = mEdit.getText().toString();
Log.d("EditText", collectionID);
// save value here in SharedPreferences
SharedPreferences settings =
ConfigPage.this.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(collectionID, collectionID);
editor.commit();
}
});
Your crash occurs because your value is null:
String savedID;
You need to add a value to the variable:
String savedID = "somevalue";
Also, your key is null as long as the Button is not pressed which will also lead to a crash.
The putString(String key, String value) method enables you to store a specific value with a specific key, that can later be used to reaccess the stored value.
Example:
String key = "somekey";
String value = "yourvaluetostore";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value); // store the value
editor.commit();
In another Activity:
String key = "somekey";
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, 0);
// get the value "" is default
String value = sharedPreferences.getString(key, "");
All you need in the other Activity is the key you stored the value with. With this key, you can pull the correct stored value out of the SharedPreferences. --> The key is needed to identify the value.
Since you are using the part of code :
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(collectionID, savedID);
editor.commit();
Log.d("Saved as", savedID);
in the onCreate method, that translates to
...
editor.putString(null, null);
Log.d("Saved as", null);
Correct your code so that you fill those elements before. I guess you wanted to make the save in the OnClick part
Yes something its not quite right here because as i see you are saving nothing. on shared pref you should have a "key" which will be use to identify the saved value in your example it should be something like this
public class ConfigPage extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
public static final String COLLECTIONID_KEY = "COLLECTIONID_KEY";
Button mButton;
EditText mEdit;
String collectionID;
String savedID;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.config);
getActionBar().hide();
mButton = (Button)findViewById(R.id.setCollection);
mEdit = (EditText)findViewById(R.id.collectionName);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
collectionID = mEdit.getText().toString();
Log.d("EditText", collectionID);
}
});
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(COLLECTIONID_KEY, collectionID);
editor.commit();
Log.d("Saved as", COLLECTIONID_KEY);
}
}
then to retrieve it :
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, 0);
String mySavedCollectionID = sharedPreferences.getString(COLLECTIONID_KEY);
and make sure that its done on the Onclick event otherwise you might end up with crash again because after the on-click event in your code the lines below will run anyway and save null!

SharedPreferences with OnCreate

I'm trying to achieve a goal which is adding some kind of wizard like this:
App launches for the first time > User follows wizard > Final wizard step saves some data into the SharedPreferences and continues to the activity that the user choosed > App Quits > App Relaunches > App shows activity that the user choose via the wizard data in SharedPreferences.
I know I can save data into the SharedPreferences space but how should I achieve this.
The user gets to see a view via an Android:OnClick action.
My App only has 1 main java class with different view actions like this:
public void myapp_confirmsetup(View view) {
setContentView(R.layout.activity_my_app_confirmsetup);
PreferenceManager.getDefaultSharedPreferences(this).edit().putString("MyApp", "app_off").commit();
}
I think that from now on I only have to load the string with the OnCreate method but I'm unsure how I can do that.
Can someone push me into the right direction?
use this to store the string...
final SharedPreferences pref1 = getSharedPreferences("myapp", MODE_PRIVATE);
SharedPreferences.Editor editor = pref1.edit();
editor.putString("Stringval", "xxxxxxx");
editor.commit();
to get the value from SharedPreference use below code:-
final SharedPreferences pref1 = getSharedPreferences("myapp", MODE_PRIVATE);
String str1= pref2.getString("Stringval", null);
final SharedPreferences pref1 = getSharedPreferences("myapp", MODE_PRIVATE);
String str1= pref1.getString("Stringval", null);
if(str1.equals("app_off")){
//do something
}else(str1.equals("app_on")){
//do something else
}

Need to save a high score for an Android game

It's quite simple, all I need to do is save a high score (an integer) for the game. I'm assuming the easiest way to do this would be to store it in a text file but I really have no idea how to go about doing this.
If all you need is to store an integer then SharedPreferences would be best for you to use:
//setting preferences
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putInt("key", score);
editor.commit();
To get a preference:
//getting preferences
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
int score = prefs.getInt("key", 0); //0 is the default value
Of course replace "key" with the key for your high score value and "myPrefsKey" with the key for your preferences (These can be whatever. It's just good to set them to something recognizable and unique).
I think this link will help you in it:
The SharedPreferences class provides a general framework that allows you to save and
retrieve persistent key-value pairs of primitive data types. You can use
SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings.
This data will persist across user sessions (even if your application is killed).
User Preferences
Shared preferences are not strictly for saving "user preferences," such as what ringtone
a user has chosen. If you're interested in creating user preferences for your
application, see PreferenceActivity, which provides an Activity framework for you to
create user preferences, which will be automatically persisted (using shared preferences).
To get a SharedPreferences object for your application, use one of two methods:
getSharedPreferences() - Use this if you need multiple preferences files identified
by name, which you specify with the first parameter.
getPreferences() - Use this if you need only one preferences file for your Activity.
Because this will be the only preferences file for your Activity, you don't supply a name.
To write values:
Call edit() to get a SharedPreferences.Editor.
Add values with methods such as putBoolean() and putString().
Commit the new values with commit()
To read values, use SharedPreferences methods such as getBoolean() and getString().
As I see, the best way for you to save high score is SharedPreferences.
Use shared preferences:
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
#Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
It's easiest way to store such a things.
public class HighScores extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_high);
//get text view
TextView scoreView = (TextView)findViewById(R.id.high_scores_list);
//get shared prefs
SharedPreferences scorePrefs = getSharedPreferences(PlayGame.GAME_PREFS, 0);
//get scores
String[] savedScores = scorePrefs.getString("highScores", "").split("\\|");
//build string
StringBuilder scoreBuild = new StringBuilder("");
for(String score : savedScores){
scoreBuild.append(score+"\n");
}
//display scores
scoreView.setText(scoreBuild.toString());
}
}

Categories

Resources