sharedPreferences help. How do I save an int? - java

I can't for the life of me seem to figure out how to save an int. All I want to do is save leftCounter into a file and retrieve it whenever I reboot my code.
public class SalesTrack extends Activity {
byte leftCounter = 0;
byte centerCounter = 0;
byte rightCounter = 0;
int total;
int x, y, z;
public static final String PREFS = "data";
TextView counterAAL, counterUPG, counterNL, counterTotal;
private final String LEFTY = "6";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sales_track);
counterAAL = (TextView) findViewById(R.id.left_number);
counterUPG = (TextView) findViewById(R.id.center_number);
counterNL = (TextView) findViewById(R.id.right_number);
counterTotal = (TextView) findViewById(R.id.total);
SharedPreferences sharedPref = this.getSharedPreferences(LEFTY, 0);
sharedPref.getInt("data", leftCounter);
counterAAL.setText(PREFS);
}
public void LeftInc(View v) {
leftCounter++;
counterAAL.setText("" + leftCounter);
Refresh();
}
public void LeftDec(View v) {
leftCounter--;
counterAAL.setText("" + leftCounter);
Refresh();
}
public void CenterInc(View v) {
centerCounter++;
counterUPG.setText("" + centerCounter);
Refresh();
}
public void CenterDec(View v) {
centerCounter--;
counterUPG.setText("" + centerCounter);
Refresh();
}
public void RightInc(View v) {
rightCounter++;
counterNL.setText("" + rightCounter);
Refresh();
}
public void RightDec(View v) {
rightCounter--;
counterNL.setText("" + rightCounter);
Refresh();
}
// Refresh Total after every click.
public void Refresh() {
x = leftCounter * 10;
y = centerCounter * 20;
z = rightCounter * 35;
total = x + y + z;
counterTotal.setText("" + total);
SharedPreferences sharedPref = getSharedPreferences(PREFS, 0);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("data", leftCounter);
editor.commit();
}
}

You have a mistake in your code.
// SharedPreferences sharedPref = getSharedPreferences(PREFS, 0); (This line is wrong)
SharedPreferences sharedPref = getSharedPreferences(LEFTY, 0);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("data", leftCounter);
editor.commit();

so you get the data from the file but it's detected as String ?
you can use the parse function to convert the String into Integer
int counter = Integer.parseInt(stringvalue);

You get the preferences with two different names LEFTY and PREFS. Given the names, I think you want to change the following line in your onCreate
SharedPreferences sharedPref = this.getSharedPreferences(LEFTY, 0);
to
SharedPreferences sharedPref = this.getSharedPreferences(PREFS, 0);

SharedPreferences sharedPref = getSharedPreferences(LEFTY, 0);
SharedPreferences.Editor editor = sharedPref .edit();
editor.putInt("data", leftCounter);
editor.commit();

You are saving your data inside preference named PREFS and fetching through preference nameLEFTY
Try to change your preference name from LEFTY to PREFS under onCreate().
protected void onCreate(Bundle savedInstanceState)
{
...
SharedPreferences sharedPref = this.getSharedPreferences(PREFS, 0);
}

Change like this
SharedPreferences sharedPref = = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("data", leftCounter);
editor.commit();

Related

Radio Button from another activity remains null?

