1

I read the official Android documentation on creating an interface to be able to communicate between a parent activity and a fragment. So I did but my app crashes when I call one of the methods to get a value from the parent activity.

if have an interface like this in my fragment

public interface InteractWithFragmentA { String getStringText(); }

In my calling activity I tested it out with a dummy text

@Override 
public String getStringText(){ return "Some dummy text";}

I have a variable in FragmentA.java that's a reference to the host activity and casted to InteractWithFragmentA, but when I call the method using

_hostActivity.getStringText()

the app crashes. Is there something that I'm missing? I've seen some suggested methods for getting the host activity's variables by making them public and static or some other method but I'm trying not to couple the fragment to that activity. Thanks in advance.

1
  • Could you post your logcat? Commented Nov 13, 2017 at 19:36

2 Answers 2

3

Yo should do this:

Activity

 public class YourActivity implements YourActivityInterface{
     @Override   public String getStringText(){ return "Some dummy text";}
 }

Interface

    public interface YourActivityInterface {
    String getStringText(); 
}

Fragment

  public class YourFragment extends Fragment {

    YourActivityInterface mListener;

     //your method...
     mListener.getStringText()


@Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof YourActivityInterface) {
            mListener = (YourActivityInterface) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement YourActivityInterface");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Figured out the problem. My getSomething method in my activity was returning a null value. I tested it with mock data and it worked then I figured out what the problem was.
Thanks for your help
2

Try this from fragment

((YourActivity) getActivity()).getStringText();

1 Comment

I was actually trying to avoid coupling the fragment to the activity like that. I figured out what the problem was. I was returning a null value. I appreciate your help though.

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.