AsyncTask.execute()不等待doInBackground完成

时间:2016-01-28 04:16:34

标签: java android multithreading android-asynctask

我知道这是一个重复的问题,但请坚持下去。我已经阅读了一些类似的问题和答案,但似乎没有一个对我有用。

怎么做: 我必须进行搜索,它将向Web服务发送请求并收到响应。 由于我无法在UI线程上使用网络,因此我使用了AsyncTask

我尝试了什么: 我尝试使用task.execute()立即返回,甚至没有显示progressdialog框,我收到响应为null(在onPostExecute中设置)

如果我使用task.execute.get(),它会冻结屏幕并再次显示没有对话框(但我收到的回复正确)。

下面是我的task.execute代码。请指正。

public class LookIn extends AppCompatActivity implements View.OnClickListener{
private Button btn=null;
private TextView txtPinCode=null;
private Service service=null;
private final static  int timeout=20;
private String jsonResponse;
//private ProgressBar helperSearchProgressBar;
private String pincode="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_look_in);
    btn=(Button)findViewById(R.id.button);
    btn.setOnClickListener(this);
    txtPinCode=(TextView) findViewById(R.id.txtPinCode);
    this.service=(Service) ParamFactory.getParam(ConstantLabels.SELECTED_SERVICE_ID);
   // this.helperSearchProgressBar=(ProgressBar)findViewById(R.id.helperSearchProgressBar);
}


@Override
public void onClick(View v) {

    String pincode= txtPinCode.getText().toString();
    if(pincode==null || pincode.isEmpty() || pincode.length()!=6)
    {
        this.txtPinCode.setError("Please enter a 6 degit pin code from 700000 to 700200");

        return;
    }

    ParamFactory.setParam(ConstantLabels.PINCODE_ID,pincode);
    this.pincode=pincode;
    loadHelper();

    Intent intent= new Intent(LookIn.this,SearchResult.class);
    startActivity(intent);
}


public void setJsonResponse(String jsonResponse)
{
    this.jsonResponse=jsonResponse;
}
private void loadHelper()
{

    Log.v("Callme", "Running thread:" + Thread.currentThread().getId());
    ArrayAdapter<User> adapter=null;
    String params=this.pincode+","+this.service.getId();
    List<User> result=null;
    try {
        new CallmeGetHelperAsyncTask().execute(params); //my task.execute()
        result= RestUtil.getUserList(jsonResponse);
        adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, result);
        ParamFactory.setParam("getHelperForService", adapter);
    }
    catch(JSONException x)
    {
        Log.e("Callme", Log.getStackTraceString(x));
    }

}
class CallmeGetHelperAsyncTask extends AsyncTask<String,Void,String > {
   // private Context context=null;
    private ProgressDialog dialog=null;
    private String jsonResponse;
    private LookIn activity;
    public CallmeGetHelperAsyncTask(){}
    public CallmeGetHelperAsyncTask(LookIn activity)
    {
        this.activity=activity;
    }
    @Override
    protected void onPreExecute() {
       this.dialog= new ProgressDialog(LookIn.this);
        this.dialog.setMessage("Loading...");
        this.dialog.show();
        Log.v("Callme","Dialog Shown");
    }

    @Override
    protected void onPostExecute(String s) {
        if(s!=null)
        {
            this.activity.setJsonResponse(s);
        }
        else
        {
            Log.v("Callme","kill me");
        }
        if(this.dialog.isShowing())
        {
            Log.v("Callme","Closing Dialog");
            this.dialog.dismiss();
        }

    }

    @Override
    protected String doInBackground(String... params) {
        Log.v("Callme","From Background:"+Thread.currentThread().getId());
        String pincode=params.clone()[0].split(",")[0];
        String serviceId=params.clone()[0].split(",")[1];
        String url=String.format(URL.GET_HELPER,serviceId,pincode);
        jsonResponse= null;
        try {
            jsonResponse = RestUtil.makeRestRequest(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonResponse;
    }
}

}

注意:我没有尝试使用while循环来等待asynctask,因为我认为这也会冻结我的屏幕。如果我错了,请纠正我

1 个答案:

答案 0 :(得分:3)

  

我没有尝试使用while循环来等待asynctask

无需使用循环来等待AsyncTask结果。

因为onPostExecute方法在doInBackground之后执行,所以不是在调用jsonResponse方法后使用execute,而是在setJsonResponse方法内执行,因为此方法从onPostExecute调用,始终在主UI线程上运行:

public void setJsonResponse(String jsonResponse)
{
    this.jsonResponse=jsonResponse;
    //Create adapter object here
    result= RestUtil.getUserList(jsonResponse);
    adapter = new ArrayAdapter(...);
    ParamFactory.setParam("getHelperForService", adapter);
}