Using share preference to save some a few int - java

android, java, sharedpreferences, datad during the run . What I want is that if I close or pause my app the ints value are saved, so when I open it back again I can have the last value back.
I have this so far, trying with 1 int to learn how to.
protected void onPause(){
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("valueSave",valueToSave );
editor.commit();
}
#Override
protected void onResume(){
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
}
But values are not saved... what am I doing wrong?
EDIT: onCreate added
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.program);
//SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
//settings = getSharedPreferences(PREFS_NAME, 0);
valueToSave = settings.getInt("valueSave",valueToSave);

Try getting a SharedPreference using the application context in this way:
To save preferences:
int valueToSave = 1;
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit();
editor.putInt("someValue", valueToSave);
editor.commit();
To retreive from preferences:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
int savedvalue = settings.getInt("someValue");

Related

Shared preference value is null in my second acivity

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

Preference wont change in my main activity

In my MainActivity I have a textView.
In that textView there is a Number that I keep in a SharedPreferences.
and every couple of min The SharedPreferences is changed with an alarm manager,
but the SharedPreferences in my MainActivity wont change,
anyone has an idea why?
this is a part of The code in the MainActivity
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
int ReleaseDate = preferences.getInt("com.fisher.freedom.ReleaseDate", 0);
TextView edit = (TextView) findViewById(R.id.DaysLeft);
Toast.makeText(MainActivity.this, "" + preferences.getInt("com.fisher.freedom.ReleaseDate", 0), Toast.LENGTH_SHORT).show();
edit.setText("" + ReleaseDate);
This is the code in the AlarmReceiver
public static final String ReleaseDate_Key = "com.fisher.freedom.ReleaseDate";
#Override
public void onReceive(Context context, Intent intent) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
int ReleaseDate = preferences.getInt(ReleaseDate_Key, 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt(ReleaseDate_Key, --ReleaseDate);
editor.apply();
For get the value of your int use this:
SharedPreferences sharedPreferences = getSharedPreferences(getApplicationContext().getPackageName(),0);
int ReleaseDate = sharedPreferences.getInt("ReleaseDate",0);
And to save it use this:
SharedPreferences prefs = getSharedPreferences(getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
prefs.edit().putInt("ReleaseDate", ReleaseDate).commit();
With this you forget about writing on static variable your package name, it worked for me, so it's going for you.

Load strings from sharedpreferences in EditText (two classes)

I have two different activity's. First one only showed to the user first time - to store phonenumber inside sharedprefs. I think the problem is my load from prefs method but just in case I will leave everything here to make it more relevant to future users. It looks like in both activitys the "mobilnummer" is saved - but I am having problem to display them.
The idea is it to be overwritten if user updates it - I think the method will do that?
OnStartUp.java
public static final String PREFS_NAME = "MobileNumberSaved";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mobilnummer = (EditText) findViewById(R.id.mobilnummer);
final Button button = (Button) findViewById(R.id.ntonboarding);}
public void SaveToMobile(View v) {
if (mobilnummer.getText().toString().length() >= 8) {
FragmentedUser.SaveMobile(mobilnummer.getText().toString()); // just saves to Parse.com (This works)
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("mobilnummer", mobilnummer.toString());
editor.commit();
}
}
Profile
EditText mobilnummer;
public static final String PREFS_NAME = "MobileNumberSaved";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mobilnummer = (EditText) findViewById(R.id.mobilnummer);
This is the issue/problem i think! (Code below)
SharedPreferences MobileNumberSaved = this.getSharedPreferences("mobilnummer", Context.MODE_PRIVATE);
String tempMobilnummer = mobilnummer.getText().toString();
mobilnummer.setText(tempMobilnummer);
// IF user wants to change mobilenumber
mobilnummer.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_SEND) {
if (mobilnummer.getText().toString().length() >= 8)
FragmentedUser.SaveMobile(mobilnummer.getText().toString());
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("mobilnummer", mobilnummer.toString());
editor.commit();
tlfstatus.setImageResource(R.drawable.ok);
handled = true;
}
return handled;
}
});
I think here is your error:
SharedPreferences MobileNumberSaved = this.getSharedPreferences("mobilnummer", Context.MODE_PRIVATE);
//here it should be MobileNumberSaved instead of mobilnummer, because tehre is no sense to set the same text to the textView again after you got it from there
String tempMobilnummer = MobileNumberSaved.getText().toString();
mobilnummer.setText(tempMobilnummer);
But the correct way to get a value from shared preferences is something like this:
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String savedMobileNumber = prefs.getString("mobilnummer", "");
mobilnummer.setText(savedMobileNumber);
Update: when you save the value in the shared preferences, you save only the editText, not it's value, so do something like this when saving:
SharedPreferences.Editor editor = settings.edit();
//mobilnumber is your EditText, so get it's text like this
editor.putString("mobilnummer", mobilnummer.getText().toString());
editor.commit();
And everything else is still the same that I wrote above

Unable to save highscore of game using shared preferences?

Here is my code for game i use to save high score
SharedPreferences preferences = null;
SharedPreferences.Editor editor = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
//Highscore.easyHigh = 0;
Highscore.easyHigh = preferences.getInt("EasyScore", 0);
Highscore.mediumHigh = preferences.getInt("MediumScore", 0);
Highscore.hardHigh = preferences.getInt("HardScore", 0);
Now i set these values when player looses the game
editor = preferences.edit();
if(level==1)
editor.putInt("EasyScore", score);
else if(level==2)
editor.putInt("MediumScore", score);
else if(level==3)
editor.putInt("HardScore", score);
editor.commit();
Highscore is my class storing public static int easy, medium , hard?
I get a null pointer exception but why does that happen?
Your preferences and editor values are not initalized, use this :
preferences = PreferencesManager.getDefaultSharedPreferenes(this);
editor = preferences.edit();
You havent initialised preferences and editor..Do it after setContentView() in your code..
Do it like this..
preferences = PreferencesManager.getDefaultSharedPreferenes(this);
editor = preferences.edit();

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!

Categories

Resources