In one activity I have my radio buttons. I'm able to save the selected state of the radio buttons throughout the application. In another activity I want to check which radio button is checked, but the radio buttons keep returning null.
Here's the first activity:
sharedPreferences = getApplicationContext().getSharedPreferences(GetInfo, MODE_PRIVATE);
go_back_btn = (Button) findViewById(R.id.go_back_btn);
distancebtn_group = findViewById(R.id.distance_btn_group);
miles_btn = (RadioButton) findViewById(R.id.miles_btn);
kilometer_btn = (RadioButton) findViewById(R.id.kilometer_btn);
go_back_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sharedPreferences = getApplicationContext().getSharedPreferences(GetInfo, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(MILESBTN, miles_btn.isChecked());
editor.putBoolean(KMBTN, kilometer_btn.isChecked());
editor.apply();
Intent intent = new Intent(settings.this, home.class);
intent.putExtra(MILESBTN, miles_btn.isChecked());
intent.putExtra(KMBTN, kilometer_btn.isChecked());
startActivity(intent);
}
});
kilometer_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sharedPreferences = getApplicationContext().getSharedPreferences(GetInfo, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(KMBTN, kilometer_btn.isChecked());
editor.apply();
}
});
miles_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sharedPreferences = getApplicationContext().getSharedPreferences(GetInfo, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(MILESBTN, miles_btn.isChecked());
editor.apply();
}
});
sharedPreferences = getApplicationContext().getSharedPreferences(GetInfo, MODE_PRIVATE);
kilometer_btn.setChecked(sharedPreferences.getBoolean("kilometer_btn", true));
miles_btn.setChecked(sharedPreferences.getBoolean("miles_btn", false));
}
Here's my second activity:
distance_counter = (TextView) findViewById(R.id.distance_counter);
distancebtn_group = (RadioGroup) findViewById(R.id.distance_btn_group);
miles_btn = (RadioButton) findViewById(R.id.miles_btn);
kilometer_btn = (RadioButton) findViewById(R.id.kilometer_btn);
distancebtn_group = findViewById(R.id.distance_btn_group);
final SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(settings.GetInfo, MODE_PRIVATE);
final Boolean milesbutton = sharedPreferences.getBoolean(MILESBTN, false);
final Boolean kilometerbutton = sharedPreferences.getBoolean(KMBTN, true);
Boolean milesbtn = getIntent().getBooleanExtra(MILESBTN, false);
Boolean kilometerbtn = getIntent().getBooleanExtra(KMBTN, true);
getIntent().getBooleanExtra(MILESBTN, false);
getIntent().getBooleanExtra(KMBTN, true);
}
}
});
}
#Override
public void onLocationChanged(Location location) {
curr_location = location;
if (start_location == null) {
start_location = curr_location;
end_location = curr_location;
} else
end_location = curr_location;
ChooseMetricUnits();
distance_counter.setText(new DecimalFormat("#.##").format(distance));
current_speed = location.getSpeed() * 2.236936;
SpdInmph.setText(new DecimalFormat("0.00").format(current_speed));
current_speed = location.getSpeed() * 3.6;
SpdInkmh.setText(new DecimalFormat("0.00").format(current_speed));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
private void distanceInMeters() {
distance = distance + (start_location.distanceTo(end_location));
start_location = end_location;
}
private void distanceInMiles() {
distance = distance + (start_location.distanceTo(end_location) * 0.00062137);
}
private void distanceInkilometers() {
distance = distance + (start_location.distanceTo(end_location) / 1000);
start_location = end_location;
}
public void ChooseMetricUnits() {
final SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(settings.GetInfo, MODE_PRIVATE);
Boolean milesbutton = sharedPreferences.getBoolean(MILESBTN, false);
Boolean kilometerbutton = sharedPreferences.getBoolean(KMBTN, true);
Boolean milesbtn = getIntent().getBooleanExtra(MILESBTN, true);
Boolean kilometerbtn = getIntent().getBooleanExtra(KMBTN, true);
getIntent().getBooleanExtra(MILESBTN, false);
getIntent().getBooleanExtra(KMBTN, true);
if(miles_btn.equals(milesbutton)) {
distanceInMiles();
: Run
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Object.equals(java.lang.Object)' on a null object reference
at mobile.run_interface.ChooseMetricUnits(run_interface.java:325)
enter image description here
As you can see the problem is here:
if(miles_btn.equals(milesbutton)) {
I've used BOTH putBoolean and putExtra to see if something different would happen when I pull the values from either one. Same result. I've placed the code for retrieving values, under create AND also under my ChooseMetricsUnits void method. My buttons are still null.
What am I doing wrong?
Has the activities the same layout? If they are not the same checks the import of R.id.miles_btn
And here there is another problem:
if(miles_btn.equals(milesbutton))
miles_btn is the RadioButton and milesbutton is a Boolean, so you must to change the code by:
if(miles_btn.isChecked() == milesbutton)
Solved the problem:
Hopes this helps anyone else in the future...\
private void ChooseMetricUnits() {
final SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(GetInfo, MODE_PRIVATE);
final Boolean MetricUnit = sharedPreferences.getBoolean(settings.KMBTN, true);
if(MetricUnit) {
distanceInkilometers();
} else
distanceInMiles();
}
}

I can't save integer

I Want to save the counter in my application memory and showing it.
I've tried sharedpreferences and didn't work.
public class MainActivity extends AppCompatActivity {
SharedPreferences sharedPreferences;
int counter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
counter = counter + 1;
tvCounter.setText(String.valueOf(counter));
}
});
}
protected int Counter(View view) {
SharedPreferences settings = getSharedPreferences(String.valueOf(counter), 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("int value", counter);
editor.commit();
sharedPreferences.getInt(String.valueOf(counter), -1);
return 0;
}
}
Counter is working,but application not saving anything.
SharedPreferences save key-value pair.
editor.putInt("int value", counter);
You are saving value of counter in key "int value".
And trying to retrieve it by wrong key
sharedPreferences.getInt(String.valueOf(counter), -1);
What you should do instead is
sharedPreferences.getInt("int value", -1);
I think you are also mixing up preferences file name. To cut confusion use final String's in the class scope.
private final String prefsFileName = "counterFile"; // file name for your shared preferences.
private final String counterKey = "counter"; // key to identify counter in your preferences.
To save counter value to shared preferences create a method.
private boolean saveCounter(int counter){
SharedPreferences prefs = getSharedPreferences(prefsFileName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(counterKey, counter);
return editor.commit();
}
To get counter value from shared preferences use another method.
private int getCounterValue() {
SharedPreferences prefs = getSharedPreferences(prefsFileName, Context.MODE_PRIVATE);
return prefs.getInt(counterKey, -1);
}

how to save changes using SharedPreferences?

I'm working on an application and I have to save changes made by the user ... the user going to click on an image, it's going to change the color. And I want to save that change.
I'm not sure how to do that actually. Here is where I want to make the change.
All I know is I need to use SharedPreferences .
private ImageView bookmark;
bookmark = (ImageView) findViewById(R.id.imageView_bookmark_readIt);
bookmark.setOnClickListener(new View.OnClickListener(){
private boolean bookmarking = true;
public void onClick(View v){
if(bookmarking){
bookmark.setImageResource(R.drawable.ic_bookmarked_blue);
bookmarking=false;
}
else{
bookmarking=true;
bookmark.setImageResource(R.drawable.ic_bookmark);
//Toast.makeText(getApplicationContext(), "Changed", Toast.LENGTH_LONG).show();
}
});
So does anybody have an idea of how to save changes made to the above code?
Note : I'm not using database
In shared preferences data is stored in the “key-value” format. As far as I understand, you need to save two fields and it will be something like this:
“booking: true”
“bookmarkImageResource: 15670341274”
Here is a convenient way to do it:
Step one – create a new class SharedPrefs:
public class SharedPrefs {
private static final String SHARED_PREFERENCES_NAME = "user_prefs";
private static final String BOOKING_INFO = "booking";
private static final String BOOKMARK_IMAGE_RESOURCE_INFO = "bookmarkImageResource";
private final SharedPreferences prefs;
public SharedPrefs(Context context) {
prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
}
public boolean saveBookingInfo(String bookingInfo, String bookmarkImageResource) {
return prefs.edit()
.putString(BOOKING_INFO, bookingInfo)
.putString(BOOKMARK_IMAGE_RESOURCE_INFO, bookmarkImageResource)
.commit();
}
public Pair<String, String> getBookingInfo() {
return new Pair<String, String>(
prefs.getString(BOOKING_INFO, ""),
prefs.getString(BOOKMARK_IMAGE_RESOURCE_INFO, ""));
}
public void clearAll() {
prefs.edit().clear().apply();
}
}
Step two - use your class wherever you need to save, get or clear data!
In you case:
SharedPrefs prefs = new SharedPrefs(this); // or getActivity() instead of this if we are in a fragment
if(bookmarking){
bookmark.setImageResource(R.drawable.ic_bookmarked_blue);
bookmarking=false;
}
else{
bookmarking=true;
bookmark.setImageResource(R.drawable.ic_bookmark);
}
prefs.saveBookingInfo(String.valueOf(bookmarking), String.valueOf(bookmark));
Hope this will help you =)
Have a good day & happy coding!
/**
* Get a shared preferences file named Const.SHARED_PREFERENCES_FILE_NAME, keys added to it must be unique
*
* #param ctx
* #return the shared preferences
*/
public static SharedPreferences getSharedPreferences(Context ctx) {
return ctx.getSharedPreferences(Const.SHARED_PREFERENCES_FILE_NAME, Context.MODE_PRIVATE);
}
public static void cacheBoolean(Context ctx, String k, Boolean v) {
SharedPreferences prefs = getSharedPreferences(ctx);
prefs.edit().putBoolean(k, v).apply();
}
public static Boolean getCachedBoolean(Context ctx, String k, Boolean defaultValue) {
SharedPreferences prefs = getSharedPreferences(ctx);
return prefs.getBoolean(k, defaultValue);
}
public static void cacheString(Context ctx, String k, String v) {
SharedPreferences prefs = getSharedPreferences(ctx);
prefs.edit().putString(k, v).apply();
}
public static String getCachedString(Context ctx, String k, String defaultValue) {
SharedPreferences prefs = getSharedPreferences(ctx);
return prefs.getString(k, defaultValue);
}
public static void cacheInt(Context ctx, String k, int v) {
SharedPreferences prefs = getSharedPreferences(ctx);
prefs.edit().putInt(k, v).apply();
}
public static int getCachedInt(Context ctx, String k, int defaultValue) {
SharedPreferences prefs = getSharedPreferences(ctx);
return prefs.getInt(k, defaultValue);
}
public static void clearCachedKey(Context context, String key) {
getSharedPreferences(context).edit().remove(key).apply();
}
Using SharedPreferences is very easy. You need to define a key which you will use to retrieve the data later. You can store Strings, ints, floats, booleans... You need to provide the context.
Context context = getApplicationContext();
To write data, use this code.
SharedPreferences mPrefs = context.getSharedPreferences("YourApp", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("color", "blue");
editor.apply();
To retrieve data, use this
SharedPreferences mPrefs = context.getSharedPreferences("YourApp", Context.MODE_PRIVATE);
String color = mPrefs.getString("color", "defaultValue");
You can easily change the type from String to other types that might best suit your needs.
Hope it helps.
Hope its help you
SharedPreferences sharedPrefs = getSharedPreferences("SharedPreferences_Name", Context.MODE_PRIVATE);
private ImageView bookmark;
bookmark = (ImageView) findViewById(R.id.imageView_bookmark_readIt);
private boolean bookmarking = sharedPrefs.getBoolean("bookmarking",true);//To get value that saved in SharedPreferences
if(bookmarking){
bookmark.setImageResource(R.drawable.ic_bookmarked_blue);
}
else{
bookmark.setImageResource(R.drawable.ic_bookmark);
//Toast.makeText(getApplicationContext(), "Changed", Toast.LENGTH_LONG).show();
}
bookmark.setOnClickListener(new View.OnClickListener(){
// private boolean bookmarking = true;
public void onClick(View v){
if(bookmarking){
bookmark.setImageResource(R.drawable.ic_bookmarked_blue);
bookmarking=false;
SharedPreferences.Editor editor = getSharedPreferences("SharedPreferences_Name", 0).edit();
editor.putBoolean("bookmarking", bookmarking);
editor.apply();
}
else{
bookmarking=true;
bookmark.setImageResource(R.drawable.ic_bookmark);
//Toast.makeText(getApplicationContext(), "Changed", Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = getSharedPreferences("SharedPreferences_Name", 0).edit();
editor.putBoolean("bookmarking", bookmarking);
editor.apply();
}
});

Button image not changing in MainActivity.onCreate

I have a mute button that mutes my app via onclick. When I return to MainActivity (where the button is) I use the savedInstanceState method to keep muted or to unmute the app (depending on what was the configuration when the user exited the activity). If the button was clicked and the app is on mute I want (when I return to MainActivity) the button to be shown as muted (I have different images for mute and unmute).
My code:
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.integer.mutecounterkeydefault);
mutecounter= sharedPref.getInt(getString(R.string.mutecounterkey), defaultValue);
mutebb = (ImageButton) findViewById(R.id.muteb);
if (mutecounter == 1) {
mutebb.setImageResource(R.mipmap.muteon);} //this if is not working
mutebb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayerPool.mute = !MediaPlayerPool.mute;
if (mutecounter == 0) {
mutebb.setImageResource(R.mipmap.muteon);
mutecounter = 1;
} else {
mutebb.setImageResource(R.mipmap.muteoff);
mutecounter = 0;
}
}
});
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.mutecounterkey), mutecounter);
editor.apply();
The solution code is
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.integer.mutecounterkeydefault);
mutecounter= sharedPref.getInt(getString(R.string.mutecounterkey), defaultValue);
mutebb = (ImageButton) findViewById(R.id.muteb);
if (mutecounter == 1) {
mutebb.setImageResource(R.mipmap.muteon);
MediaPlayerPool.mute = true;
}
mutebb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
if (mutecounter == 0) {
mutebb.setImageResource(R.mipmap.muteon);
mutecounter = 1;
MediaPlayerPool.mute = true;
editor.putInt(getString(R.string.mutecounterkey), mutecounter);
} else {
mutebb.setImageResource(R.mipmap.muteoff);
mutecounter = 0;
MediaPlayerPool.mute = false;
editor.putInt(getString(R.string.mutecounterkey), mutecounter);
}
editor.apply();
}
});
The problem is that you're saving the muteCounter before the OnClickListener is called.
Your code will set the onClickListener, then immediately save the muteCounter to whatever value is held by mutecounter at that time, which in this case will be 0 every time.
What you need to do is this:
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.integer.mutecounterkeydefault);
int mutecounter = sharedPref.getInt(getString(R.string.mutecounterkey), defaultValue);
ImageButton mutebb = (ImageButton) findViewById(R.id.muteb);
if (mutecounter == 1) {
mutebb.setImageResource(R.mipmap.muteon);
}
mutebb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayerPool.mute = !MediaPlayerPool.mute;
SharedPreferences.Editor editor = sharedPref.edit();
if (mutecounter == 0) {
mutebb.setImageResource(R.mipmap.muteon);
mutecounter = 1;
editor.putInt(getString(R.string.mutecounterkey), mutecounter);
} else {
mutebb.setImageResource(R.mipmap.muteoff);
mutecounter = 0;
editor.putInt(getString(R.string.mutecounterkey), mutecounter);
}
editor.apply();
}
});
We're setting the value to save to SharedPreferences inside the OnClickListener here, so that it will always be set when the button is tapped.
That way the next time the view is loaded, it will have the new value in SharedPreferences. The way you have it currently, you're always saving the default value to SharedPreferences, not updating it when the button is pressed.
This happens because the code inside the onClick method is executed only when the button is clicked. and the code outside the onClick method is executed immediately when the activity is created. so the changes made by onClick method will not be reflected in sharedPreference because the code for saving data in preference is not get executed when the onClick method is called.
Solution:
Put the "saving data to SharedPreferences" logic inside the onClick method like this.
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.integer.mutecounterkeydefault);
mutecounter= sharedPref.getInt(getString(R.string.mutecounterkey), defaultValue);
mutebb = (ImageButton) findViewById(R.id.muteb);
if (mutecounter == 1) {
mutebb.setImageResource(R.mipmap.muteon);} //this if is not working
mutebb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayerPool.mute = !MediaPlayerPool.mute;
if (mutecounter == 0) {
mutebb.setImageResource(R.mipmap.muteon);
mutecounter = 1;
} else {
mutebb.setImageResource(R.mipmap.muteoff);
mutecounter = 0;
}
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.mutecounterkey), mutecounter);
editor.apply();
}
});
You can create a new class Data file like:
public class DataStoreTemporary {
////////////////////////////////// INSTANCE //////////////////////////////////
private static DataStoreTemporary instance = null;
public static DataStoreTemporary getInstance() {
if (null == instance) {
synchronized (DataStoreTemporary.class) {
if (null == instance) {
instance = new DataStoreTemporary();
}
}
}
return instance;
}
//Example//
private boolean isMute = false;
public boolean isMute() {
return isMute;
}
public void setMute(boolean mute) {
isMute = mute;
}
}
And for use in your code (in Activity):
boolean mute = DataStoreTemporary.getInstance.isMute; //get information
DaraStoreTemporary.getInstance.setMute(mute); //to save the state
If you don't close the app, this should work.

