suku suku - 28 days ago 9
Android Question

Passing context of fragment to a class which executes a method in the fragment through an interface

I have a fragment which initializes download process through a class NetworkConnector along with RequestCompleteListener class which listens to the completion of the download.

Constructor of NetworkConnector

public NetworkConnector(Context ctx, String url, String methodType, int downloadId,
ArrayList<ArrayList<String>> postData, RequestCompleteListener<String> listener)


This class does the download and through an interface named RequestCompleteListener, executes the method OnRequestExecuted.

public class OnRequestComplete implements RequestCompleteListener<String> {
private DataProcessInterface dataProcessInterface;

public OnRequestComplete(Context context) {
dataProcessInterface = (DataProcessInterface) context;
}

@Override
public void onRequestExecuted(String responseType, String result, int downloadId) {
if (!responseType.equals("error")) {
dataProcessInterface.processData(result, downloadId);
} else {
dataProcessInterface.processError(result, downloadId);
}
}
}


The fragment implements the interface DataProcessInterface. And OnRequestCompleted method executes methods, processData and processError, in the fragment using through the interface.

public class FoodListFragment extends Fragment implements DataProcessInterface {


This process works perfectly fine when executed from an activity. But when this done through a fragment, I get
ClassCastException
as it needs the context of the fragment in place of the ??? below.

new NetworkConnector(getActivity(), url, "GET", 101, null, new OnRequestComplete(???));


getActivity()
and
view.getContext()
don't work for obvious reasons. When I tried
FoodListFragment.this
, the error says it
OnRequestComplete
wants a context and not a fragment.

So what should be passed in place of the ??? ? I don't want to implement the
DataProcessInterface
interface in the activity and then use another interface to show the data in the fragment.

Answer

A fragment isn't a Context, it may have a Context. You're passing a context to the OnRequestComplete instance and trying to cast it to a DataProcessInterface. You should probably pass the interface directly instead for clarity.

public class OnRequestComplete implements RequestCompleteListener<String> {
    private DataProcessInterface dataProcessInterface;

    public OnRequestComplete(DataProcessInterface dpi) {
        dataProcessInterface = context;
    }
<....>
   }

and now the below should work.

new NetworkConnector(getActivity(), url, "GET", 101, null, new OnRequestComplete(FoodListFragment.this));

Update: Note, I think you're in for a world of hurt with this design tho. You're risking leaking both contexts and fragments.