有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java异步任务:doInBackground未完成

我正在尝试在Android中实现一个AsyncTask,它将从数据库中加载我的所有数据。因此,我使用了onPreExecute方法来启动ProgressDialog

public class DataLoader extends AsyncTask<Void, Void, Void> {

private LoginActivity activity;
private ProgressDialog nDialog;

public DataLoader (LoginActivity act){
    this.activity = act;
    nDialog = new ProgressDialog(activity);
}

protected void onPreExecute() {
    System.out.print("Start AsyncTask");
    nDialog.setMessage("Loading data..");
    nDialog.setTitle("Starting the application");
    nDialog.setIndeterminate(false);
    nDialog.setCancelable(true);
    nDialog.show();
}

@Override
protected Void doInBackground(Void ... params) {
    System.out.println("Starting doInBackground");
    loadDashboardData();
    return null;
}

protected void onPostExecute() {
    nDialog.dismiss();
    Intent i = new Intent();
    i.setClass(activity.getApplicationContext(), DashboardActivity.class);
    activity.startActivity(i);
}

I使用doInBackground方法加载调用函数来加载数据。此方法是从可见活动调用的。该任务通过以下方式调用:

public class LoginActivity extends Activity {
    public void onClick(View v) {
        DataLoader dl = new DataLoader(this);
        dl.execute();
    }
}

doInBackground的代码是:

protected Void doInBackground(Void ... params) {
    System.out.println("Starting doInBackground");
    loadDashboardData();
    return null;
}

现在的问题是我的doInBackground方法无法完成。我试图在onPreExecute方法中实现loadDashboardData()调用。这不会显示“我的”对话框,但会正确加载数据。在这种情况下,UI线程没有响应,将在加载所有数据后响应

什么会妨碍doInBackground方法正确执行并正确加载数据?被调用的方法有效(因为我可以调用它并获得正确的数据)。此外,我没有在我的跑步控制台中看到println。 在前端,我可以看到progressbar正在旋转,但在后端,我可以看到没有加载任何数据


共 (1) 个答案

  1. # 1 楼答案

    您的问题是覆盖了错误的方法名称:) 应该是的

    @Override
    protected void onPostExecute(Void result) {
        // your code
    }
    

    在你的例子中,doInBackground返回的变量是Void

    你可以查看关于AsyncTask的文档