The app I am developing has an activity that extends SherlockFragmentActivity. I would like to use the preferences api in order to easily add preferences to the activity. Since I would like to support api level 8 and above, I have to extend the activity from the class SherlockPreferenceActivity.
The problem is that the activity needs to show a dialog. The dialog extends SherlockDialogFragment. The show() method of the dialog needs two parameters: a FragmentManager object and a String tag.
In order to get the FragmentManager object, i used to call the getSupportFragmentManager() method of the activity. This method is missing from SherlockPreferenceActivity. I tried to use getFragmentManager() but Eclipse says that
The method show(FragmentManager, String) in the type DialogFragment is
not applicable for the arguments (FragmentManager, String)
How can I show the dialog fragment from SherlockPreferenceActivity?
You should use Shared Preferences rather than using the PreferenceActivity. Declare these references in a separate helper class rather than extending it to an Activity.This gives you the flexibility of creating a custom layout.
Example:
public class SharePrefManager {
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "selfhelppref";
//Your configurable fields
public static final String KEY_PREF1 = "pref1";
public static final String KEY_PREF2 = "pref2";
public static final String KEY_PREF3 = "pref3";
public SharePrefManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
//Setter function for configurable field
public void setPref(String key, String value){
editor.putString(key, value);
}
//Getter function for configurable field
public String getPref(String key){
return editor.getString(key);
}
}
Referencing on your activity
SharePrefManager SM = new SharePrefManager(this);
SM.setPref(SM.KEY_PREF1, "name");
String value = SM.getPref(SM.KEY_PREF1);
Try using SherlockDialogFragment.getSherlockActivity().getSupportFragmentManager().
Example:
mySherlockDialogFragment.show(mySherlockDialogFragment.getSherlockActivity().getSupportFragmentManager(), "my_tag");
Related
I have a text field for entering the to-do, a spinner where the user chooses if it's work, personal, or other and I have a date/time picker. I need to save all those using shared preferences and then populate them in a table view on the main page. I am having trouble figuring out how to save them all and send them to the different columns on the main screen.
Use the below code to save the value in SharedPreferences
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
Editor editor = pref.edit();
editor.putString("id", "iddata");
editor.commit();
Use below code retrive value from SharedPreferences
String id=pref.getString("id", null);
first of all u need to create a java class that handles your session data and use get and set methods in order to set and get data using shared preference.
public class SessionManager
{
// LogCat tag
private static String TAG = SessionManager.class.getSimpleName();
SharedPreferences pref;
Editor editor;
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "yourprefname";
private static final String KEY_IS_NAME = "isname";
private static final String KEY_IS_DATE="isdate";
private static final String KEY_IS_TIME="istime";
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setTime(String time)
{
editor.putString(KEY_IS_TIME,time);
editor.commit();
}
public String getTime()
{
return pref.getString(KEY_IS_TIME,null);
}
}
after that u need to use sessionManager class by creating object in any activity like
SessionManager session = new SessionManager(this);
//to set the values , use set method
session.setTime(time);
//to get the values, use get method
String time=Session.getTime();
I am new to android..and I'm developing an application using Json. I want to pass a string value from my main activity to another class without starting the activity class. I heard there is some way using shared preferences. I just tried.. but didn't worked..i got null point exception.. here is my code...
confirm = check.AuthenticateUser(name, passwd);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name",confirm);
editor.commit();
here is the place i want to send the value of "confirm" (string variable)
and below code shows where i want to get that preference..actually that class named "ShortList".
here is the code where i trying to get the value
public class ShortList extends Activity {
//ArrayList<HashMap<String, String>> arl;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String cargivr = preferences.getString("Name","");
please some one help me..
public static String CREDENTIALS_FILENAME = "com.myapp.credentials";
public static String PIN = "pin";
public static void writeCredentials(Context c,String pin) {
SharedPreferences credentialsPref = c.getSharedPreferences(CREDENTIALS_FILENAME, 0);
SharedPreferences.Editor editor = credentialsPref.edit();
editor.putString(PIN, pin);
editor.commit();
}
public static String readCredentials(Context c,String pin) {
SharedPreferences credentialsPref = c.getSharedPreferences(CREDENTIALS_FILENAME, 0);
SharedPreferences.Editor editor = credentialsPref.edit();
return credentialsPref.getString(PIN, "default value");
}
MainActivity.java
SharedPreferences pref = getApplicationContext().getSharedPreferences("New",Context.MODE_PRIVATE);
Editor edit = pref.edit();
edit.putString("SomeKey", "SomeValue");
edit.commit();
SecondActivity.java
SharedPreferences prefs = getApplicationContext().getSharedPreferences("New",Context.MODE_PRIVATE);
String value = prefs.getString("SomeKey","DefaultValue");
Also make sure that you have added the second activity details in your android manifest file -
<activity
android:name="com.example.projectName.SecondActivity"
android:parentActivityName="com.example.sharedpref.MainActivity">
</activity>
public class ShortList extends Activity {
//ArrayList<HashMap<String, String>> arl;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String cargivr = preferences.getString("Name","");
Here it seems you're initializing member variables.
You cannot use an Activity as a Context until onCreate() in the activity lifecycle. Member variable initialization is too early and will usually lead to NPE in getBaseContext().
Move the initialization of preferences and cargivr to onCreate() or later.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ShortList.this);
String cargivr = preferences.getString("Name","");
I've kept a static shared preference to access the values from multiple activities.
Now, I've set an alarm to go off at a certain time. Now in that Broadcast Receiver, I'm trying to access the shared pref variable.
It has already been initialized in another activity and returns the proper value there.
But in this Broadcast Receiver it doesn't give the actual value. It gives the uninitialized value.
Since it is static shouldn't the value remain same?
Here is the shared preference class.
package com.footballalarm.invincibles;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
public class SessionManagement {
// Shared Preferences
public static SharedPreferences pref;
// Editor for Shared preferences
public static Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Shared pref file name
private static final String PREF_NAME = "invincibles_alarm";
// All Shared Preferences Key
public static final String PREF_MATCH = "match";
// Constructor
public SessionManagement(Context context){
this._context = context;
pref = _context.getSharedPreferences(getPrefName(), PRIVATE_MODE);
editor = pref.edit();
editor.commit();
Log.e("Pref Match Value-constructor for pref", getValueMatch());
}
public static void fillValues(String match){
try{// Storing login value as TRUE
editor.putString(PREF_MATCH, match);
// commit changes
editor.commit();
Log.e("Pref Match Value-in fill values", getValueMatch());
}
catch(Exception e)
{Log.e("fillValues", e.toString());}
}
public static String getValueMatch(){
return pref.getString(PREF_MATCH, "Loading Match");
}
public static String getPrefName() {
return PREF_NAME;
}
}
I tried to log the output in other activities and it returns properly.
When I run the app and then close it before the alarm takes place, the program crashes with null-pointer exception since the Broadcast Receiver cannot access the shared pref.
I have tried this solution - SharedPreferences in BroadcastReceiver seems to not update? but I'm only using name in the manifest for the recievers.
This only happens if I close my app in ICS via the minimize menu.
Check this link:
Static variable loses value
Maybe static variables are loosing its value in your case .
static variables can loose value in the following cases:
1) Class is unloaded.
2) JVM shuts down.
3) The process dies.
Instead of using static variables and functions , try using a public class instead.
Hope it helps
EDIT 1:
Example code of using a public class for preferences instead of static methods
public class PreferenceForApp {
Context context;
SharedPreferences prefs;
public PreferenceForApp(Context context) {
this.context = context;
prefs = context.getSharedPreferences(AllConstants.PREFS_NAME, 0);
}
public Boolean getIsDeviceValidated() {
return prefs.getBoolean("Validated", false);
}
public void setIsDeviceValidated(Boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("Validated", value);
editor.commit();
}
}
In your code add:
PreferenceForApp myPref = new PreferenceForApp(contxt);
myPref.getIsDeviceValidated();
Useful related links:
Android static object lifecycle
Why are static variables considered evil?
Android : Static variable null on low memory
EDIT 2
TEST when is your static variable loosing value :
You can test this with a few lines of code:
print the uninitialized static in onCreate of your activity -> should print null
initialize the static. print it -> value would be non null
Hit the back button and go to home screen. Note: Home screen is another activity.
Launch your activity again -> the static variable will be non-null
Kill your application process from DDMS(stop button in the devices window).
Restart your activity -> the static will have null value.
I referred to this link Android static object lifecycle
Using shared preferences I saved data in one of the activity Now I want to use that data in another activity how to do that?
Create a sharedPreference where you want to add shared data. A little example of code like this:
SharedPreferences prefs = this.getSharedPreferences("CONSTANT_FILE_NAME",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("isPaid", true);
editor.commit();
And to retrieve that shared data use this code:
SharedPreferences prefs = this.getSharedPreferences("CONSTANT_FILE_NAME",
Context.MODE_PRIVATE);
prefs.getBoolean("isPaid",false);
Read this from developer site: click here
PREFS_NAME is the value you stored in shared preference.
public static final String PREFS_NAME = "MyPrefsFile";
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false)
Look at Restoring preferences
Edited:To use it among all classes i.e. setter getter method.Perfect use of OOPS.You can call the value from any class thats 1-line job
Make a normal class name as ReturningClass.
public class ReturningClass {
private static String MY_STRING_PREF = "mystringpref";
private static String MY_INT_PREF = "shareduserid";
public static SharedPreferences getPrefs(Context context) {
return context.getSharedPreferences("UserNameAcrossApplication", context.MODE_PRIVATE);
}
public static String getMyStringPref(Context context) {
return getPrefs(context).getString(MY_STRING_PREF, "default");
}
public static int getMyIntPref(Context context) {
return getPrefs(context).getInt(MY_INT_PREF, 0);
}
public static void setMyStringPref(Context context, String value) {
// perform validation etc..
getPrefs(context).edit().putString(MY_STRING_PREF, value).commit();
}
public static void setMyIntPref(Context context, int value) {
// perform validation etc..
getPrefs(context).edit().putInt(MY_INT_PREF, value).commit();
}
Set your value by calling
ReturningClass.setMyIntPref(mContext,22);
Once You have set your sharedPreference.Then just call this method.Just pass the context.from your class
int usersharedpreference=ReturningClass.getMyIntPref(mContext);
This link can help you.
Unable to use shared preference values in class A extends BroadcastReceiver , Android
also
http://saigeethamn.blogspot.in/2009/10/shared-preferences-android-developer.html
//decleration
SharedPreferences saveWord;
//onCreate
saveWord=PreferenceManager.getDefaultSharedPreferences(ActivityName.this);
String word=saveWord.getBoolean(PREFS_NAME, false);
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