你好朋友,我有一个类Asynctask
,我想获得onPostExecute
它在完成我的Activity
主要类时生成的方法的结果MainActivity
,因为类是分开的,有人知道怎么做吗?因为我遵循了英语 StackOverFlow 中可能解决方案的步骤:
但它给了我以下错误:
> E/AndroidRuntime: FATAL EXCEPTION: main
> Process: com.appmovilperote, PID: 29566
> java.lang.NullPointerException: Attempt to invoke interface method 'void
> com.appmovilperote.AsyncTaskServicios.AsyncResponse.processFinish(java.lang.String)'
> on a null object reference
> at com.appmovilperote.AsyncTaskServicios.AsyncTaskDatos.onPostExecute(AsyncTaskDatos.java:48)
> at com.appmovilperote.AsyncTaskServicios.AsyncTaskDatos.onPostExecute(AsyncTaskDatos.java:25)
> at android.os.AsyncTask.finish(AsyncTask.java:636)
> at android.os.AsyncTask.access$500(AsyncTask.java:177)
> at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
> at android.os.Handler.dispatchMessage(Handler.java:102)
> at android.os.Looper.loop(Looper.java:155)
> at android.app.ActivityThread.main(ActivityThread.java:5725)
> at java.lang.reflect.Method.invoke(Native Method)
> at java.lang.reflect.Method.invoke(Method.java:372)
> at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1030)
> at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:825)
飞溅:
public class Splash extends Activity implements AsyncResponse {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
AsyncTaskDatos tel = new AsyncTaskDatos(Splash.this);
tel.execute();
}
@Override
public void processFinish(String output){
//Here you will receive the result fired from async class
//of onPostExecute(result) method.
}
}
异步任务:
public class AsyncTaskDatos extends AsyncTask<String, Void, String> {
private ProgressDialog dialog;
Splash activity;
public AsyncResponse delegate = null;
public AsyncTaskDatos(Splash activity) {
dialog = new ProgressDialog(activity);
this.activity = activity;
}
@Override
protected void onPreExecute() {
dialog.setMessage("Cargando datos por favor espere");
dialog.show();
}
@Override
protected void onPostExecute(String result) {
if (dialog.isShowing()) {
dialog.dismiss();
delegate.processFinish(result);
}
}
@Override
protected String doInBackground(String... params) {
String res = "1";
} catch (InterruptedException e) {
e.printStackTrace();
}
return res;
}
}
}
异步响应:
public interface AsyncResponse {
void processFinish(String output);
}
如何在我的 Activity 中获取我的 AsyncTask 的 onPostExecute 方法的返回值?正是使用您声明的接口:
在您的 Asynctask 中,您为接口定义一个变量,该变量将在 Asynctask 执行结束时调用
onPostExecute()
:您的这部分是正确的,但是错误中提到了该问题,表明:
这意味着接口实例
AsyncResponse
没有初始化!添加一个接收这个实例的构造函数:这样,在 tu 方法中,
processFinish()
您Activity
将获得在onPostExecute()
tu方法中获得的值Asynctask
: