Clear Shared Preferences - java

I am trying to make it possible that you can save a high score and I also need the user to be able to reset/delete their high score. the TOAST works but the data doesn't get deleted.
public static final String PREFS_NAME = "MyPrefsFile";
static SharedPreferences settings;
static SharedPreferences.Editor editor;
// When 'back' button is pressed save the highscore to settings
editor = settings.edit();// Create a new editor
editor.putInt("highscore", HighScore); // Storing integer
editor.commit();
// When 'Show' button is pressed
public void showPreferences(View v) {
int highscore = GameActivity.settings.getInt("highscore", GameActivity.HighScore);
Toast.makeText( MainMenu.this, "Your Highscore is: " + highscore, Toast.LENGTH_LONG).show();
}
//When delete button is pressed
public void clearPreferences(View V) {
GameActivity.editor = GameActivity.settings.edit();// Create a new editor
GameActivity.editor.clear();
GameActivity.editor.commit();
Toast.makeText( MainMenu.this,"Highscore has been reset",Toast.LENGTH_LONG).show();
}

I believe you are just reading it wrong, use this
int highscore = GameActivity.settings.getInt("highscore", 0);
Note that second parameter is the default value, a value that is returned if the value by that key is not present in the settings.

You can try this:
settings = getSharedPreferences("MyPrefsFile", 0);
preferences.edit().remove("highscore").commit();
Or you can update the sharepreference by the value 0.

Use the below to clear shared preferences
settings.edit().clear().commit();
Or use the below to clear single value from preferences
settings.edit().remove("highscore").commit();

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"

Generate random int and save it to SharedPreferences

I need to generate random int to give device id when my app run for the first time, then save it to SharedPreffs, show id on TextView, and when is turned on again show saved id from SharedPreffs on TextView.
public class MainActivity extends AppCompatActivity {
public static final String MyPREFERENCES = "MyPrefs";
public static final String KEY_DEVICE = "id";
SharedPreferences sharedpreferences;
String id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
deviceid = (TextView) findViewById(R.id.deviceid);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (!sharedpreferences.contains(id)) {
SharedPreferences.Editor editor = sharedpreferences.edit();
id = String.valueOf(new Random().nextInt(900000) + 100000);
editor.putString(KEY_DEVICE, id);
editor.commit();
deviceid.setText(id);
}
deviceid.setText(id);
}
}
Above code generates random int and show it on TexView, but every time I hide or turn off the app, the device id changes
Could you explain me what i have to do to achive my goal.
There should be "id" or KEY_DEVICE
Replace
!sharedpreferences.contains(id)
to
!sharedpreferences.contains(KEY_DEVICE)
Also
deviceid.setText(id);
will show null in that case
So you have to add before setText
id = sharedpreferences.getString(KEY_DEVICE,"0");
Try this
String MyPREFERENCES = "MyPrefs";
String KEY_DEVICE = "device_id";
SharedPreferences sharedpreferences;
SharedPreferences.Editor editor;
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (sharedpreferences.contains(KEY_DEVICE)) {
id = sharedpreferences.getString(KEY_DEVICE, "0");
deviceid.setText(id);
} else {
id = String.valueOf(new Random().nextInt(900000) + 100000);
editor = sharedpreferences.edit();
editor.putString(KEY_DEVICE, id);
editor.apply();
deviceid.setText(id);
}
This is because you are just checking if there is no shared preference value then select a random number and add it to device but you are not getting any value in the on create method i.e you are not getting any shared preference value that you stored before. Simply get your stored value and then check if the value is exist, if exists then set in textview otherwise call the condition check. Hope it Helps
Put a check for null before fetching the value from sharedPreferences.
If it is null : then save the id
else : fetch the older one only.
If this check : if(!sharedpreferences.contains(id)) is required then keep it nested under null check.

Sharedpreferences returning null value after saving

