I made one class with name session and i maintain my all shared preferences from there only like..
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
}
Now from UI application i call this session and my all variable didnt get there default value like..
public void setIsFirsTimeCall(boolean IsFirsTimeCall) {
prefs.edit().putBoolean("IsFirsTimeCall", IsFirsTimeCall).commit();
prefsCommit();
}
public boolean getIsFirsTimeCall() {
return prefs.getBoolean("IsFirsTimeCall", true);
}
so when i call for getIsFirsTimeCall() then it will give false to me
I don't know why it is doing this
But when i copy and share this project to other PC then its work fine
Have you ever seem this type of behavior
I don't know if this can help you to solve:
I think you can do something like this:
public static void setIsFirsTimeCall(Context cntx, boolean IsFirsTimeCall) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
prefs.edit().putBoolean("IsFirsTimeCall", IsFirsTimeCall).commit();
prefsCommit();
}
public static boolean getIsFirsTimeCall(Context cntx) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
return prefs.getBoolean("IsFirsTimeCall", true);
}
I've moved the declaration and definition of prefs from the constructor of Session class, inside each method that require it. Each of this methods is static, so you can call them from outside the Session class in this way: Session.getIsFirsTimeCall(yourContext) and so on.
Maybe you have to change the behavior of your code because I don't know if your method prefsCommit() can become static, otherwise you can't call it from a static method.
Hope it will help you
Related
The following method was working, but now it is not writing my integer into file.
public void writeChpNum(int num) {
SharedPreferences prefs = context.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
prefs.edit().putInt("chapter", num).apply();
}
and this is how I get from Main class:
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
chapterNum = prefs.getInt("chapter", 1);
Method did not work in this situation:
writeChpNum(1);
writeLastLine("0");
boolean deleted = file.delete();
boolean deleted2 = file2.delete();
boolean deleted3 = file3.delete();
boolean deleted4 = last.delete();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
Here, I want to restart everything and exit, so I am removing files, but for chapters I just have to write "1"-chapter. However, it did not write.
Is this because I am exiting the app?
Context object will not be available in other Activities when you access it like that. Try passing it context in method as well if you want to write this method to only one class. make method static so you don't need to create activity object.
Edit
Based on your new code for exiting app you need commit() instead of apply()
Ref: https://developer.android.com/reference/android/content/SharedPreferences.Editor.html#apply()
public static void writeChpNum(Context c, int num) {
SharedPreferences prefs = c.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
prefs.edit().putInt("chapter", num).commit() ;
}
Please read carefully because it is a little bit complicated!
I have a service that call many functions every 5 second. Now I want to call one specific fucntion in those functions just 1 time only. So I make this to check if that function has called before.
private void checkFirstLaunchApp() {
final String HAS_RUN_BEFORE = "hasRunBefore";
final String HAS_RUN = "hasRun";
SharedPreferences runCheck = getSharedPreferences(HAS_RUN_BEFORE, 0);
Boolean hasRun = runCheck.getBoolean(HAS_RUN, false);
if (!hasRun) {
SharedPreferences settings = getSharedPreferences(HAS_RUN_BEFORE, 0);
SharedPreferences.Editor edit = settings.edit();
edit.putBoolean(HAS_RUN, true); //set to has run
edit.apply(); //apply
//do that function
functionIWant();
}
} else {
//do nothing
}
}
But the problem is if I close my app and reopen it,that function will not be called anymore. What I want is when I reopen my app, that function will be called 1 time again.Please show me how can I do that?
you have to reset HAS_RUN to false inside onStart() of your launcher activity.
Alternate
Extend Application class and create global variable:
public class MyApplication extends Application{
public boolean hasRun;
public void onCreate (){
hasRun=false;
}
}
Get instance of MyApplication
MyApplication app=(MyApplication)getApplication();
if(!app.hasRun){
app.hasRun=true;
// do your stuff
}
Handle it in the onResume method
Use global variable instead of SharedPreferences
A field variable is fine, sharedpreferences is not suitable for this case.
private boolean mIsCalled;
...
private void functionIWant() {
if (mIsCalled) return;
mIsCalled = ture;
// your function body
}
Set SharedPreference to false in onStop() method :
SharedPreferences settings = getSharedPreferences(HAS_RUN_BEFORE, 0);
SharedPreferences.Editor edit = settings.edit();
edit.putBoolean(HAS_RUN, true); //set to has run
edit.apply(); //apply
Call your method in onResume() method :
checkFirstLaunchApp()
I am using defaultSharedPreferences() throughout my application. I define it once in my Application class and use it whenever needed:
public class Itu extends Application {
public static SharedPreferences sharedPreferencesFDefault;
#Override
public void onCreate() {
sharedPreferencesFDefault = PreferenceManager.getDefaultSharedPreferences(this);
}
public static SharedPreferences getSharedPreferencesItu(){
return sharedPreferencesFDefault;
}
public static int getStudentNameColor(SharedPreferences sharedPref){
int color = sharedPref.getInt("studentNameColor", -1);
if (color == -1) {
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("studentNameColor", 0);
editor.commit();
color = sharedPref.getInt("studentNameColor", 0);
}
....
return color;
}
I use it in this Activity:
public class StudentAddActivity extends ActionBarActivity {
...
private void attemptAdd() {
SharedPreferences sharedPref=((Itu)getApplication()).getSharedPreferencesItu();
int color=Itu.getStudentNameColor(sharedPref);
}
Now i want to delete all values from my another activity which does not work:
public class CourseListActivity extends ActionBarActivity{
public static SharedPreferences sharedPreferencesFDefault;
...
sharedPreferencesFDefault = ((Itu) getApplication()).getSharedPreferencesItu();
sharedPreferencesFDefault.edit().clear().commit();
}
After i call sharedPreferencesFDefault.edit().clear().commit();, i still see that my "studentNameColor" value exists in defaultSharedPreferences.
What might be problem? Using defaultSharedPreferences instead of sharedPreference? or passing Application context instead of each activity's context? or i call wrong function to delete?
UPDATE 1: i can delete it from my Application class, but not from my Activities. why?
UPDATE 2: i can delete now it from another activity by accessing variable directly:
((Itu) getApplication()).sharedPreferencesFDefault.edit().clear().commit();
But if i get sharedPreference variable through my static function, i can not clear it, why?
I have changed public static SharedPreferences sharedPreferencesFDefault; to public SharedPreferences sharedPreferencesFDefault; and now clear() works. The thing was getting static sharedPreference, from Application class, into static variable of Activity class.
I still don't know what happens when we initialize static variable with another static variable. You can follow that question here.
I have an application where I'm setting roughly around 200 shared preferences when the application is run for the first time. I was initially loading all the preferences by calling it from my onCreate method
SharedPreferences pref = getSharedPreferences(CALC_PREFS, MODE_PRIVATE);
settingsEditor = prefs.edit();
settingsEditor.putString("Something", "");
....
settingsEditor.commit();
and it would work well and rather quickly. I then redesigned my application to have an abstract activity class to handle all the work with the shared preferences becacuse I have 4 different activities accessing these preferences.
public abstract class AnActivity extends Activity{
// Shared Preference string
private static final String CALC_PREFS = "CalculatorPrefs";
// Editor to customize preferences
private Editor settingsEditor;
// Shared preference
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
prefs = getSharedPreferences(CALC_PREFS, MODE_PRIVATE);
settingsEditor = prefs.edit();
}
protected void addPref(String key, String value){
settingsEditor.putString(key, value).commit();
}
protected void addPref(String key, int value){
settingsEditor.putInt(key, value).commit();
}
//other methods were not posted
}
My main activity not extends the "AnActivity" class. However, when I run my application on a fresh install or attemp to access any shared preference, it takes upwards of 10 seconds to instantiate everything.
How can I set the default values in a clean and efficient manner? Does creating an Abstract class to handle the preferences create more overhead than just calling getSharedPreferences manually?
Are you commiting each time you add a preference? This is probably your issue, commiting for each entry could be quite expensive, batch together your put's and commit once.
If you don't need to specify the default value, you could always use clear() instead
http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#clear%28%29
I have a problem with SharedPrefences and initializations.
My application has a login where you insert an user, and for that user, you have a specific preferences... so, I need to save preferences according to the user to load it later.
I though that SharedPrefences would be the solution, and it really is I think, but I have a problem to initialize they: I have an Activity class called Options. It has static functions that returns the value of the options... but I have a problem, I call that functions before I have create that activity (intent), so I think that the functions are returning the last value that the last user has selected on the options...
How can I load the options before that calls?
I though to use first of all an Intent sending extra data with the user and in onCreate() of the Options, initialize they, but if I make an intent, then the Options will appear (xml will load).
Any help pls?
Try something like this.... adding methods for each variable you want to save.
public class PreferenceManager {
private static PreferenceManager self;
private SharedPreferences preferences = null;
private SharedPreferences.Editor editor = null;
private boolean isInitialised = false;
private static final String MY_PREFERENCE = "mypreferencekey";
private String myPreference = null;
public void initialise(Context context) {
if (!isInitialised) {
preferences = context.getSharedPreferences("MyPreferencePlace", Context.MODE_PRIVATE);
editor = preferences.edit();
loadPreferences();
isInitialised = true;
}
}
public static PreferenceManager getInstance() {
if (self == null) {
self = new PreferenceManager();
}
return self;
}
private PreferenceManager() {
}
public void setPreference(String newPreferenceValue) {
this.myPreference = newPreferenceValue;
savePreferences();
}
public String getPreference(){
return myPreference;
}
private void savePreferences() {
editor.putString(MY_PREFERENCE, myPreference);
editor.commit();
}
private void loadPreferences() {
myPreference = preferences.getString(MY_PREFERENCE, null);
}
}
All the SharedPreferences need is a context and it can be initialized. As your application always opens an Activity to start with, you always have a context to work with.
I would advise you to wrap the SharedPreferences in a Singleton class and just pass a context as parameter at the getInstance method. You should be able to access your shared preferences at all Activities this way.
I work on the dependency injector for android, and content of shared preferences is already injectable into annotated fields ( see: https://github.com/ko5tik/andject , PreferenceInjector). Patches and improvements are welcome. Saving of preferences comes soon