How to set a default value to SharedPreferences programmatically? - android

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);
}
}

Related

Android SharedPreference not working right

I'm trying to save an int I get from an EditText, and as people said it will be best with SharedPreference, I listened, but everytime i'm trying to save/load, the program crashes! any ideas?
public static final String MY_PREFS_NAME = "MyPrefsFile";
String getsturdvalue;
int sturd;
EditText sturdadapter;
int sturdadaptercount;
public void onSave(View view) {
SharedPreferences.Editor editor = (SharedPreferences.Editor) getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
editor.putInt(getstrengthvalue, strnth);
editor.apply();
}
public void onLoad(View view) {
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText= prefs.getString("text", null);
if (restoredText != null) {
int insertvalue = prefs.getInt("insertvalue", strnth);
int adapter = prefs.getInt("adapter", strengthadaptercount);
}
strengthadapter.setText(prefs.getInt("" ,strengthadaptercount));
}
It seems a ClassCastException. Try this:
public void onSave(View view) {
SharedPreferences.Editor editor = (SharedPreferences.Editor)
getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
// ...
}

how can i use share preference in counter in android?

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

Using Shared preferences to remember the font size that a user prefers in Android

I'm developing a mobile songbook android application. I have enabled text to be zoomed in or out. I want the application to be able to remember the specific font size that a user prefers when a user closes a specific song to another or even better even when a user closes the application and opens it again. Here is how i tried doing it:
public void saveFont(View view){
SharedPreferences sharedPref = getSharedPreferences("fontsize", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putFloat("fontsize",factor.getInt());
editor.apply();
}
public void rememberFont(View view){
SharedPreferences sharedPref = getSharedPreferences("fontsize", Context.MODE_PRIVATE);
double factor = sharedPref.getString("fontsize","");
factor.setInt();
}
Here is the entire class:
public class SongbookActivity extends AppCompatActivity {
private TextView wordMeaning;
private TextToSpeech convertToSpeech;
ScaleGestureDetector scaleGestureDetector;
public double factor;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dictionary);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarSongActivity);
TextView textViewTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
setSupportActionBar(toolbar);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
int dictionaryId = bundle.getInt("SONG._ID");
int id = dictionaryId + 1;
wordMeaning = (TextView)findViewById(R.id.dictionary);
String title = bundle.getString("SONG._TITLE");
String description = bundle.getString("SONG._LYRICS");
final android.support.v7.app.ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.left);
ab.setTitle(null);
ab.setDisplayHomeAsUpEnabled(true);
textViewTitle.setText(title);
textViewTitle.setSelected(true);
// textViewTitle.setMovementMethod(new ScrollingMovementMethod());
wordMeaning.setTextIsSelectable(true);
registerForContextMenu(wordMeaning);
wordMeaning.setMovementMethod(new ScrollingMovementMethod());
wordMeaning.setText(description);
scaleGestureDetector = new ScaleGestureDetector(this, new simpleOnScaleGestureListener());
}
//copy text or select
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
//user has long pressed your TextView
menu.add(0, v.getId(), 0, "Song copied to Clipboard");
//cast the received View to TextView so that you can get its text
TextView yourTextView = (TextView) v;
//place your TextView's text in clipboard
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(yourTextView.getText());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getPointerCount() > 1) {
scaleGestureDetector.onTouchEvent(event);
return true;
}
return false;
}
public void saveFont(View view){
SharedPreferences sharedPref = getSharedPreferences("fontsize", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putFloat("fontsize",factor.getInt());
editor.apply();
}
public void rememberFont(View view){
SharedPreferences sharedPref = getSharedPreferences("fontsize", Context.MODE_PRIVATE);
double factor = sharedPref.getString("fontsize","");
factor.setInt();
}
public class simpleOnScaleGestureListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector detector) {
// TODO Auto-generated method stub
float size = wordMeaning.getTextSize();
Log.d("TextSizeStart", String.valueOf(size));
float factor = detector.getScaleFactor();
Log.d("Factor", String.valueOf(factor));
float product = size*factor;
Log.d("TextSize", String.valueOf(product));
wordMeaning.setTextSize(TypedValue.COMPLEX_UNIT_PX, product);
size = wordMeaning.getTextSize();
Log.d("TextSizeEnd", String.valueOf(size));
return true;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
double factor = 1;
float size = wordMeaning.getTextSize();
saveFont(View view);
rememberFont(View view);
Log.d("TextSizeStart", String.valueOf(size));
switch (item.getItemId()) {
case R.id.small_layout:
factor = 0.5;
break;
case R.id.medium_layout:
factor = 0.9;
break;
case R.id.large_layout:
factor = 1.3;
break;
case R.id.xlarge_layout:
factor = 1.8;
break;
}
Log.d("Factor", String.valueOf(factor));
double product = size*factor;
Log.d("TextSize", String.valueOf(product));
wordMeaning.setTextSize(TypedValue.COMPLEX_UNIT_PX, (float)product);
size = wordMeaning.getTextSize();
Log.d("TextSizeEnd", String.valueOf(size));
return super.onOptionsItemSelected(item);
}
}
I'm getting errors when trying to call the method and on the method declaration. i'm a noob at this so please give me all the details you might think can help me, no matter how insignificant it can be.
here you will get all http://developer.android.com/training/basics/data-storage/shared-preferences.html
actually you storing in float with int and trying to get in string so try below
public void saveFont(View view){
SharedPreferences sharedPref = getSharedPreferences("fontsize", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("fontsize",factor.getInt());
editor.commit();
}
and from getting back
public void rememberFont(View view){
SharedPreferences sharedPref = getSharedPreferences("fontsize", Context.MODE_PRIVATE);
int prevFont = sharedPref.getInt("fontsize",-1);
}
in -1 you can set your default font
If you are having trouble with SharedPreferences, try using this. This greatly simplifies the whole process and uses SharedPreferences internally. All you have to do is copy the source file in your project and use it.
Here is an example:
In your activity's onCreate() method, initialize TinyDB.
TinyDB tinyDB = new TinyDB(this);
Then use it like this:
tinyDB.putString("fontSize", "12");
String fontSize = tinyDB.getString("fontSize");
As simple as that. There are many methods which are very useful in day to day development, just go through the source file once. Hope it helps.
Just a "light" how you can do this.
public void setVariable(float myFloat) {
pref = _context.getSharedPreferences("fontsize", Context.MODE_PRIVATE);
editor = pref.edit();
editor.putFloat("fontsize", myFloat);
editor.commit();
}
public float getVariable() {
pref = _context.getSharedPreferences("fontsize", Context.MODE_PRIVATE);
return pref.getFloat("fontsize", 5.5/*a default value*/);
}
_context can be an attribute.
EDIT1: This class works FINE for me to any 'save' issues. Change this as your need
public class SharedPreferencesManager {
// Shared Preferences
private SharedPreferences pref;
private SharedPreferences.Editor editor;
private Context _context;
// Shared pref mode
private final int PRIVATE_MODE_SHARED_PREF = 0;
// Shared preferences file name
private final String PREF_NAME = "blabla";
/*KEYS para o sharedpreferences*/
private final String KEY_TO_USE = PREF_NAME + "setFont";
public SharedPreferencesManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE_SHARED_PREF);
editor = pref.edit();
}
public void setFont(float keySize) {
editor.putFloat(KEY_TO_USE, keySize);
editor.commit();
}
public boolean getFont() {
return pref.getFloat(KEY_TO_USE, 15/*your default value is in here (in sp)*/);
}
}
To use this, just create an object (passing the context[the activity]) and use the method GET in EVERY call/inflate of your EditText/TextView, and set the size like this
myTextView.setTextSize(mSharedPreferencesManagerObject.getVariable())
And to all of this make sense, on EVERY zoom changes, you need to call
mSharedPreference.setVariable(sizeHere)
It HAS to work. If not, the problem is in your "OnZoomChange" logic/semantic.

