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
Related
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.
I need to use string data inside OnReceivedDataMethod into second activity in order to save those string data into file but currently i have empty data into my file
SharedPreferences sp;
UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() { //Defining a Callback which triggers whenever data is read.
#Override
public void onReceivedData(byte[] arg0) {
try {
data = new String(arg0, "UTF-8");
data.concat("/n");
sp = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor et = sp.edit();
et.putString("key",data);
et.apply();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
};
In second activity
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
desiredPreference = sharedPreferences.getString("key","data");
Toast.makeText(this,"spdata"+desiredPreference,Toast.LENGTH_LONG).show();
}
The Value is null because you used PreferenceManager.getDefaultSharedPreferences(this) which returns preference with this activity name and it's different from the other preference you used in your first activity. Instead, you should call your preference in the same way you called it in your first activity.
SharedPreferences prefs = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String desiredPreference = sharedPreferences.getString("key","data");
To know more about the difference you can check the documentation and this answer.
Do something like this,
For storing
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("key", data);
editor.commit();
for Retriving
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
String checkDate = sharedPref.getString("key","");
I am using shared preferences but my code is not working. I don't know what's wrong with it. Am I implementing something wrong?
My main java activity(relevant bit of code) is:
public class MainActivity extends AppCompatActivity {
private String s;
public static final String subjectKey = "SubjectID";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SharedPreferences sharedPreferences = getSharedPreferences(subjectKey, Context.MODE_PRIVATE);
TextView calc_monday = (TextView) findViewById(R.id.monday_calc);
calc_monday.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View v){
CustomDialogClass cdd = new CustomDialogClass(MainActivity.this);
cdd.show();
TextView text1 = (TextView) cdd.findViewById(R.id.Subject_ID);
String text = sharedPreferences.getString(subjectKey, " ");
if(text != " ")
{
text1.setText(text); /* Edit the value here*/
}
TextView text2 = (TextView) cdd.findViewById(R.id.Room_ID);
text2.setText("6 (SEECS)");
TextView text3 = (TextView) cdd.findViewById(R.id.Time_ID);
text3.setText("09:00am - 09:50am");
}
}
);
calc_monday.setOnLongClickListener(
new Button.OnLongClickListener() {
public boolean onLongClick(View v) {
SettingDialogClass SDC = new SettingDialogClass(MainActivity.this);
SDC.show();
EditText texii = (EditText) SDC.findViewById(R.id.set_Subject_ID);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(subjectKey, texii.getText().toString());
editor.apply();
return true;
}
}
);
Basically I want that when I longClick a textbox (calc_monday), a dialog box should appear which appears. Now I should be able to write something on the EditText field which appears on this dialog box. Whatever I write should be stored and then displayed when I SINGLE CLICK on the same textbox (calc_monday)
Please see the 2 methods: onClick and onLongClick to understand.
The code is not working, i.e the text I write on EditText field on onLongCLick dialog box is not being displayed when I single click on the textbox.
What's wrong with the code
When you long press calc_monday, it just show your custom dialog with empty value for EditText. To save your text when input in EditText, create a button in your custom dialog, and call onClickListener action for this button, then save value to SharePreferences.
calc_monday.setOnLongClickListener(
new Button.OnLongClickListener() {
public boolean onLongClick(View v) {
SettingDialogClass SDC = new SettingDialogClass(MainActivity.this);
EditText texii = (EditText) SDC.findViewById(R.id.set_Subject_ID);
Button btnSave = (Button)SDC.findViewById(R.id.your_custom_button);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(subjectKey, texii.getText().toString());
editor.apply();
SDC.dismiss();
}
});
SDC.show();
return true;
}
}
);
I think it's should be :
String text = sharedPreferences.getString("Name", " ");
Try these methods for saving and loading Strings with preferences:
//save prefs
public void savePrefs(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
//get prefs
public String loadPrefs(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String data = sharedPreferences.getString(key, value);
return data;
}
You can call the load method like this:
subjectKey = loadPrefs("YouCanNameThisAnything", subjectKey);
And you can call the save method like this:
savePrefs("YouCanNameThisAnything", subjectKey);
More details on how to use shared preferences is also available in the documentation here:
http://developer.android.com/reference/android/content/SharedPreferences.html
//create and initialize the intance of shared preference
SharedPreferences sharedPreferences = getSharedPreferences("Session", MODE_PRIVATE);
//save a string
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putString(subjectKey , texii.getText().toString());
edit.commit();
//retrieve the string
String subject = sharedPreferences.getString(subjectKey, "");
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();
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!