Custom DialogPreference in Android - java

In My Project I am using SeekBarPreference. I take reference from http://android.hlidskialf.com/blog/code/android-seekbar-preference code work perfect without any error but when i fetch share Preference value in other activity. then i always found 0 why?
I use below code for get share Preference value:-
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String str=Integer.toString( prefs.getInt("duration", 0));

Using Shared preferences code for get and put the values below:
code for put the values into sharedpreferences:
public static final String PREFS_NAME = "Prefs";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_WORLD_READABLE);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("no", 11);
editor.commit();
Code for get the values from sharedpreferences:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_WORLD_READABLE);
String in=Integer.toString(settings.getInt("no", 0));

Related

sharedPreferences is not working to between two fragment?

fragment 1:
SharedPreferences sPrefs = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sPrefs.edit();
editor.putString("name", "testnameJack");
editor.commit();
fragment 2:
SharedPreferences sPrefs = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
String data= sPrefs.getString("name", "err");
emailId.setText(data);
I want transfer data to between two fragment but not working
Try:
SharedPreferences sPrefs = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
String data= sPrefs.getString("name","No name defined");
emailId.setText(data);
This isn't how it works. If you update SharedPreferences while both fragments are on screen... how would they know that the preference had changed. There are two ways to solve this easily:
1) Add an OnSharedPreferenceChangeListener to the preferences in the fragment you are attempting to update. When the listener detects a change you can alter your text. In your case fragment 2. for example:
sPrefs.registerOnSharedPreferenceChangeListener(
new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// .. Check the key to see if its the one you are looking for then set the text
}
});
Don't forget to unregister the listener to avoid leaks though.
2) Implement an interface in the parent Activity or Fragment and call a public method from the Activity in Fragment 2.
see docs
Good Luck and Happy Coding!
answer:
//Set Preference
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor;
prefsEditor = myPrefs.edit();
//strVersionName->Any value to be stored
prefsEditor.putString("STOREDVALUE", strVersionName);
prefsEditor.commit();
//Get Preferenece
SharedPreferences myPrefs;
myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String StoredValue=myPrefs.getString("STOREDVALUE", "");
Thanks everyone :)

I need to set the value of a global variable and save it even on restarting the app

So I'm developing a feature in an app where I have a boolean set to true which leads to some action being done. Now, onClick of a button will do a few related tasks and also set the boolean to false. That's fine and it works great, but once it has been changed to false, I want that on restarting the app it is assigned as false instead of true. I've tried searching for a while without any luck. Help will be appreciated.
I've only been learning Java and Android app dev for 2 months and now I'm making programs, so kindly bear with me. Maybe some sort of use of Boolean instead of boolean? I haven't got too far though.
public class Constants {
public static boolean VARIABLE = true;
}
public Fragment {
mSharedPreferencesManager.setFeatureUpdateCheck(Constants.VARIABLE);
if(mSharedPreferencesManager.getFeatureUpdateCheck())
chatUpdateNotif.setVisibility(View.VISIBLE);
else
chatUpdateNotif.setVisibility(View.GONE);
#OnClick (R.id.chat_notification_close_button)
public void onClickHideNotification() {
chatUpdateNotif.setVisibility(View.GONE);
Constants.VARIABLE = false;
Your question is very unclear.If you are trying to save a value in closing the application and getting the value back on restart try using shared preferences.
1.Save the value on click of button
SharedPreferences sharedPref = getSharedPreferences("YOUR PREF NAME", Context.MODE_PRIVATE);
sharedPref.edit().putBoolean("VALUE NAME", true).apply();
2.Restore the value from preferences on restring app
sharedPref.getBoolean("VALUE NAME", null);
Edit:If your are not using activity use context to use preference
SharedPreferences sharedPref = context.getSharedPreferences("YOUR PREF NAME", Context.MODE_PRIVATE);
Use Shared Preferences to save the boolean value when it is changed like this:
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
"DataSaved", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("VARIABLE", VARIABLE);
editor.commit();
Then in Constant write this:
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
"DataSaved", Context.MODE_PRIVATE);
VARIABLE = sharedPref.getBoolean("VARIABLE", false);
private String MY_PREFS_NAME = "sharedPref";
This sets the boolean:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putBoolean("Value", false);
editor.commit();
This gets the boolean:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
TextView textview = (TextView)findViewById(R.id.textview);
textview.setText(String.valueOf(prefs.getBoolean("Value", true)));
This textview will print out false, because the boolean has been set. If the boolean was not set it would be true (default value).

Android: SharedPreferences not getting pulled in another activity

I am currently having some trouble getting a shared preference in another activity. I currently have the following set up in my main activity:
OnCreate method:
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
String tut = preferences.getString("KEY", "");
ip = tut;
Then I have a menu to edit the preference:
SharedPreferences.Editor editor = getPreferences(
MODE_PRIVATE).edit();
String value = input.getText().toString();
editor.putString("KEY", value);
editor.commit();
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
String tut = preferences.getString("KEY", "");
ip = tut;
However when I try to receive the data in another activity in its OnCreate method it doesn't get the data:
Second Activity:
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
String tut = preferences.getString("KEY", "");
ip = tut;
Any ideas?
instead of using "getPreferences(0)" you need to set and use shared preferences with his own name, this is an example:
//Fragment Activity One
SharedPreferences prefs = getActivity().getSharedPreferences("user",0);
SharedPreferences.Editor setPrefs = prefs.edit();
setPrefs.putString("name",profile.getName());
setPrefs.putString("email",profile.getEmail());
setPrefs.putString("idFacebook",profile.getIdFacebook());
setPrefs.putString("password",profile.getPassword());
setPrefs.putString("bio",profile.getBio());
setPrefs.putInt("id",profile.getId());
setPrefs.commit();
//Fragment Activity Two
SharedPreferences prefs = getActivity().getSharedPreferences("user",0);
String name = prefs.getString("name","")
thats how i use SharedPreferences, hope it help
You are using the private version of shared preferences; how you are using it, the values can only be seen by the originating Activity. You should be using getSharedPreferences(String, int); instead. Learn more at: http://developer.android.com/guide/topics/data/data-storage.html#pref

android read/write user preferences

I am migrating iOS app to android and, thinking about iOS, I set a default plist file with strings and keys that are then modified using NSuserDefaults. I read some posts and docs and not really clear about how to do it properly in Android.
I need a preferences file with keys and strings that I could read and write. Thank you.
SharedPreferences settings;
settings = getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE);
//get the sharepref
int id = settings.getInt("ID", 0);
//set the sharedpref
Editor editor = settings.edit();
editor.putInt("ID", "1");
editor.commit();
Read Settings
public static String readSetting(Context context, String key, String defaul){
SharedPreferences preferences = context.getSharedPreferences("mySettings",MODE_PRIVATE);
return preferences.getString(key,defaul);
}
save settings-
#SuppressLint("ApplySharedPref")
public static void saveSetting(Context context, String key, String valu){
SharedPreferences preferences = context.getSharedPreferences("mySettings",MODE_PRIVATE);
SharedPreferences.Editor edit= preferences.edit();
edit.putString(key,valu);
edit.commit();
}

