-4

Hello so I am trying to pass an array list from my activity to the fragment and this is what I did :

FirstActivity :

AdminInterface instanceForInterface;

OnCreate
//
System.out.println(results.size) ; //works fine
instanceForInterface.onDataRecieved(results);  // here I am getting the exception
//

public interface AdminInterface {
    void onDataRecieved(ArrayList <Result> response);
}



public void setInterface(UserFragment anInterface) {
    this.instanceForInterface = anInterface;
}

Fragment

 OnActivityCreated
((FirstActivity) getActivity()).setInterface(this);

 @Override
public void onDataRecieved(ArrayList<Result> response) {
    processData(response);
}

Exception

Attempt to invoke interface method 'void **************.onDataRecieved(java.util.ArrayList)' on a null object reference

What I think :

I am calling this line

instanceForInterface.onDataRecieved(results); in OnCreate()

before the initialisation of

((FirstActivity) getActivity()).setInterface(this); in OnActivityCreated()

Solution Please ??

Thank You

Shreeya Chhatrala
  • 1,441
  • 18
  • 33
Mohamed Elloumi
  • 158
  • 4
  • 21

1 Answers1

1

The problem is that your fragment's onActivityCreated() method is invoked after your activity's onCreate() method.

The smallest change you can make to achieve the behavior you want is to use the onResumeFragments() method in your activity. That is, delete the line instanceForInterface.onDataRecieved(results); from your onCreate and add this code:

@Override
protected void onResumeFragments() {
    super.onResumeFragments();
    instanceForInterface.onDataRecieved(results);
}

onResumeFragments() will be invoked by the system after both your activity's onCreate() and your fragment's onActivityCreated() methods.

That being said, chances are quite good that you would be better off with a different approach entirely. For instance, you could have your activity expose a getter for results and have your fragment retrieve the results to work with (rather than have your activity store a reference to your fragment).

Further reading about the Activity and Fragment lifecycles: https://developer.android.com/guide/components/activities/activity-lifecycle.html https://developer.android.com/guide/components/fragments.html

Ben P.
  • 52,661
  • 6
  • 95
  • 123