-1

I have a class thate extends a built-in dialog class, and I want to access sharedprefence in it, but having null pointer exception at that point.

Here is my code

public class DialogCancelOrder extends Dialog {

    Context context;

    public DialogCancelOrder(Context a, String orderid) {
        super(a);
        this.orderid = orderid;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sp = context.getSharedPreferences("afewtaps", Context.MODE_PRIVATE);

        face = Typeface.createFromAsset(context.getAssets(), "fonts/Nunito-Regular.ttf");
        face1 = Typeface.createFromAsset(context.getAssets(), "fonts/Rupee_Foradian_2.ttf");
}
Petter Hesselberg
  • 5,062
  • 2
  • 24
  • 42
Mukesh Mishra
  • 241
  • 1
  • 3
  • 12

4 Answers4

3

You are missing the line context=a; Use the below code. I have assigned the value for the context in the constructor.

 public class DialogCancelOrder extends Dialog {

    Context context;

    public DialogCancelOrder(Context a, String orderid) {
        super(a);
        this.orderid = orderid;
        this.context = a;

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        sp = context.getSharedPreferences("afewtaps", Context.MODE_PRIVATE);

        face = Typeface.createFromAsset(context.getAssets(), "fonts/Nunito-Regular.ttf");
        face1 = Typeface.createFromAsset(context.getAssets(), "fonts/Rupee_Foradian_2.ttf");

    }
}
Nithinlal
  • 4,845
  • 1
  • 29
  • 40
0

You don't initialize your context field. Try this in the constructor:

this.context = a;
Petter Hesselberg
  • 5,062
  • 2
  • 24
  • 42
0

you did not initialize context use this. This may help

public DialogCancelOrder(Context a, String orderid) {
               super(a);
                      this.orderid = orderid;
                      context=a;
                        }
santosh kumar
  • 2,952
  • 1
  • 15
  • 27
0

You simply don't write anything into context variable. Then you try to use it.
Instead of declaring your own variable, you can use this.getContext() inside the Dialog

Vladyslav Matviienko
  • 10,610
  • 4
  • 33
  • 52