如何获得AsyncTask的结果来启动另一个活动?这个异步任务看起来很不舒服。。。现在,在onPostExecute完成之前,它会启动没有结果的活动。这怎么能等到它完成而不必重写整个代码呢?
public class MainFragment extends Fragment implements InsertAsyncTask.AsyncInsertTaskCompleteListener {
private Repository mRepository;
private String data;
private int codeId;
private int editMode = 0;
private Context mContext;
private FragmentMainBinding binding;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this.getContext();
mRepository = new Repository(mContext);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.mainfragment, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
binding = FragmentMainBinding.bind(view);
binding.createFormSaveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String text = binding.codeCreateFormTextInput.getText().toString().trim();
if (!text.equals("")){
create("save data");
Intent intent = new Intent(mContext.getApplicationContext(), NextActivity.class);
intent.putExtra("code_id", codeId);
mContext.startActivity(intent);
}
}
}
private void create(String data){
if (editMode == 1){
//updated data to DB
updateCode(data);
} else {
//save data to DB
save(data);
}
}
public void save(String data){
mRepository.insertTask(data, MainFragment.this);
}
@Override
public void onInsertTaskComplete(long[] id) {
if (id[0] > 0){
codeId = (int) id[0];
}
}
}
Repository.java:
public void insertTask(String data, InsertAsyncTask.AsyncInsertTaskCompleteListener mListener) {
new InsertAsyncTask(myDatabase.getCDao(), mListener).execute(data);
}
InsertAsyncTask.java:
public class InsertAsyncTask extends AsyncTask<String, Void, Long> {
private static final String TAG = "InsertAsyncTask";
private cDao mCDao;
private AsyncInsertTaskCompleteListener callback;
private long[] insertId;
public InsertAsyncTask(CDao dao, AsyncInsertTaskCompleteListener cb) {
mCDao = dao;
this.callback = cb;
}
@Override
protected void onPostExecute(Long aLong) {
super.onPostExecute(aLong);
if (callback != null) {
callback.onInsertTaskComplete(insertId);
}
}
@Override
protected Long doInBackground(String... datas) {
insertId = mCDao.insertCode(datas);
return null;
}
public interface AsyncInsertTaskCompleteListener {
void onInsertTaskComplete(long[] id);
}
}
将顶部codeId
的值初始化为
private int codeId = -1;
然后在onViewCreated
内将您的条件更改为:
if (codeId != -1){
create("save data");
Intent intent = new Intent(mContext.getApplicationContext(), NextActivity.class);
intent.putExtra("code_id", codeId);
mContext.startActivity(intent);
}
现在应该可以了。