Can't post response from AsyncTask to MainActivity [closed]

南笙酒味 提交于 2019-11-28 13:13:56
Raghunandan

This is wrong. You should not create an instance of your activity class.

 MainActivity main = new MainActivity();

Activity is started by startActivity.

You can make your asynctask an inner class of your activity class and update ui in onPostExecute

Or use a interface

How do I return a boolean from AsyncTask?

Edit

   new OnbuttonclickHttpPost(ActivityName.this).execute(params);

In your asyctask

  TheInterface listener;

In the construcotr

  public OnbuttonclickHttpPost(Context context)
{

    listener = (TheInterface) context;
    c= context;

}    

The interface

  public interface TheInterface {

    public void theMethod(String result);

     }

In onPostExecute

    if (listener != null) 
  {
      listener.theMethod(result);
      }

In your activity class implement the interface

     implements OnbuttonclickHttpPos.TheInterface

Implement the method

     @Override
     public void theMethod(STring result) {
   // update ui using result
     }
codeMagic

This is the wrong way to do it. The best way is if you don't need that AsyncTask anywhere else then make it an inner class of your Activity. Then it will have access to member variables of your Activity and functions so it can update variables easily in your onPostExecute().

If you want to keep it as a separate file then you can use an interface to listen for a callback.

This answer has an interface example at the bottom of the answer.

just change your onPostExecute()

@Override
protected void onPostExecute(String result) {
    parseResponse(result);      
}

and then you have

private void parseResponse(String result) {
    if(result.equals("NO_USER_ERROR")){
        showNewDialog("There is no user existed with the given details.");
    }else if(result.equals("FIELDS_ERR")){
        showNewDialog("Please enter username and password.");
    }else{
        startRecharge(result);
    }
}

This is not doing nothing

MainActivity main = new MainActivity();

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!