Remember click in Android

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.

how to save some value in sharedpreferences and get that in next activity

I'm creating a Quiz App, I ask some questions and give options in the form of radio buttons, now I want to store value of of answer (plus on right answer and minus on wrong one) in SharedPreferences and show that result in other activity. I have searched and found this answer here
I used that but still I'm unable to get my desired results
My code Looks Like :
Main Activity which saves some value in SharedPreferences:
public class MainActivity extends Activity {
private SharedPreferences saveScore;
private SharedPreferences.Editor editor;
RadioGroup group;
RadioButton radioButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
group = (RadioGroup) findViewById(R.id.radioGroup1);
radioButton = (RadioButton) group.findViewById(group.getCheckedRadioButtonId());
saveScore = getPreferences(MODE_PRIVATE);
}
public void gotoNextAndSaveScore(View view) {
if(group.getCheckedRadioButtonId() != R.id.radio3){
editor = saveScore.edit();
editor.putInt("score", -1);
editor.commit();
}else{
editor = saveScore.edit();
editor.putInt("score", 1);
editor.commit();
}
Intent intent = new Intent (MainActivity.this, NextActivity.class);
startActivity(intent);
}}
this is the Next Activity which tries to get values from SharedPreferences:
public class NextActivity extends Activity{
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
preferences = this.getSharedPreferences("score", MODE_WORLD_WRITEABLE);
int value = preferences.getInt("score", 0);
String score = "Your Score is : " + value;
UIHelper.displayScore(this, R.id.tvScore, score );
}}
does any one know how to that?
You should change the line
saveScore = getPreferences(MODE_PRIVATE);
To
saveScore = getSharedPreferences("score",Context.MODE_PRIVATE);
Store the value when navigating to nextActivity during onPause() as below:
#Override
protected void onPause()
{
super.onPause();
// Store values between instances here
SharedPreferences preferences = getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("YourStringKeyValue", "StringValue"); // value to store
// Commit to storage
editor.commit();
}
and get the data with that key in next Activity's onCreate as below:
SharedPreferences preferences = getSharedPreferences("sharedPrefs", 0);
String name= preferences.getString("YourStringKeyValue","");
try this,
public class DataStorage {
private static String KEY;
public static SharedPreferences savedSession;
public void saveID(Context context, String msessionid) {
// TODO Auto-generated method stub
Editor editor = context
.getSharedPreferences(KEY, Activity.MODE_PRIVATE).edit();
editor.putString("SESSION_UID", msessionid);
editor.commit();
}
public String getID(Context context) {
savedSession = context.getSharedPreferences(KEY, Activity.MODE_PRIVATE);
return savedSession.getString("SESSION_UID", "");
}
}
Edit:
DataStorage mdata = new DataStorage();
public void gotoNextAndSaveScore(View view) {
if(group.getCheckedRadioButtonId() != R.id.radio3){
mdata.saveId(Mainactivity.this,1);
}else{
mdata.saveId(Mainactivity.this,-1);
}
And then get value from NextActivity.
DataStorage mdata = new DataStorage();
mdata.getId(NextActivity.this);
You're using the wrong preference file, the getPreference function on Activity returns a file private to that Activity. You need to use the named file version- getSharedPreferences(name, mode)

Categories

Resources