我有一个对象,MyObject
它自己填充了一些随机数。它不需要很长时间,似乎是瞬间的。但是,这些值在 UI 上使用,有时在 UI 构建时它还没有完全准备好。
我创建了一个AsyncTask
用于实例化对象的对象,它位于本文的末尾。
但是,在以这种方式调用doInBackground(...)
之前,不会完全实例化对象。onPostExecute(...)
protected MyObject doInBackground(Void... unused) {
// this may take a few moments and cause a null reference
// so make a task
MyObject obj = new MyObject();
return obj;
}
我也尝试使用标志来表示完成,但它似乎也不能保证。
MyObject obj = new MyObject();
while (obj.isComplete() == false) {
// do nothing. Wait for completion
}
return obj;
里面MyObject
很简单
public MyObject() {
createValues(); // entire object created with this
this.mComplete = true;
}
它失败得更少,但仍然失败。如果这有助于竞争条件,则将其用于其计算的一部分createValues()
。ArrayList
下面是一个MyFragment
使用 中的任务的示例methodCall()
。
问题我如何简单地等到MyObject
完全实例化结束?
堆栈跟踪
java.lang.NullPointerException
at MyFragment.setupFragment(MyFragment.java:95)
at MyFragment.onTaskComplete(MyFragment.java:143)
at MyTask.onPostExecute(MyTask.java:37)
at MyTask.onPostExecute(MyTask.java:1)
at android.os.AsyncTask.finish(AsyncTask.java:631)
分段
public class MyFragment extends Fragment implements MyTask.OnTaskComplete {
private MyObject mMyObject;
// ...
public void methodCall() {
// generate puzzle and set it up in the background
MyTask task = new MyTask(this);
task.execute();
}
function void setupFragment() {
// null pointer exception here
// mMyObject is not initiated yet and only some times
// values is an array of integers
int example = this.mMyObject.values[0];
}
@Override
public void onTaskComplete(MyObject obj) {
// returned from MyTask
this.mMyObject = obj;
this.setupFragment();
}
}
异步任务
public class MyObjectTask extends AsyncTask<Void, Void, MyObject> {
public static interface OnTaskComplete {
public abstract void onTaskComplete(MyObject obj);
}
static final String TAG = "MyObjectTask";
private OnTaskComplete mListener;
public MyObjectTask(OnTaskComplete listener) {
this.mListener = listener;
}
@Override
protected MyObject doInBackground(Void... unused) {
// this may take a few moments and cause a null reference
// so make a task
return new MyObject();
}
@Override
protected void onPostExecute(MyObject obj) {
this.mListener.onTaskComplete(obj);
}
}