Need to save a high score for an Android game

It's quite simple, all I need to do is save a high score (an integer) for the game. I'm assuming the easiest way to do this would be to store it in a text file but I really have no idea how to go about doing this.
If all you need is to store an integer then SharedPreferences would be best for you to use:
//setting preferences
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putInt("key", score);
editor.commit();
To get a preference:
//getting preferences
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
int score = prefs.getInt("key", 0); //0 is the default value
Of course replace "key" with the key for your high score value and "myPrefsKey" with the key for your preferences (These can be whatever. It's just good to set them to something recognizable and unique).
I think this link will help you in it:
The SharedPreferences class provides a general framework that allows you to save and
retrieve persistent key-value pairs of primitive data types. You can use
SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings.
This data will persist across user sessions (even if your application is killed).
User Preferences
Shared preferences are not strictly for saving "user preferences," such as what ringtone
a user has chosen. If you're interested in creating user preferences for your
application, see PreferenceActivity, which provides an Activity framework for you to
create user preferences, which will be automatically persisted (using shared preferences).
To get a SharedPreferences object for your application, use one of two methods:
getSharedPreferences() - Use this if you need multiple preferences files identified
by name, which you specify with the first parameter.
getPreferences() - Use this if you need only one preferences file for your Activity.
Because this will be the only preferences file for your Activity, you don't supply a name.
To write values:
Call edit() to get a SharedPreferences.Editor.
Add values with methods such as putBoolean() and putString().
Commit the new values with commit()
To read values, use SharedPreferences methods such as getBoolean() and getString().
As I see, the best way for you to save high score is SharedPreferences.
Use shared preferences:
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
#Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
It's easiest way to store such a things.
public class HighScores extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_high);
//get text view
TextView scoreView = (TextView)findViewById(R.id.high_scores_list);
//get shared prefs
SharedPreferences scorePrefs = getSharedPreferences(PlayGame.GAME_PREFS, 0);
//get scores
String[] savedScores = scorePrefs.getString("highScores", "").split("\\|");
//build string
StringBuilder scoreBuild = new StringBuilder("");
for(String score : savedScores){
scoreBuild.append(score+"\n");
}
//display scores
scoreView.setText(scoreBuild.toString());
}
}

Categories

Resources