我正在制作一个测验应用程序,可以向用户显示一张具有先前测验结果的表格。我正在尝试用AsyncTask
填充表,但问题是onCreateView()方法在AsyncTask
之前完成,所以我得到了一个空表。我已经能够在不使用AsyncTask
的情况下动态添加行,所以我确定问题出在我使用该类的方式上。这是应用程序这一部分的片段:
public class GalleryFragment extends Fragment {
private GalleryViewModel galleryViewModel;
private QuizAppData quizAppData;
private List<QuizResults> resultsList;
private TableLayout table;
private QuizResultsReader reader;
public TableRow addNewEntry(Context context, String user, String date, String score) {
QuizHistoryTableRow row = new QuizHistoryTableRow(context, user, date, score);
row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
return row;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View root = getLayoutInflater().inflate(R.layout.fragment_gallery, null, false);
table = root.findViewById(R.id.quiz_history_table);
quizAppData = new QuizAppData(getContext());
reader = new QuizResultsReader();
reader.execute(getContext());
}
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_gallery, container, false);
return root;
}
private class QuizResultsReader extends AsyncTask<Context,Void,Void> {
@Override
protected Void doInBackground(Context... context) {
android.os.Debug.waitForDebugger();
openAppData();
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
final String DEBUG_TAG = "onPostExecute";
populateTable();
Log.d( DEBUG_TAG, " QuizResults retrieved");
}
}
public void openAppData() {
android.os.Debug.waitForDebugger();
String TAG = "QuizResults reader";
try {
quizAppData.open();
resultsList = quizAppData.retrieveAllQuizResults();
}
catch (Exception e){
Log.e(TAG,e.toString());
}
}
public void populateTable() {
String user, date, score;
for (QuizResults results: resultsList) {
user = results.getUsername();
date = results.getDate();
score = results.getResult();
TableRow row = addNewEntry(getContext(), user, date, score);
table.addView(row, new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
}
TableRow row = addNewEntry(getContext(), "user", "date", "score");
table.addView(row, new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
quizAppData.close();
}
}
我已尝试在onCreateView方法中使用AsyncTask.get()
以确保任务已完成,但这会导致应用程序冻结。在这个问题上的任何帮助将不胜感激。
在onViewCreated()
中执行AsyncTask调用。在onViewCreated()
方法中移动以下几行:
quizAppData = new QuizAppData(getContext());
reader = new QuizResultsReader();
reader.execute(getContext());
并在table
中初始化onCreateView ()
对象>>