问题描述
*的更新时间:(见下文)的*我一直在四处寻找几天,找不到一个直接的答案。有人说,这可能在一定要说到做到有人说这不是。我正在疯狂这一点。
*Updated: (See below)*I have been looking around for couple of days and can't find a straight answer to this.Some say it possible to some say to accomplish some say it's not. I am getting crazy on this.
我要的只是有AsyncTaskTask呈现出进度的外部类。要做到这一点,我路过的背景下,你可以在主类见。但无论我尝试,我得到 NullPointerException异常
。
What I want is just to have the AsyncTaskTask showing a progressbar an external class. To do this I am passing the context as you can see in the main class. But whatever I try I get NullPointerException
.
工作code的例子就是AP preciated。谢谢
Working code examples is appreciated. Thank you
采用Android 2.2的方式。
Using Android 2.2 by the way.
主要的:
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();
}
}
AsyncClass.java
AsyncClass.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();
}
}
更新: 我有一个跟进的问题:使用上述code,是有可能从onPostExecute方法回返回一个值主班,不知何故? (很抱歉beeing noobish)我曾尝试这样的东西:
Update: I have a follow up question: Using the above code, is it possible to return a value from the onPostExecute method back to the main class, somehow? (Sorry about beeing noobish)I have tried something like this:
String result = new AsyncClass(this).execute();
和然后该返回字符串的方法。但我不能这样做,因为我得到了:
and then a method that return back a string. But I can't do that because i got:
Type mismatch: cannot convert from AsyncTask<String,Void,Void> to String
我能做些什么来解决这个问题?谢谢你。
What can I do to tackle this problem? Thanks.
推荐答案
您用了一个空的上下文创建 ProgressDialog
。下面code为我工作。
You were creating the ProgressDialog
with a null context. The following code worked for me.
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();
}
}
这篇关于与ProgressDialog外部的AsyncTask类[更新:?并返回返回]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!