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>(JSONParseAsync.java:33)
at com.demo.fragment.PersonalDetailFragment.loadProfileAction(PersonalDetailFragment.java:93)
at com.demo.fragment.PersonalDetailFragment.onCreate(PersonalDetailFragment.java:81)
at android.support.v4.app.Fragment.performCreate(Fragment.java:1942)
Interface class:
public interface OnTaskCompleteListener {
void onTaskComplete(JSONObject jsonObject);
}
PersonalDetailFragment class:
public class PersonalDetailFragment extends Fragment implements OnTaskCompleteListener {
private View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_personal_detail, container,
false);
loadProfileAction();
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()
parseAsync.execute((URLConstants.GET_USER_DETAIL_URL+processUrl).trim());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
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);
fillProfileData(data);
} else if (status == false) {
Snackbar.make(view,
"Incorrect User Name OR Password",
Snackbar.LENGTH_LONG).show();
}
Log.i("GARG", "Excution Line Finish ");
} catch (Exception e) {
e.printStackTrace();
}
}
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;
}
@Override
protected JSONObject doInBackground(String... URL) {
JSONObject jsonObj = null;
try{
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) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return jsonObj;
}
@Override
protected void onPreExecute() {
Log.d(Constants.DEBUG_TAG, "line excucation 1 onPreexcute");
mProgress = new ProgressDialog(mContext);
mProgress.setMessage("Downloading nPlease wait...");
mProgress.show();
}
@Override
protected void onProgressUpdate(String... values) {
Log.d(Constants.DEBUG_TAG, "line excucation 3 onProgressUpdate");
mProgress.setMessage(values[0]);
}
@Override
protected void onPostExecute(JSONObject result) {
Log.d(Constants.DEBUG_TAG, "line excucation 3 onPostExecute");
mProgress.dismiss();
This is where you return data back to caller
Log.d(Constants.APP_TAG, " final result:- "+result);
mCallback.onTaskComplete(result);
}
}
Please help me :
Solution
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;
}