I have a radiogroup with two radio buttons. I want to select one radio button and hit save so that when I return the same radiobutton will be selected already. The problem is that even after I hit save the sharedpreferences in onCreate always returns null. I know that the save function is executing because the toast runs and I get the System.out.println printed in my console.
public void saveSettings(View view)
{
Toast.makeText(getApplicationContext(), "Settings Saved", Toast.LENGTH_LONG).show();
//DETERMINE WHICH RADIO BUTTON IS SELECTED
RadioButton lbSetting = (RadioButton)findViewById(R.id.weightSettingLB);
RadioButton kgSetting = (RadioButton)findViewById(R.id.weightSettingKG);
if(lbSetting.isChecked())
{
weightSetting = "lb";
}
if(kgSetting.isChecked())
{
weightSetting = "kg";
}
System.out.println("The " + weightSetting + " radio button has been selected.");
//SAVE WEIGHT SETTING BETWEEN LB/KG
settingsPrefString = getSharedPreferences(weightSetting, 0);
SharedPreferences.Editor editor = settingsPrefString.edit();
editor.putString("weightSetting", weightSetting);
editor.commit();
}
In my onCreate I try to retrieve the saved data as
if(settingsPrefString != null)
{
weightSetting = settingsPrefString.getString("weightSetting", "Couldn't load data!");
}
if(settingsPrefString == null)
{
System.out.println("settingsPrefString is NULL!");
}
Even after I hit save the sharedpreferences is always being returned as null.
Call these functions when you need them:
private void savePreferences(String key, String value){
SharedPreferences sharedPreferences = getSharedPreferences("weightSetting", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private String loadPreferences(String key){
SharedPreferences sharedPreferences = getSharedPreferences("weightSetting", MODE_PRIVATE);
String load = sharedPreferences.getString(key, "");
return load;
}
}
For example:
savePreferences("selected", "lb");
and
String s = loadPreferences("selected);
The mistake you are doing is inside saveSettings method. While creating a shared preference for the first you are not assigning a constant name to it since you have used variable for name so change it. Create a global string constant for same
//SAVE WEIGHT SETTING BETWEEN LB/KG
settingsPrefString = getSharedPreferences(weightSetting, 0);
SharedPreferences.Editor editor = settingsPrefString.edit();
to
public static final String SETTINGS_PREFERENCE = "SETTINGS_PREFERENCE"
SharedPreference settingsPrefString
//your code
//saveSettings method
//SAVE WEIGHT SETTING BETWEEN LB/KG
settingsPrefString = getSharedPreferences(SETTINGS_PREFERENCE , Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settingsPrefString.edit();
if you look in the change then two constant are used which makes code more readable and accessable.
Also next time inside your onCreate() method you will have to add
settingsPrefString = getSharedPreferences(SETTINGS_PREFERENCE , Context.MODE_PRIVATE);
if(settingsPrefString != null)
{
weightSetting = settingsPrefString.getString("weightSetting", "Couldn't load data!");
} else {
System.out.println("settingsPrefString is NULL!");
}
Replace
settingsPrefString = getSharedPreferences(weightSetting, 0);
With
settingsPrefString = getSharedPreferences(weightSetting, Context.MODE_PRIVATE);
This will also help
settingsPrefString = PreferenceManager.getDefaultSharedPreferences(this);
and follow this link

issue with unmute button java android

I'm creating a simple click counter android app, sound is played when a button is clicked and the count is also saved when leaving the count screen and then returning to it.
I have encountered a problem with the mute button. When I click it, it mutes the whole application rather than just that particular gui screen (activity).
First issue is that the mute button mutes the sound for the whole app, and I only need to mute for that activity.
Second issue is that when you click mute button and come out of the screen, then go back, then try to unmute - it does not unmute the sound.
Was thinking the resolution to this is that we take the mute button out of the SharedPreferences save instance state - if this is possible...
Here is my code so far, if you can guide me on how to achieve the above that would be great. Thanks.
public class wazeefa extends Activity {
//Count Button
TextView txtCount;
ImageView image;
Button btnCount;
Button wmute;
Button wreset;
public static int count = 0;
SharedPreferences app_preferences;
MediaPlayer mpButtonClick;
AudioManager audioManager;
public static boolean mutestatus = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// The activity is being created.
setContentView(R.layout.wazeefa);
audioManager =
(AudioManager) getSystemService(Context.AUDIO_SERVICE);
//SAVE COUNT
app_preferences = this.getSharedPreferences("myPrefscount", MODE_WORLD_READABLE);
count = app_preferences.getInt("count", 0);
txtCount = (TextView) findViewById(R.id.wcount);
txtCount.setText("This app has been started " + count + " times.");
image = (ImageView) findViewById(R.id.imageview);
txtCount = (TextView) findViewById(R.id.wcount);
txtCount.setText("This app has been started " + count + " times.");
//Button SOUND AND COUNT
mpButtonClick = MediaPlayer.create(this, R.raw.bubble);
//RESET Button
wreset = (Button) findViewById(R.id.wreset);
txtCount = (TextView) findViewById(R.id.wcount);
txtCount.setText(String.valueOf(count));
btnCount = (Button) findViewById(R.id.wclick);
wmute = (Button) findViewById(R.id.wmute);
btnCount.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
count++;
if (count > 50) count = 0;
image.setImageResource(R.drawable.duroodimage);
if (count > 0) image.setImageResource(R.drawable.duroodimage);
if (count > 9) image.setImageResource(R.drawable.zikrimage);
if (count > 39) image.setImageResource(R.drawable.duroodimage);
txtCount.setText(String.valueOf(count));
mpButtonClick.start();
}
});
wreset.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
count = 0;
image.setImageResource(R.drawable.duroodimage);
;
txtCount.setText("0");
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("count", count);
editor.commit();
}
});
wmute.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!mutestatus) {
mutestatus = true;
audioManager.setMode(AudioManager.MODE_IN_CALL);
audioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, true);
Log.v("'test....", "" + mutestatus);
} else {
mutestatus = false;
audioManager.setMode(AudioManager.MODE_NORMAL);
audioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, false);
Log.v("'test....", "" + mutestatus);
}
}
});
}
#Override
protected void onPause() {
super.onPause();
// save count value here
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("count", count);
editor.commit();
}
}
You are saving the preferences on the application level, make it Activity specific, i.e. Implement mute functionality for the activity not the application.
Edit
See your objective is some what to mute and unmute (loquent) the audio, Preferences can be saved in three ways.
1) Preferences can be retrieved only by a single activity.
2 )Preferences can be shared and retrieved among all activities within the application.
3)Preferences can be shared and retrieved through all applications on the device.
In your case, Saving Activity-level preferences:
SharedPreferences prefs=getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor=prefs.edit();
editor.putString("pref 1", "some text");
editor.commit();
We get a SharedPreferences object by calling getPreferences(int mode) method which takes an integer value as a parameter, the mode value can be one of the following:
Context.MODE_PRIVATE (0): a file creating mode that makes the created file only accessible by applications with the same user ID (access the file from the same application context, will desctribe later).
Context.MODE_WORLD_READABLE (1): file mode makes the file readable from other applications.
Context.MODE_WORLD_WRITEABLE (2): file mode allows other applications to write to the file.
Then we get an instance of SharedPreferences.Editor and write the preference value with editor.putString(String key, String value) method.
shared preferences allows you to insert preferences using the following methods:
editor.putBoolean(String key, boolean value).
editor.putFloat(String key,float value).
editor.putInt(String key, int value).
editor.putLong(String key, long value)
editor.putString(String key, String value)
Then we call edit.commit() to save the preferences to the file. commit returns a boolean indicating the result of saving, true if successful and false if failed.
Reading preferences values:
To read preferences values:
SharedPreferences prefs=getPreferences(Context.MODE_PRIVATE);
String val=prefs.getString("pref 1", "some text");
We use sharedpreferences.getString(String key, String defaultValue) (or get boolean/float/int) to return the value stored with a specific key or defaultValue if not found.
Source

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

Categories

Resources