我想在AsyncTask中显示一个ProgressDialog,从Fragment执行。 我面临的问题是,在AsyncTask期间没有显示进度对话框,我不知道为什么。
这是AsyncTask:
public class RankTask extends AsyncTask<Void, Void, ArrayList<RowRank>> {
private ProgressDialog pDialog;
private Context context;
public RankTask(Context context) {
super();
this.context = context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected ArrayList<RowRank> doInBackground(Void... params) {
IDBInteraction interaction = new DBInteraction(
Connection.getConnection());
return interaction.getRank();
}
@Override
protected void onPostExecute(ArrayList<RowRank> result) {
pDialog.dismiss();
super.onPostExecute(result);
}
}
这是Fragment,它执行AsyncTask:
public class RankFragment extends Fragment {
private TableLayout tableLayout;
private static float SIZE_TEXT = 20;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(
com.example.testintro.R.layout.fragment_rank, container, false);
tableLayout = (TableLayout) rootView
.findViewById(R.id.table_rank_layout);
tableLayout.setStretchAllColumns(true);
tableLayout.bringToFront();
RankTask task = new RankTask(getActivity());
try {
createTable(task.execute().get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return rootView;
}
以下是Activity的代码行,其中提交了Fragment:
private void changeActivity(Button button, final Fragment fragment) {
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.replace(R.id.container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
答案 0 :(得分:1)
它与进度对话框或片段无关 你能做的唯一错误就是你正在使用
task.execute().get()
如果有必要等待计算完成,然后检索其结果。
并且当它在主线程上运行时你不能使用任何视图删除get()它应该可以正常工作
答案 1 :(得分:1)
我想..这是由于&#39; context&#39;问题..正确地传递上下文..
在片段中添加了此代码..
public Context context;
@Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
context = activity;
}