title: Class Casting error when I pass the listener to async task
body: <p>I am working on async task , the structure is implement interface in the main class, pass the main class to the async task as an listener , when the async class is finish , call the listener function , the problem is when I pass the main class to async task it return the following error:</p>
  
  <pre><code>02-18 19:37:43.826: E/AndroidRuntime(15928): FATAL EXCEPTION: AsyncTask #2
  02-18 19:37:43.826: E/AndroidRuntime(15928): java.lang.RuntimeException: An error occured while executing doInBackground()
  02-18 19:37:43.826: E/AndroidRuntime(15928):    at android.os.AsyncTask$3.done(AsyncTask.java:299)
  02-18 19:37:43.826: E/AndroidRuntime(15928):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
  02-18 19:37:43.826: E/AndroidRuntime(15928):    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
  02-18 19:37:43.826: E/AndroidRuntime(15928):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
  02-18 19:37:43.826: E/AndroidRuntime(15928):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
  02-18 19:37:43.826: E/AndroidRuntime(15928):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
  02-18 19:37:43.826: E/AndroidRuntime(15928):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
  02-18 19:37:43.826: E/AndroidRuntime(15928):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
  02-18 19:37:43.826: E/AndroidRuntime(15928):    at java.lang.Thread.run(Thread.java:856)
  02-18 19:37:43.826: E/AndroidRuntime(15928): Caused by: java.lang.ClassCastException: com.project.hkseven.Fragment.Home$1 cannot be cast to com.project.hkseven.Listener.LoginListener
  02-18 19:37:43.826: E/AndroidRuntime(15928):    at com.project.hkseven.Utility.APIHandler.doInBackground(APIHandler.java:69)
  02-18 19:37:43.826: E/AndroidRuntime(15928):    at com.project.hkseven.Utility.APIHandler.doInBackground(APIHandler.java:1)
  02-18 19:37:43.826: E/AndroidRuntime(15928):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
  02-18 19:37:43.826: E/AndroidRuntime(15928):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
  02-18 19:37:43.826: E/AndroidRuntime(15928):    ... 5 more
  </code></pre>
  
  <p>Here is how I call and pass the main class (a fragment) to async task</p>
  
  <pre><code>new APIHandler(getActivity(),tracker,"login").execute(this,session.getAccessToken());
  </code></pre>
  
  <p>The API Handler , which is an async task , handle like this</p>
  
  <pre><code>public class APIHandler extends AsyncTask&lt;Object, Void, JSONObject&gt; {
      private String TAG = "APIHandler";
      private LoginListener loginListener;
      private UploadImageListener uploadImageListener;
      private UpdateProfileListener updateProfileListener;
      private MyPtListener myPtListener;
  
      public Context ctx;
      public String type;
      public String url;
      public String formType;
      public EasyTracker tracker;
      public String token;
      public String memId;
  
      public APIHandler(Context _ctx,EasyTracker _tracker,String _formType) {
          this.ctx = _ctx;
          this.tracker = _tracker;
          this.formType = _formType;
  
          //Get access data
          SharedPreferences prefs = ctx.getSharedPreferences("userInfo", 0);
          token = prefs.getString("token","");
          memId = prefs.getString("memId","");
      }
  
      @Override
      protected JSONObject doInBackground(Object... params) {
  
          MultipartEntityBuilder builder = MultipartEntityBuilder.create();
          builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
  
          if (formType.equals("login")){
  
              url = Constant.loginAPI;
              loginListener = (LoginListener) params[0];
  
              Log.d(TAG, "Login API(token): " + params[1] );
  
              builder.addTextBody("var1", (String) params[1]); //Facebook access token
              builder.addTextBody("var2", "2"); //Device type 2 = android
  
  .......................
  
  @Override
      protected void onPostExecute(JSONObject result) {
  
  
          try {
              if(result != null)  {
                  if (formType.equals("login")){
                      if (result.getString("result").equals("ok")) {
                          loginListener.onLoginComplete(result.getString("member_id"),result.getString("token"));
                      }else {
                          loginListener.onLoginFailure(result.getString("error_code"));   
                      }
  </code></pre>
  
  <p><strong>Update:</strong></p>
  
  <p>Thanks for reply , I have implemented the loginListener for sure, but it still casting error.</p>
  
  <p>The interface:</p>
  
  <pre><code>public interface LoginListener {
      public void onLoginComplete(String memberId, String token);
      public void onLoginFailure(String errorMsg);
  }
  </code></pre>
  
  <p>The Home class fragment:</p>
  
  <pre><code>public class Home extends Fragment implements LoginListener {
      public View rootView;
      public ImageView HomeBg;
      public ImageView buttonLoginLogout;
      public TextView chi;
      public TextView eng;
      public ColorStateList oldColor;
      public SharedPreferences prefs;
      public EasyTracker tracker = null;
      public String[] PERMISSION_ARRAY_READ = {"email"};
      public List&lt;String&gt; PERMISSION_LIST;
      public SharedPreferences.Editor editor;
      public ProgressDialog pd;
  
      //Facebook login
      private Session.StatusCallback statusCallback = new SessionStatusCallback();
  
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
              Bundle savedInstanceState) {
  
          tracker = EasyTracker.getInstance(getActivity());
  
          PERMISSION_LIST = Arrays.asList(PERMISSION_ARRAY_READ);
  
          prefs = getActivity().getSharedPreferences("userInfo", 0);
          editor = prefs.edit();
  
          getActivity().getActionBar().hide();
  
          rootView = inflater.inflate(R.layout.home, container, false);
          buttonLoginLogout = (ImageView) rootView.findViewById(R.id.home_connectFB);
          eng = (TextView) rootView.findViewById(R.id.btn_eng);
          chi = (TextView) rootView.findViewById(R.id.btn_chi);
  
          if (Utility.getLocale(getActivity()).equals("TC")) {
              chi.setTextColor(getActivity().getResources().getColor(
                      android.R.color.white));
              oldColor = eng.getTextColors();
          } else {
              eng.setTextColor(getActivity().getResources().getColor(
                      android.R.color.white));
              oldColor = chi.getTextColors();
  
          }
  
          eng.setOnClickListener(setChangeLangListener("EN"));
          chi.setOnClickListener(setChangeLangListener("TC"));
  
          //Facebook login
          Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
  
          Session session = Session.getActiveSession();
          if (session == null) {
              if (savedInstanceState != null) {
                  session = Session.restoreSession(getActivity(), null, statusCallback, savedInstanceState);
              }
              if (session == null) {
                  session = new Session(getActivity());
              }
              Session.setActiveSession(session);
              if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
                  session.openForRead(new Session.OpenRequest(this).setPermissions(PERMISSION_LIST).setCallback(statusCallback));
              }
          }
  
         updateView();
         return rootView;
      }
  
      @Override
      public void onStart() {
          super.onStart();
          Session.getActiveSession().addCallback(statusCallback);
          tracker.set(Fields.SCREEN_NAME, "hk7app/CX/" + Utility.getLocale(getActivity()) + "/Landing Page");
          tracker.send(MapBuilder.createAppView().build());
      }
  
      @Override
      public void onStop() {
          super.onStop();
          Session.getActiveSession().removeCallback(statusCallback);
          EasyTracker.getInstance(getActivity()).activityStop(getActivity());
      }
  
      @Override
      public void onActivityResult(int requestCode, int resultCode, Intent data) {
          super.onActivityResult(requestCode, resultCode, data);
          Session.getActiveSession().onActivityResult(getActivity(), requestCode, resultCode, data);
      }
  
      @Override
      public void onSaveInstanceState(Bundle outState) {
          super.onSaveInstanceState(outState);
          Session session = Session.getActiveSession();
          Session.saveSession(session, outState);
      }
  
      @SuppressWarnings("deprecation")
      private void updateView() {
          final Session session = Session.getActiveSession();
          if (session.isOpened()) {
              Request.executeMeRequestAsync(session,
                  new Request.GraphUserCallback() {
                      @Override
                      public void onCompleted(GraphUser user,Response response) {
                          // TODO Auto-generated method stub
                          if (user != null) {
                              if (!user.getId().equals(prefs.getString("fbId",""))) {
                                  editor.putString("fbId", user.getId());
                                  editor.putString("fName", user.getFirstName());
                                  editor.putString("lName", user.getLastName());
                                  editor.putString("email", user.asMap().get("email").toString());
                                  editor.commit();
                                  //pd = ProgressDialog.show(getActivity(), getActivity().getResources().getString(R.string.sys_info),getActivity().getResources().getString(R.string.loading));
                                  Log.d("test1",session.getAccessToken());
                                  new APIHandler(getActivity(),tracker,"login").execute(this,session.getAccessToken());
                              } else {
                                  onLoginComplete("","");
                              }
                          }
                      }
              });             
  
          } else {
              buttonLoginLogout.setImageResource(R.drawable.landing_btn_connect_facebook);
              buttonLoginLogout.setOnClickListener(new View.OnClickListener() {
                  public void onClick(View view) { onClickLogin(); }
              });
          }
      }
  
      private void onClickLogin() {
          tracker.send(MapBuilder.createEvent("menu_click","Fbconnect","connectFB_" + Utility.getLocale(getActivity()),null).build());
          Session session = Session.getActiveSession();
          if (!session.isOpened() &amp;&amp; !session.isClosed()) {
              session.openForRead(new Session.OpenRequest(this).setPermissions(PERMISSION_LIST).setCallback(statusCallback));
          } else {
              Session.openActiveSession(getActivity(), this, true, statusCallback);
          }
      }
  
      private class SessionStatusCallback implements Session.StatusCallback {
          @Override
          public void call(Session session, SessionState state, Exception exception) {
              updateView();
          }
      }
  
      public OnClickListener setChangeLangListener(final String lang) {
          OnClickListener changeLangListener = new OnClickListener() {
              @Override
              public void onClick(View arg0) {
                  Configuration config = new Configuration(getResources().getConfiguration());
  
                  if (Utility.getLocale(getActivity()).equals("TC") &amp;&amp; lang.equals("EN")) {
                      tracker.send(MapBuilder.createEvent("menu_click","language", "switchEN", null).build());
                      config.locale = Locale.ENGLISH;
                      chi.setTextColor(oldColor);
                      eng.setTextColor(getActivity().getResources().getColor(
                              android.R.color.white));
                  } else if (Utility.getLocale(getActivity()).equals("EN") &amp;&amp; lang.equals("TC")) {
                      tracker.send(MapBuilder.createEvent("menu_click","language", "switchTC", null).build());
                      config.locale = Locale.TRADITIONAL_CHINESE;
                      eng.setTextColor(oldColor);
                      chi.setTextColor(getActivity().getResources().getColor(
                              android.R.color.white));
                  }
  
                  getResources().updateConfiguration(config,getResources().getDisplayMetrics());
  
                  onConfigurationChanged(config);
              }
          };
          return changeLangListener;
      }
  
      @Override
      public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Intent intent = getActivity().getIntent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        getActivity().finish();
        startActivity(intent);
      }
  
      @Override
      public void onResume() {
          super.onResume();
          AppEventsLogger.activateApp(getActivity(),getResources().getString(R.string.app_id));
      }
  
      @Override
      public void onLoginComplete(String memberId, String token) {    
          if (pd != null)
              pd.dismiss();
  
          if (!memberId.equals("") &amp;&amp; !token.equals("")) {
              editor.putString("memId", memberId);
              editor.putString("token", token);
          }
  
          buttonLoginLogout.setImageResource(R.drawable.landing_btn_take_a_selfie);
          buttonLoginLogout.setOnClickListener(new View.OnClickListener() {
              public void onClick(View view) {
                   tracker.send(MapBuilder.createEvent("menu_click","TakeSelfie","Selfie_now_" + Utility.getLocale(getActivity()),null).build());
                  ((LandingPage)getActivity()).tabHost.setCurrentTab(2);
              }
          });
      }
  
      @Override
      public void onLoginFailure(String errorMsg) {
          if (pd != null)
              pd.dismiss();
  
          Toast.makeText(getActivity(), errorMsg, Toast.LENGTH_LONG).show();
      }
  
  }
  </code></pre>
  
  <p><strong>Update(2):</strong></p>
  
  <p>Instead of casting the Home to LoginListener , I tried to simply not casting it , the problem is it still throw exception</p>
  
  <pre><code>Caused by: java.lang.ClassCastException: com.project.hkseven.Fragment.Home$1 cannot be cast to com.project.hkseven.Fragment.Home
  </code></pre>