SharedPreferences with OnCreate - java

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
}

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"

I need to set the value of a global variable and save it even on restarting the app

So I'm developing a feature in an app where I have a boolean set to true which leads to some action being done. Now, onClick of a button will do a few related tasks and also set the boolean to false. That's fine and it works great, but once it has been changed to false, I want that on restarting the app it is assigned as false instead of true. I've tried searching for a while without any luck. Help will be appreciated.
I've only been learning Java and Android app dev for 2 months and now I'm making programs, so kindly bear with me. Maybe some sort of use of Boolean instead of boolean? I haven't got too far though.
public class Constants {
public static boolean VARIABLE = true;
}
public Fragment {
mSharedPreferencesManager.setFeatureUpdateCheck(Constants.VARIABLE);
if(mSharedPreferencesManager.getFeatureUpdateCheck())
chatUpdateNotif.setVisibility(View.VISIBLE);
else
chatUpdateNotif.setVisibility(View.GONE);
#OnClick (R.id.chat_notification_close_button)
public void onClickHideNotification() {
chatUpdateNotif.setVisibility(View.GONE);
Constants.VARIABLE = false;
Your question is very unclear.If you are trying to save a value in closing the application and getting the value back on restart try using shared preferences.
1.Save the value on click of button
SharedPreferences sharedPref = getSharedPreferences("YOUR PREF NAME", Context.MODE_PRIVATE);
sharedPref.edit().putBoolean("VALUE NAME", true).apply();
2.Restore the value from preferences on restring app
sharedPref.getBoolean("VALUE NAME", null);
Edit:If your are not using activity use context to use preference
SharedPreferences sharedPref = context.getSharedPreferences("YOUR PREF NAME", Context.MODE_PRIVATE);
Use Shared Preferences to save the boolean value when it is changed like this:
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
"DataSaved", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("VARIABLE", VARIABLE);
editor.commit();
Then in Constant write this:
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
"DataSaved", Context.MODE_PRIVATE);
VARIABLE = sharedPref.getBoolean("VARIABLE", false);
private String MY_PREFS_NAME = "sharedPref";
This sets the boolean:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putBoolean("Value", false);
editor.commit();
This gets the boolean:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
TextView textview = (TextView)findViewById(R.id.textview);
textview.setText(String.valueOf(prefs.getBoolean("Value", true)));
This textview will print out false, because the boolean has been set. If the boolean was not set it would be true (default value).

Saving changed Activity background colour on button click

I have this code which allows me to change the background colour of my activity and I call this on a button click.
View someView = findViewById(R.id.mainLayout);
View root = someView.getRootView();
root.setBackgroundColor(0xFF00FF00);
How can I save the background colour so that it stays changed whenever the app is restarted.
If you need to persist this setting across multiple starts by the user use SharedPreferences as described here:
http://developer.android.com/training/basics/data-storage/shared-preferences.html
If you only want to keep this setting when re-created by the system because of orientation changes for example, use onSaveInstanceState() and check for a Bundle in onCreate() as described here:
http://developer.android.com/training/basics/activity-lifecycle/recreating.html
Save to SharedPref.
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(KEY, Value);
editor.commit();
Read from SharedPref.
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int i = sharedPref.getInt(KEY, defaultValue);
Set Flag in sharedPreferences by
Editor editor = sharedpreferences.edit();
editor.putString(Flag, "Y");
And while loading the screen in Oncreate check for the flag by
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (sharedpreferences.contains(Flag))
{
name.setText(sharedpreferences.getString(Flag, ""));
}

how to persist data in editText using Shared Preferences in android

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

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