user3077909
user3077909

Reputation: 19

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 ?

Upvotes: 1

Views: 117

Answers (3)

christiandeange
christiandeange

Reputation: 1175

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

Upvotes: 0

Viswanath Lekshmanan
Viswanath Lekshmanan

Reputation: 10083

You should pass the Context and use

SharedPreferences prefs = Context.getSharedPreferences( "Prefs", Context.MODE_PRIVATE);

Upvotes: 1

androidcodehunter
androidcodehunter

Reputation: 21937

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

Upvotes: 0

Related Questions