我正在尝试将一些 AsyncTask 类拆分为公共(单独的)函数,这样我就不必重写这么多代码。我几乎拥有它,除了一个非常重要的方面。AsyncTask 函数通过对服务器进行 php 调用来编译 ArrayList。完成此列表后,我需要更新主 UI 线程上的微调器。我在这里找到了一个非常好的答案,但我很难让它发挥作用。
这是我所拥有的缩小版本:(请注意,此时,我要做的只是调用一条Toast
消息来证明往返行程有效)
这是调用Activity
:
public class MyActivity extends Activity implements OnTaskCompleted {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sg_list = new ArrayList<String>();
new GetSuperGroups(UpdateAffiliationsPreferences.this, context, "Retrieving Group List...").execute();
}
public void onTaskCompleted(ArrayList<String> list) {
Toast.makeText(getApplicationContext(), "hello from async", Toast.LENGTH_SHORT).show();
}
}
这是界面:
public interface OnTaskCompleted {
void onTaskCompleted(ArrayList<String> list);
}
最后,这是AsyncTask
. 请注意,它是一个公共类:
public class GetSuperGroups extends AsyncTask<String, String, ArrayList<String>> {
private Activity activity;
private Context context;
private String progressMsg;
private ProgressDialog pDialog;
private ArrayList<String> sg_list;
private OnTaskCompleted listener;
public GetSuperGroups(Activity activity, Context context, String progressMsg) {
this.activity = activity;
this.context = context;
this.progressMsg = progressMsg;
}
public void setSuperGroupList (OnTaskCompleted listener){
this.listener = listener;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage(progressMsg);
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected ArrayList<String> doInBackground(String... args) {
sg_list = new ArrayList<String>();
//make a php call, compile the ArrayList
return sg_list;
}
protected void onPostExecute(ArrayList<String> sg_list) {
pDialog.dismiss();
//this next line causes a null pointer error
//note that I am throwing away the array list for now
//all I want to do is prove that I can call the Toast back in the calling Activity
listener.onTaskCompleted(new ArrayList<String>());
}
}