0

Hi i am trying to solve this from quite sometime but not able to success

I am trying to initialize the variables in content provider as below

public static String rb_radio ;
    public static String im_radio ;
    static {
        rb_radio = context.getResources().getString(R.string.kgs);
        im_radio = context.getResources().getString(R.string.grams);
    }

    public AerProvider(Context ctx) {
        super(ctx);
        context = ctx;

i am setting rb_radio values for the resource folder as you can see but i am getting null pointer exception,below is my stack trace

10-09 16:38:40.265: E/AndroidRuntime(4114): Caused by: java.lang.NullPointerException
10-09 16:38:40.265: E/AndroidRuntime(4114):at com.in.android.aer.contentprovider.AerProvider.<clinit>(AerProvider.java:49)

Any help is appreciated

2 Answers 2

1

When rb_radio is initialized in a static way, context does not have a value yet as it will get its value in the constructor, when the object is instantiated.

Try this :

public static String rb_radio = null;
public static String im_radio = null;

public AerProvider(Context ctx) {
    super(ctx);
    context = ctx;
    if (rb_radio == null) rb_radio = context.getResources().getString(R.string.kgs);
    if (im_radio == null) im_radio = context.getResources().getString(R.string.grams);
}
Sign up to request clarification or add additional context in comments.

Comments

0

The code in your static initializer is too early to run at static initialization phase. For example, the instance variable context is not yet initialized.

Move the code in your static { ... } block to onCreate() in the proider.

Also note that content providers should not have a constructor that takes args, though with this code you should be getting a compile-time error if the class really was a ContentProvider.

2 Comments

cool thank you, how should i get R.string values loaded to my static block when the application starts?
You can't. Context and resources are only available in and after onCreate() in android app/activity/service/whatever lifecycle.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.