gpt4 book ai didi

android - 无法在 AsyncTask 中显示 ProgressDialog

转载 作者:行者123 更新时间:2023-11-29 18:08:07 24 4
gpt4 key购买 nike

这是我的代码:

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate");
setContentView(R.layout.list);
new GetBlockListAsyncTask().execute(BlockListActivity.this);
}
public void initializeDialog() {
dialog = ProgressDialog.show(BlockListActivity.this, "", "Loading data. Wait...", true);
dialog.show();
}

public void dismissDialog(){
dialog.dismiss();
}

GetBlockListAsyncTask:

 public class GetBlockListAsyncTask extends AsyncTask<Object, Boolean, String>{

private BlockListActivity callerActivity;
private String TAG = "GetBlockListAsyncTask";
private String stringCode = "";

@Override
protected String doInBackground(Object... params) {

callerActivity = (BlockListActivity)params[0];
try {
Log.d(TAG, "Start to sleep");
Thread.sleep(4000);
Log.d(TAG, "End sleep");
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(String response) {
callerActivity.dismissDialog();
}

@Override
protected void onPreExecute() {
callerActivity.initializeDialog();
}

它会显示错误:

'Caused by: java.lang.NullPointerException'
onPreExecute(GetBlockListAsyncTask.java:101)

我发现一个解决方案是,如果我将 initializeDialog 移出 AsyncTask 并将其放在 new GetBlockListAsyncTask().execute(BlockListActivity.this); 行之前 onCreate,有效。
问题是如果我想将 initializeDialog 放在 AsyncTask 中,如何让它工作。

最佳答案

尝试向您的 AsyncTask 添加一个公共(public)构造函数,它接受 Activity Context 作为第一个参数:

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// Create a new AsyncTask with the Activity Context
AsyncTask task = new GetBlockListAsyncTask(this);

// Execute the task
task.execute();
}

public class GetBlockListAsyncTask extends AsyncTask<Object, Boolean, String> {
private Context activityContext;

private String TAG = "GetBlockListAsyncTask";
private String stringCode = "";

//Constructor
public GetBlockListAsyncTask(Context c) {
// Store the activity context
activityContext = c;
}

@Override
protected String doInBackground(Object... params) {
try {
Log.d(TAG, "Start to sleep");
Thread.sleep(4000);
Log.d(TAG, "End sleep");
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(String response) {
activityContext.dismissDialog();
}

@Override
protected void onPreExecute() {
activityContext.initializeDialog();
}
}

关于android - 无法在 AsyncTask 中显示 ProgressDialog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12292586/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com