gpt4 book ai didi

java - 带有 ProgressDialog 的外部 AsyncTask 类 [更新 : and returning back?]

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:37:41 26 4
gpt4 key购买 nike

**更新:(见下文)**我已经四处寻找了几天,但找不到直接的答案。有人说有可能,有人说可以,有人说不可能。我对此感到疯狂。

我想要的只是让 AsyncTaskTask 显示一个外部类的进度条。为此,我将传递上下文,正如您在主类中看到的那样。但无论我尝试什么,我都会得到 NullPointerException

工作代码示例表示赞赏。谢谢

顺便说一句,使用 Android 2.2。

主要内容:

import android.app.Activity;
import android.os.Bundle;

public class AsyncDemo extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new AsyncClass(this).execute();
}
}

异步类.java

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.SystemClock;

public class AsyncClass extends AsyncTask<Void, String, Void> {
private Context context;
ProgressDialog dialog = new ProgressDialog(context);

public AsyncClass(Context cxt) {
context = cxt;
}

@Override
protected void onPreExecute() {
dialog.setTitle("Please wait");
dialog.show();
}

@Override
protected Void doInBackground(Void... unused) {
SystemClock.sleep(2000);
return (null);
}

@Override
protected void onPostExecute(Void unused) {
dialog.dismiss();
}
}

更新: 我有一个后续问题:使用上面的代码,是否可以通过某种方式将 onPostExecute 方法的值返回到主类? (抱歉我是菜鸟)我试过这样的事情:

String result = new AsyncClass(this).execute();

然后是一个返回字符串的方法。但我不能那样做,因为我得到了:

Type mismatch: cannot convert from AsyncTask<String,Void,Void> to String

我该怎么做才能解决这个问题?谢谢。

最佳答案

您正在使用空上下文创建 ProgressDialog。以下代码对我有用。

public class AsyncClass extends AsyncTask<Void, String, Void> {
private Context context;
ProgressDialog dialog;

public AsyncClass(Context cxt) {
context = cxt;
dialog = new ProgressDialog(context);
}

@Override
protected void onPreExecute() {
dialog.setTitle("Please wait");
dialog.show();
}

@Override
protected Void doInBackground(Void... unused) {
SystemClock.sleep(2000);
return (null);
}

@Override
protected void onPostExecute(Void unused) {
dialog.dismiss();
}
}

关于java - 带有 ProgressDialog 的外部 AsyncTask 类 [更新 : and returning back?],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3347247/

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