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);
}
Related
I want to use sharedprefrence string form another activity but the value is not being passed it always passes the default value?
Creation of variable toast Shows inp value but value is not being passed
name_next = (Button) findViewById(R.id.name_next);
sp= getSharedPreferences("name_pref",Context.MODE_PRIVATE);
name_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
inp = nameInput.getText().toString();
SharedPreferences.Editor editor= sp.edit();
editor.putString(inp,nameInput);
editor.commit();
Toast.makeText(com.calmo.name.this,"welcome "+inp,Toast.LENGTH_LONG).show();
Intent intent = new Intent(name.this,MainActivity.class);
startActivity(intent);
}
});```
**Calling **
**The Value is always returned as error that is default**
``` SharedPreferences sp=getApplicationContext().getSharedPreferences("name_pref",Context.MODE_PRIVATE);
String name_in =sp.getString("inp","Error");
name.setText(name_in);
public class AppSharedPreferences {
public static final String TAG = "AppSharedPreferences";
private static SharedPreferences sharedPref;
private String demo_string = "demo string's key"
public AppSharedPreferences() {
}
public static void init(Context context)
{
if(sharedPref == null)
sharedPref = context.getSharedPreferences(
context.getPackageName(), Activity.MODE_PRIVATE);
}
public static void setDemoString(String demoString) {
Editor prefs = sharedPref.edit();
prefs.putString(demo_string, demoString);
prefs.apply();
}
public static String getDemoString() {
return sharedPref.getString(demo_string, "");
}}
Put this wherever u want to use shared prefs:
AppSharedPreferences.init(this);
You can exchange this for activity or context, depending on where you use the code.
To set value in preference, use this code:
AppSharedPreferences.setDemoString("Some Text");
To get the value from preference:
String text = AppSharedPreferences.getDemoString();
Remove
inp = nameInput.getText().toString();
under onclick
and change
editor.putString(inp,nameInput);
to
editor.putString("inp",nameInput.getText().toString());
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.
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();
}
});
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);
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();