Andrew
Andrew

Reputation: 2157

Call fragment method from dialogfragment

I'm trying to call fragment function from dialogfragment. My application is based on navigation drawer which contains container for fragments. At one of my fragments I make retrofit request and I also can open dialogfragment from this fragment. But I faced with one very serious problem - I can't get SharedPreferences after calling fragment function from dialogFragment. Here how I call this method:

 btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
                JobList jobList = new JobList();
                jobList.testFunction();
            }
        });

and here is my testFunction():

public void testFunction() {
        sp = Objects.requireNonNull(getActivity()).getSharedPreferences("app_data", 0);
        Log.w("MY_tag", sp.getString("access_token", ""));
    }

my testFunction contains only experimental logs, because I try to get data from sharedpreferences but I get only error:

java.lang.NullPointerException

after putting breakpoint I understood that I can't receive any context for getting sharedPreferences. I can't understand how to solve my problem, and I will be happy if smb help me with the solution.

Upvotes: 1

Views: 1451

Answers (2)

Erselan Khan
Erselan Khan

Reputation: 845

Easy and Recommended way:

First make a callback in fragment: How?

interface DialogCallBack{
    void callback(View view);
}

implement interface on your fragment, and when you create constructor for your dialogfragment, just pass the callback for that fragment.

Then in your dialogFragment:

btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dismiss();
            listener.callback(view);
        }
    });

listener call interface method which is implemented on fragment. So do this inside your fragment:

@override
callback(View view){
 testFunction(view);
}

Upvotes: 1

Farid Haq
Farid Haq

Reputation: 4229

please try as follows

btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dismiss();
            JobList jobList = new JobList();
            jobList.testFunction(view);
        }
    });

  public void testFunction(View view) {
    sp = Objects.requireNonNull(view.getContext()).getSharedPreferences("app_data", 0);
    Log.w("MY_tag", sp.getString("access_token", ""));
}

Upvotes: 1

Related Questions