【问题标题】:AsyncTask.execute() doesn't wait for doInBackground to completeAsyncTask.execute() 不等待 doInBackground 完成
【发布时间】:2016-01-28 04:16:33
【问题描述】:

我知道这是一个重复的问题,但请稍等。我已经阅读了一些类似的问题和答案,但它们似乎都不适合我。

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

我尝试了什么: 我尝试使用task.execute() 这会立即返回,甚至没有显示进度对话框,我收到的响应为空(在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 循环来等待异步任务,因为我认为这也会导致我的屏幕冻结。如果我错了,请纠正我

【问题讨论】:

  • 我希望,但我会反对。
  • 不,这也很好。我已经尝试从 doInBackground 打印 jsonresponse 并且效果很好。除此之外,如果我使用 new CallmeGetHelperAsyncTask().execute(params).get() 而不是 new CallmeGetHelperAsyncTask().execute(params)

标签: java android multithreading android-asynctask


【解决方案1】:

我没有尝试使用 while 循环来等待异步任务

无需使用循环等待AsyncTask Result。

因为onPostExecute 方法在doInBackground 之后执行,所以不要在调用execute 方法之后使用jsonResponse,而是在setJsonResponse 方法中执行,因为这个方法是从onPostExecute 调用的,它总是在 Main 上运行用户界面线程:

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

【讨论】:

  • hye ρяσѕρєя K,你的天才救了我。非常感谢
猜你喜欢
  • 2020-05-13
  • 2020-10-04
  • 1970-01-01
  • 2019-06-16
  • 2019-11-19
  • 2018-03-05
  • 2020-06-10
  • 2021-03-23
  • 2013-01-08
相关资源
最近更新 更多