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);
Related
I've got class to add some variables inside it.
I've created an object from it.
Then i've added some value to it.
The problem now is, i don't know how to add it inside.
SharedPreferences
i want to edit the code so i can add it without problems.
// class : MainActivity
public class MainActivity extends AppCompatActivity {
Times times;
public static Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.context = context;
times = new Times(5,30);
// setInt(times);
}
public final static String PREFS_NAME = "appname_prefs";
public static void setInt(String key, int value) {
SharedPreferences sharedPref = context.getSharedPreferences(PREFS_NAME ,0);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(key, value);
editor.apply();
}
public static int getInt(String key) {
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, context.MODE_PRIVATE);
return prefs.getInt(key , 0);
}
}
// class Times:
public class Times{
int Houre;
int Minute;
public Times(int houre, int minute){
Houre = houre;
Minute = minute;
}
public void setHoure(int houre){
Houre = houre;
}
public void setMinute(int minute){
Minute = minute;
}
public int getHoure(){
return Houre;
}
public int getMinute(){
return Minute;
}
}
Just add editor.commit(); delete editor.apply();
you can read explanation on shared prefs here
https://www.tutorialspoint.com/android/android_shared_preferences.htm
Ohad is correct. SharedPreferences only store primitive types like Int and String. In this case you would have to store each value as its own SharedPreference.
If your data is more complex than what SharedPreferences can handle, consider storing it in a Room database.
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 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);
}
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();
}
});
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();