I'm new to android, and I'm stuck right now.
I'm building an android app.
I have a textview with int value
final int intbut = 40;
hp.setText(String.valueOf(intbut));
I have a button, when clicking on it it add +1, +0 or -1 to the value.
public void onClick(DialogInterface dialog, int which) {
if(answer.getHp() == 1){
hp.setText(String.valueOf(intbut + 1));
Log.i("GameActivity", "json " + answer.getHp());
}
But at the click of the button it also reload the activity so the new value is not saved, how can I save the changed value ?
One option would be using Shared preferences, to save the desired value and retrieve it in any point of your application.
as an example this are create methods to save and retrieve and integer value:
private String PREFS_KEY = "mypreferences";
public void saveValuePref(Context context, int value) {
SharedPreferences settings = context.getSharedPreferences(PREFS_KEY, MODE_PRIVATE);
SharedPreferences.Editor editor;
editor = settings.edit();
editor.putInt("myValue", value);
editor.commit();
}
public int getValuePref(Context context) {
SharedPreferences preferences = context.getSharedPreferences(PREFS_KEY, MODE_PRIVATE);
return preferences.getInt("myValue", 0);
}
To save the value use:
saveValuePref(getApplicationContext, intbut);
to retrieve the value use:
int intbut = getValuePref(getApplicationContext);
Related
Here's the problem. In my second class, I'm trying to load the SharedPreferences. Below I'll also include my first class.
//set label for journal questions
public TextView journalQuestionLabel;
public int counter = 0;
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_journal);
//TODO: Send saved preferences here
preferences = getSharedPreferences("grammarOption", MODE_PRIVATE);
int selection = preferences.getInt("grammarOption", -1);
Log.d("in onCreate", "preferences = " + selection);
}
When I test it, my debug log always prints -1. It won't load my shared preferences. What am I doing wrong?
I've tried the other answers on here and every tutorial, but they aren't working. Here is my code to set up and save my spinner preferences. I've checked this and it's working.
private void setupSpinner() {
// Create adapter for spinner. The list options are from the String array it will use
// the spinner will use the default layout
final ArrayAdapter grammarSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.array_grammar_options,
android.R.layout.simple_spinner_dropdown_item);
// Specify dropdown layout style - simple list view with 1 item per line
grammarSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
//Apply the adapter to the spinner
grammarChoiceSpinner.setAdapter(grammarSpinnerAdapter);
//Create shared preferences to store the spinner selection
SharedPreferences preferences = getApplicationContext().getSharedPreferences
("Selection", MODE_PRIVATE);
editor = preferences.edit();
// Create the intent to save the position
grammarChoiceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//receive the string of the option and store it
int grammarOptionPosition = grammarChoiceSpinner.getSelectedItemPosition();
//put the string in the editor
editor.putInt("grammarOption", grammarOptionPosition);
editor.commit();
//make a toast so the user knows if it's not "select"
if (grammarOptionPosition != 0) {
Toast.makeText(getApplicationContext(), "Choice saved.",
Toast.LENGTH_SHORT).show();
}
}
// Because AdapterView is an abstract class, onNothingSelected must be defined
#Override
public void onNothingSelected(AdapterView<?> parent) {
mGrammar = 0;
}
});
}
Here it's called in onCreate()
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_opening);
//find the spinner to read user input
grammarChoiceSpinner = (Spinner) findViewById(R.id.spinner);
setupSpinner();
You are passing wrong String in getSharedPreferences(String, int).
preferences = getSharedPreferences("Selection", MODE_PRIVATE);
int selection = preferences.getInt("grammarOption", -1);
Log.d("in onCreate", "preferences = " + selection);
Give this a try.
I hope it helps.
Make sure your SharedPreference key is same in both the class or even throughout the whole App.
While saving do like -
SharedPreferences preferences = getSharedPreferences("MY_PREFS", MODE_PRIVATE);
preferences.edit().putInt("grammerOption", 1).apply();
While Getting data from prefs do like -
SharedPreferences preferences = getSharedPreferences("MY_PREFS", MODE_PRIVATE);
int option = preference.getInt("grammerOption", -1);
PS,
Key for preference(which is MY_PREFS here) must be the same.
Excuse me because 3 of my simple question, but I need your help. I want to have a counter (with using shared preference) in my app like this:
At the first, there are 2 buttons, START and RESET. If RESET is
clicked, the counter starts from 0.
Also if START is clicked, the counter starts from shared preference data.
Start counting
At last time, I want to save counter in share preference. (but I don't know its better to save it in BACK btn or CLICK btn)
My problem is in share preference part. Please help me how can I do this? Thanks a lot!
Edit: this is my code
public class CountActivity extends Activity {
private Button click;
private int count,savedCount;
private String count_text;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.counting);
click= (Button) findViewById(R.id.vow_counting);
final Typeface typeface = Typeface.createFromAsset(getAssets(),"fonts/Far_Homa.ttf");
final SharedPreferences sharedPreferences=getSharedPreferences("counters", Context.MODE_PRIVATE);
final SharedPreferences.Editor editor=sharedPreferences.edit();
AlertDialog.Builder fBuilder=new AlertDialog.Builder(VowCountActivity.this);
fBuilder.setMessage("please choose");
fBuilder.setCancelable(false);
fBuilder.setPositiveButton("start from beging", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
count = sharedPreferences.getInt("counter", 0);
click.setText("0");
click.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/Far_Homa.ttf"));
dialogInterface.cancel();
}
});
fBuilder.setNegativeButton("countinue", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
count = sharedPreferences.getInt("counter",savedCount);
editor.putInt("counter",savedCount).commit();
dialogInterface.cancel();
}
});
fBuilder.show();
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
count++;
count_text=Integer.toString(count);
click.setText(count_text);
click.setTypeface(typeface);
savedCount = sharedPreferences.getInt("savedCounter", count);
vibrate(500);
}
});
}
// vibrate
public void vibrate(int duration) {
Vibrator vibs = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibs.vibrate(duration);
}
To get value on start button you can define this function and have value for shared preferences
public static int getIntPreferences(String key) {
SharedPreferences settings = context.getSharedPreferences(SP_FILE_NAME, 0);
return settings.getInt(key, 0);
}
Now to reset your shared preferences value you can use the following function
public static void updatePreferences(String key, int value) {
SharedPreferences settings = context.getSharedPreferences(SP_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putInt(key, value);
editor.commit();
}
Use
SharedPreferences preferences = getSharedPreferences("PROFILE", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = preferences.edit();
edit.putString("yourPreferenceName", yourPreferenceObject);
edit.commit();
for saving preference
and
SharedPreferences preferences = this.getSharedPreferences("PROFILE", Context.MODE_PRIVATE);
String string = preferences.getString("yourPreferenceName", "defaultReturn");
for receiving your sharedPreferences
.get and .put with return type
Try this:
SharedPreferences preferences = getSharedPreferences("counterStat", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = preferences.edit();
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int counter = preferences.getInt("counter", 0);
// counter = counter + 1; start counting
edit.putInt("counter", counter).commit();
}
});
btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edit.putInt("counter", 0).commit();
}
});
Dialog back:
int counter = preferences.getInt("counter", 0);
edit.putInt("savedCounter", counter).commit();
Dialog cancel:
int counter = preferences.getInt("counter", 0);
edit.putInt("savedCounter", counter).commit();
edit.putInt("counter", 0).commit();
Then you can use: int savedCounter = preferences.getInt("savedCounter", 0); anywhere
Here is how to add an entry to SharedPrefs, and save to disk.
SharedPreferences settings = getSharedPreferences("my_prefs", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", "Adam");
editor.commit();
Here is how to read a saved value from SharedPrefs.
SharedPreferences settings = getSharedPreferences("my_prefs", 0);
String name = settings.getString("name", null);
I am using SharedPreferences to keep the information about user's weight, which I need in my application. The problem is, how to set a default value (eg. 75 kg) automatically after installation? I know how to do it via .xml, but how to do this programmatically?
My code:
public class SettingsDialogFragment extends DialogFragment{
public static final String PREFS_NAME = "settings";
public Dialog onCreateDialog(Bundle savedInstanceState) {
builder.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Data.weight = weight;
SharedPreferences prefs = getActivity().getSharedPreferences(PREFS_NAME, 0);
Editor editor = prefs.edit();
editor.putInt("key_weight", weight);
editor.commit();
Data.ifMale = ifMale;
checkedRadio = rg.getCheckedRadioButtonId();
System.out.println("numer radio" +checkedRadio);
}
});
return builder.create();
}
}
Try this way, please.
SharedPreferences prefs = getActivity().getSharedPreferences(
PREFS_NAME, 0);
if (prefs.getInt("key_weight", null) == null) {
Editor editor = prefs.edit();
editor.putInt("key_weight", 75);
editor.commit();
}
For first time use this, or else use your code only(means without if condition).
getInt takes a default value.
prefs.getInt("key_weight", 75)
Or in a more mainstream style....
public class AppPreferences {
private SharedPreferences mPreferences;
Public AppPreferences(SharedPreferences preferences)
{
this.mPreferences = preferences;
}
private static final String KEY_WEIGHT_KEY = "key_weight";
private static final int DEFAULT_KEY_WEIGHT = 75;
public static int getKeyWeight()
{
return mPreferences.getInt(KEY_WEIGHT_KEY,DEFAULT_KEY_WEIGHT);
}
}
I have created an activity that should be displayed only once. In this Activity, I added a button, and click its close and will not reopen anymore when the application is started again. I thought of using SharedPreferences, but I do not get the desired result.
I memorize a data in Shared:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
SharedPreferences userDetails = getSharedPreferences("entrato", MODE_PRIVATE);
Editor edit = userDetails.edit();
edit.clear();
edit.putString( "entrato", "entra" );
edit.commit();
this.finish();
break;
}
}
then, in OnCreate() of the previous activity call the Shared and if the data is present do not open the activity:
//remember click
SharedPreferences userDetails = getSharedPreferences("entrato", MODE_PRIVATE);
String valore = userDetails.getString("entrato", "");
if (valore.equals("entra")){
return;
}else{
Intent intent = null;
intent = new Intent(this, Benvenuto.class);
startActivity(intent);
create share preference class like this:
public class MyPreference {
private static final String APP_SHARED_PREFS = "myPref";
private SharedPreferences appSharedPrefs;
private Editor prefsEditor;
public MyPreference(Context context) {
this.appSharedPrefs = context.getSharedPreferences(APP_SHARED_PREFS, Activity.MODE_PRIVATE);
this.prefsEditor = appSharedPrefs.edit();
}
public boolean loadServices(String servicName) {
return appSharedPrefs.getBoolean(servicName, false);
}
public void saveServices(String servicName, boolean isActivated) {
prefsEditor.putBoolean(servicName, isActivated);
prefsEditor.commit();
}
}
then On Oncreate activity check if service exist so wont show and exit.
public static MyPreference myPref = new MyPreference(this);
if(myPref.loadService("this is not first time")){
thisActivity.finish();
}else {
// so it's first time and you can do what ever you want to do
}
and go on you click events and save service like this.
public static MyPreference myPref = new MyPreference(this);
myPref.saveService("this is not first time");
Try this code instead
// save string
static public boolean setPreference(Context c, String value, String key) {
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, 0);
settings = c.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
return editor.commit();
}
// retrieve String
static public String getPreference(Context c, String key) {
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, 0);
settings = c.getSharedPreferences(PREFS_NAME, 0);
String value = settings.getString(key, "");
return value;
}
I have Four activities
Splash
Have 2 Buttons And 1 CheckBox ( Remember Me)
3 & 4. Another Activity
If I check the remember me option using checkbox, then I have to remember the button I have clicked and then start the 3rd or 4th activity directly whenever next start.
I have following code in settings.java:
public static int numberOfQuestions = 0;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
pref = getSharedPreferences(Constants.PREF_SETTINGS, 0);
final RadioGroup rg_numberOfQuestions = (RadioGroup) findViewById(R.id.radioGroupQuestions);
rg_numberOfQuestions.setOnCheckedChangeListener(this);
RadioButton rbtn = ((RadioButton) rg_numberOfQuestions.findViewById(pref.getInt("NQ", 0)));
if(rbtn!=null)
rbtn.setChecked(true);
}
public void onCheckedChanged(RadioGroup rg, int i) {
switch (rg.getCheckedRadioButtonId())
{
case R.id.rb_0to10:
numbersBetween = 10;
break;
case R.id.rb_0to25:
numbersBetween = 25;
break;
case R.id.rb_0to50:
numbersBetween = 50;
break;
}
if(rg.getCheckedRadioButtonId() == R.id.rb_0to10 || rg.getCheckedRadioButtonId() == R.id.rb_0to25 || rg.getCheckedRadioButtonId() == R.id.rb_0to50)
{
savePref("NB", rg.getCheckedRadioButtonId());
}
}
This is code to save and access preference:
private void savePref(String key, int value) {
pref = getSharedPreferences(Constants.PREF_SETTINGS, 0);
editor = pref.edit();
editor.putInt(key, value);
editor.commit();
}
private void savePref(String key, Boolean value) {
pref = getSharedPreferences(Constants.PREF_SETTINGS, 0);
editor = pref.edit();
editor.putBoolean(key, value);
editor.commit();
}
}
If i am in settings numberOfQuestions variable gets updated and it works fine in my other view called main.java. But lets say i open main.java directly and not open setting first numberOfQuestions does not have right value. Is there easier way to transfer shared preference value to other view? Or do i need to write all cases in main.java also?
You don't need to do anything special, you can use the same shared preferences from each part of your app in the same way.
You can move the methods to access shared preferences to:
a parent class for all your activities
a static methods in a helper class (you would have to pass context as parameter in this case and be careful not to create a reference to this context to avoid memory leaks).
You can use
numberOfQuestions = getSharedPreferences(Constants.NUM_OF_QUESTIONS, 0);
to initialize its value. then access it anywhere in your application