Context needed for SharedPreferences - android

I am using SharedPreferences in my asynctask but because of this the following line of code does not work:
SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
But if I remove the 'this.' it throws me this error:
09-04 10:16:49.184: E/AndroidRuntime(1883): at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:161)
Also, it is being called from a service if that complicates things anymore? So how do I provide proper context to this SharedPreferences?

You can set a parameter in the AsyncTask Constructor, that will be the base context, like it:
public class X extends AsyncTask {
private Context context;
public X(Context context) {
this.context = context;
}
#Override
doInBackground() {
SharedPreferences prefs = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
// your code
}
Hugs.

Declare it globally in class which extends Activity
public static SharedPreferences prefs;
pref=PreferenceManager.getDefaultSharedPreferences(getBaseContext());
Now u can use pref as per your need.

Related

Unable to Initialize SharedPreferences

I have a class A this class does not extend or implement any other classes. I then have an Class B, this class also does not extend or implement any other classes.
My Class B is solely used to manage SharedPreferences :
private static SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
Here is the problem method in Class B:
public static void setCurrentUsersEmail(String email){
sharedPreferences.edit().putString("userEmail",email).commit();
}
Now class A is a database manager and needs to store the users email in SharedPreferences for later use. I do this with the following code:`
MySharedPrefs.setCurrentUsersEmail(currentUsersEmail);
However, when i try run the code in Class A i get the error:
java.lang.ExceptionInInitializerError
at com.test.Android.MySharedPrefs.setCurrentUsersEmail(MySharedPrefs.java:0)
I am really confused as to why this happens I couldn't find a solution online after searching either, I use my sharedPreferences class in other activities perfectly fine. Is it an activity problem?
Any help is much appreciated.
You can use singleton for your requirement :
public class MyPrefs {
private static MyPrefs myPrefs;
private SharedPreferences sharedPreferences;
private MyPrefs(Context context){
sharedPreferences=context.getSharedPreferences("MyPREFERENCES", Context.MODE_PRIVATE);
}
public static MyPrefs getInstance(Context context){
if(myPrefs==null)
myPrefs=new MyPrefs(context);
return myPrefs;
}
public void setCurrentUsersEmail(String email){
sharedPreferences.edit().putString("userEmail",email).commit();
}
}
You can put email in this way :
MyPrefs.getInstance(context).setCurrentUsersEmail(currentUsersEmail);
You need to pass context at first time for the reference of sharedPreferences in your Class.
or
From Activity call MyPrefs.getInstance(context) at once
Then you can call without context
MyPrefs.getInstance().setCurrentUsersEmail(currentUsersEmail);
getInstance() method :
public static MyPrefs getInstance(){
if(myPrefs==null) throw new AssertionError("MyPrefs cannot be null");
else
return myPrefs;
}
You could do this , in any activity, dont need to create a new method:
To save:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("email", "YOURUSEREMAIL#.email");
editor.commit();
To restore:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("email", null);
You cant call MyPrefs.aFunctionYouCreated() !!!

Android - Access SharedPreferences once application is stopped/destroyed

I implementing notifications together with a periodical alarm and on IntentService i need to validate some values on SharedPreferences to decide if I will show a notifications or not.
When the application is on pause i have context, and everything goes ok, the problem comes when i destroy(remove from "recent apps" list) my application.
In this case, the alarm is still running (which is ok), but when it tries to load my shared preferences gives me NullPointerException.
IntentService:
public class MyIntentService extends IntentService {
private final PreferencesManager prefs;
public SchedulingService() {
super("MyIntentService");
prefs = PreferencesManager.getInstance(this); //Error here
}
#Override
protected void onHandleIntent(Intent intent) {
// Do some checking with prefs variable ...
}
}
SharedPreferences
public class PreferencesManager {
public static final String SHARED_PREFERENCES_NAME = "PREFERENCES_PROJECT";
private static PreferencesManager preferencesManager = null;
private SharedPreferences sharedPreferences;
private PreferencesManager(Context context) {
sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
}
public static PreferencesManager getInstance(Context context) {
if (preferencesManager == null) {
preferencesManager = new PreferencesManager(context);
}
return preferencesManager;
}
//....
}
How can retrieve the values from my PreferencesManager when the application is not running?
Move your prefs = PreferencesManager.getInstance(this) line to onHandleIntent(), or into an onCreate() method after the super.onCreate() call.
why dont i have context on constructor?
You do have a Context. It is not fully initialized yet. Never attempt to use a Context before the inherited onCreate() of the relevant component has completed. In this case, the component is a Service, so once super.onCreate() is over, then it is safe to use the Service to retrieve a SharedPreferences object.

SharedPreferences produces force close in android program

I'm building an android project that contains SharedPreferences.
My SharedPreferences works fine and I tested it in mutiple activity. but in a class that I defined for global variables, defining that SharedPreferences will cause force close (eclipse didn't show any error in codes).
public class Globals extends Application {
final SharedPreferences s = getSharedPreferences("Prefs", MODE_PRIVATE);
}
What is the problem ?
You should pass the Context and use
SharedPreferences prefs = Context.getSharedPreferences(
"Prefs", Context.MODE_PRIVATE);
Create a constructor and pass a Context variable as a parameter. Any activity that want to use this preference then you have to pass the activity. Here's the code given below:
public class Globals extends Application {
private Context context;
public Globals (Context context) {
this.context = context;
}
SharedPreferences myPref = context.getSharedPreferences("Prefs", Context.MODE_PRIVATE);
}
You can't run getSharedPreferences() in the actual class. Everything you do must be in the Application's onCreate method. If you try to run this in the class, it will fail since it has not been initialized yet. Think of it almost as an activity, since both the activity and the application have a lifecycle.
Try the following:
public class Globals extends Application {
#Override
public void onCreate() {
super.onCreate();
final SharedPreferences s = getSharedPreferences("Prefs", MODE_PRIVATE);
}
}

Using getSharedPreferences android?

This is the save() method in my app:
public void save() {
Context context;
SharedPreferences sp = context.getSharedPreferences("gameSave",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("X", player.getX());
editor.putInt("Y", player.getY());
editor.putInt("level", player.getLevel());
editor.putFloat("xp", player.getXp());
editor.commit();
}
I have been trying to get this to work for a while now, but the getSharedPreferences (String name, int mode) has not been working for me. It doesn't come up on it's own, context.getSharedPreferences() works, but that yields a NullPointerException, I think because of my context. I have tried save(Context context){} as a constructor, but calling that from another method with context declared inside of that method does not work either. I've looked at many examples, but none of them have worked for me. So how can I get getSharedPreferences() to work?
EDIT: I have a class GameScreen and a class SaveManager. When I save in Gamescreen this is the code I use:
Savemanager savemanager;
savemanager.save();
state = GameState.Running;
And I have my class SaveManager:
package com.package.game;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
public class SaveManager extends Activity {
private Player player = GameScreen.getPlayer();
public void save() {
SharedPreferences sp = getSharedPreferences("gameSave",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("X", player.getX());
editor.putInt("Y", player.getY());
editor.putInt("level", player.getLevel());
editor.putFloat("xp", player.getXp());
}
}
And when I save in GameScreen my app crashes and I get this logcat:
02-20 01:39:31.979: E/AndroidRuntime(1368): FATAL EXCEPTION: Thread-119
02-20 01:39:31.979: E/AndroidRuntime(1368): java.lang.NullPointerException
02-20 01:39:31.979: E/AndroidRuntime(1368): at com.package.game.GameScreen.updateLevelUp(GameScreen.java:364)
Line 364 is the line savemanager.save();. I have no idea why this crashes my app.
getSharedPreferences() is a Context method. If save() is in a class that extends Context, such as Activity, you don't have to do context.getSharedPreferences(), so you can do, as you put it "the method by itself".
However, if save isn't in a class that extends Context, for it to be able to call getSharedPreferences(), it needs to have a Context variable passed off. This means that what you were doing by simply making a context variable isn't enough (and that code shouldn't compile, there would be an error thrown about how the context variable hasn't been initialized). And since Contexts aren't made using a constructor, your method hits a dead end.
However, you are close. For the sake of explanation, you can make a static method that accepts in a Context and does the saving. static since this method really shouldn't need an object instance, it can be self-contained:
public static void save(Context context) {
if (context == null)
throw new RuntimeException ("Context is null, what are you doing?");
SharedPreferences sp = context.getSharedPreferences("gameSave",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("X", player.getX());
editor.putInt("Y", player.getY());
editor.putInt("level", player.getLevel());
editor.putFloat("xp", player.getXp());
editor.commit();
}
Now if this method was part of a class for example named StaticUtils, you can call save:
Through an Activity: StaticUtils.save(YourActivityClass.this); or StaticUtils.save(this); depending on the scope (eg if inside an anonymous inner function, you'd use YourActivityClass.this).
Fragment: StaticUtils.save(getActivity());
BroadcastReceiver: StaticUtils.save(context);
A View (eg the View passed on when onClick() is called: StaticUtils.save(v.getContext());
Just keep in mind that the earilest you can do saving in an Activity is onCreate() anything before will fail and the Exception should clearly indicate that.
A simple demo. No extending anything, no fancy making of Context:
MainActivity.java:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StaticUtils.save(this);
SharedPreferences prefs = getSharedPreferences ("gameSave", Context.MODE_PRIVATE);
System.out.println ("X is " + prefs.getInt ("X",-1));
}
}
StaticUtils.java
public class StaticUtils {
public static void save(Context context) {
if (context == null)
throw new RuntimeException ("Context is null, what are you doing?");
SharedPreferences sp = context.getSharedPreferences("gameSave",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("X", 11);
editor.putInt("Y", 24);
editor.putInt("level", 3);
editor.putFloat("xp", 100);
editor.commit();
}
}

How to use shared preference data in different classes in android?

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

Categories

Resources