SharedPreferences isn't saving my data

So in my game I'm making, I'm using SharedPreferences to save my data, however it's not saving my data or restoring it (either or both). (And yes I know getting using double.valueOf() is inefficient but that's not the problem now)
Here's my onCreate (where I get all the saved data)
public int hasPlayed = 0;
public double $money;
public int $isonmainpage = 1;
Random random = new Random();
public int $cantafford = 0;
public double $employertimer;
public double $employercounter;
public double $employeeupgrade1earnings;
public double $employeeupgrade1cost = 1;
public double $employeeupgrade1level;
public double $employerupgrade1level;
public double $employerupgrade1earnings;
public double $employerupgrade1cost = 1;
public double $allupgrades;
public String version = "0.0.1";
;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedpreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedpreferences.edit();
hasPlayed = sharedpreferences.getInt("hasPlayed", 1);
sharedpreferences.getAll();
if (hasPlayed == 1){
$money = Double.valueOf(sharedpreferences.getString("money", (Double.toString($money))));
$employercounter = Double.valueOf(sharedpreferences.getString("employercounter", (Double.toString($employercounter))));
$employerupgrade1earnings = Double.valueOf(sharedpreferences.getString("employerupgrade1earnings", (Double.toString($employerupgrade1earnings))));
$employerupgrade1level = Double.valueOf(sharedpreferences.getString("employerupgrade1level", (Double.toString($employerupgrade1level))));
$employerupgrade1cost = Double.valueOf(sharedpreferences.getString("employerupgrade1cost", (Double.toString($employerupgrade1cost))));
$employeeupgrade1level = Double.valueOf(sharedpreferences.getString("employeeupgrade1level", (Double.toString($employeeupgrade1level))));
$employeeupgrade1earnings = Double.valueOf(sharedpreferences.getString("employeeupgrade1earnings", (Double.toString($employeeupgrade1earnings))));
$employeeupgrade1cost = Double.valueOf(sharedpreferences.getString("employeeupgrade1cost", (Double.toString($employeeupgrade1cost))));
}
if (hasPlayed == 0) {
hasPlayed = 1;
editor.putInt("hasPlayed", 1);
editor.commit();
}
updatemoney();
timer();
}
And here's my onStop/onPause (when I save the data)
#Override
protected void onPause() {
super.onPause();
SharedPreferences sharedpreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("money", (Double.toString($money)));
editor.putString("employercounter", (Double.toString($employercounter)));
editor.putString("employerupgrade1earnings", (Double.toString($employerupgrade1earnings )));
editor.putString("employerupgrade1level", (Double.toString($employerupgrade1level)));
editor.putString("employerupgrade1cost", (Double.toString($employerupgrade1cost)));
editor.putString("employeeupgrade1level", (Double.toString($employeeupgrade1level)));
editor.putString("employeeupgrade1earnings", (Double.toString($employeeupgrade1earnings)));
editor.putString("employeeupgrade1cost", (Double.toString($employeeupgrade1cost)));
editor.commit();
}
#Override
protected void onStop() {
super.onStop();
SharedPreferences sharedpreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("money", (Double.toString($money)));
editor.putString("employercounter", (Double.toString($employercounter)));
editor.putString("employerupgrade1earnings", (Double.toString($employerupgrade1earnings )));
editor.putString("employerupgrade1level", (Double.toString($employerupgrade1level)));
editor.putString("employerupgrade1cost", (Double.toString($employerupgrade1cost)));
editor.putString("employeeupgrade1level", (Double.toString($employeeupgrade1level)));
editor.putString("employeeupgrade1earnings", (Double.toString($employeeupgrade1earnings)));
editor.putString("employeeupgrade1cost", (Double.toString($employeeupgrade1cost)));
editor.commit();
}
edit: im never going to learn why i'm being downvoted if i'm not told why i'm being downvoted. thanks
Replace
SharedPreferences savefile = getPreferences(MODE_PRIVATE);
with
SharedPreferences sharedpreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
and follow this link
I guess it should be because of this
hasplayed and hasPlayed, the key should be case sensitive
savefile.getInt("hasplayed", 0);
editor.putInt("hasPlayed", 1);

Categories