Java – How to translate the context of a fragment into an interface

How to translate the context of a fragment into an interface… here is a solution to the problem.

How to translate the context of a fragment into an interface

I want to return a value from the AsyncTask class via interface. The problem is that my following code works fine in Activity but not in the fragment class.

I got ClassCastException:

java.lang.ClassCastException: com.demo.HomeActivity cannot be cast to com.demo.helper.OnTaskCompleteListener
at com.demo.util.JSONParseAsync.<init>(
at com.demo.fragment.PersonalDetailFragment.loadProfileAction(
at com.demo.fragment.PersonalDetailFragment.onCreate(

Interface class:

public interface OnTaskCompleteListener {

void onTaskComplete(JSONObject jsonObject);


PersonalDetailFragment class:

public class PersonalDetailFragment extends Fragment  implements OnTaskCompleteListener {
private View view;

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragment_personal_detail, container,
    return view;
private void loadProfileAction() {

SessionPreference preference = new SessionPreference(getActivity());
    try {
        String encodedUrl = URLEncoder.encode(preference.getSessionId(), "UTF-8")
                + ","
                + URLEncoder.encode(Constants.URL_TOKEN, "UTF-8");
         URL base64Encode
        String processUrl = Base64.encodeToString(encodedUrl.getBytes("UTF-8"), Base64.DEFAULT);

JSONParseAsync parseAsync = new JSONParseAsync(getContext());  also try getActivity()

} catch (UnsupportedEncodingException e) {
    } catch (Exception e) {

public void onTaskComplete(JSONObject jsonObject) {
    try {

boolean status = jsonObject.getBoolean(URLConstants.TAG_STATUS);

Log.e(Constants.DEBUG_TAG, "Status:- " + status);

if (status == true) {
            JSONArray dataarray = jsonObject.getJSONArray(URLConstants.TAG_DATA);
            JSONObject data = dataarray.getJSONObject(0);

} else if (status == false) {
                    "Incorrect User Name OR Password",

Log.i("GARG", "Excution Line Finish ");
    } catch (Exception e) {

JSONParseAsync class:

public class JSONParseAsync extends AsyncTask<String, String, JSONObject>{

private Context mContext;

ProgressDialog mProgress;
private OnTaskCompleteListener mCallback;

public JSONParseAsync(Context context){
    this.mContext = (AppCompatActivity)context;
    this.mCallback = (OnTaskCompleteListener) mContext;

protected JSONObject doInBackground(String... URL) {
    JSONObject jsonObj = null;

    Log.d(Constants.DEBUG_TAG, "line excucation 2 doInBackground");
    ServiceHandler sh = new ServiceHandler();
    String url = URL[0];
    Log.d(Constants.ACTIVITY_TAG, "...." + url);
     Making a request to url and getting response.

String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

Log.d(Constants.JSON_TAG, "" + jsonStr);

if (jsonStr != null) {

jsonObj = new JSONObject(jsonStr);
            Log.e(Constants.JSON_TAG, "" + jsonObj);

    } catch (JSONException e) {
    } catch (Exception e) {
    return jsonObj;

protected void onPreExecute() {
    Log.d(Constants.DEBUG_TAG, "line excucation 1 onPreexcute");
    mProgress = new ProgressDialog(mContext);
    mProgress.setMessage("Downloading nPlease wait...");;

protected void onProgressUpdate(String... values) {
    Log.d(Constants.DEBUG_TAG, "line excucation 3 onProgressUpdate");

protected void onPostExecute(JSONObject result) {
    Log.d(Constants.DEBUG_TAG, "line excucation 3 onPostExecute");
    This is where you return data back to caller
    Log.d(Constants.APP_TAG, " final result:- "+result);


Please help me :


By doing so

JSONParseAsync parseAsync = new JSONParseAsync(getContext());

You are sending an activity to your AsyncTask, but it is your Fragment that implements the OnTaskCompleteListener.

Or let your activity implement your interface, or

Do this:

JSONParseAsync parseAsync = new JSONParseAsync(this, getContext());

and change your AsyncTask constructor to

public JSONParseAsync(OnTaskCompleteListener listener, Context context){
    this.mContext = context;
    this.mContext = (AppCompatActivity)context; -> you don't need that cast, AppCompatActivity is a subclass of Context
    this.mCallback = listener;

Related Problems and Solutions