此代码正常运行,但当我跳转到另一个片段时,正在执行几次次。
例如,这是第一个片段,如果我转到第三个(或者例如第四个“差异多个片段”)并返回到首先,它将再次执行onCreateView()。
我知道这是正常的,我想我想将它更改为onCreate()方法,但在我的情况下,我想我会得到空值,因为还没有任何UI(例如获取微调器)。
想法是从php webservice 填充微调器。
有什么想法解决这个问题吗?谢谢你的帮助。
public class ProfessoresFragment extends Fragment {
private Spinner spinnerProfessores;
// array list for spinner adapter
private ArrayList<Teacher> TeacherList;
ProgressDialog pDialog;
// API urls
// Url to get all teachers
private String URL_TEACHERS = "http://10.0.2.2/android/GetAllTeachersJson.php";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_professores, container, false);
spinnerProfessores = (Spinner) rootView.findViewById(R.id.spinner);
TeacherList = new ArrayList<Teacher>();
new GetTeachers().execute();
return rootView;
}
/**
* Adding spinner data
* */
private void populateSpinner() {
List<String> lables = new ArrayList<String>();
for (int i = 0; i < TeacherList.size(); i++) {
lables.add(TeacherList.get(i).getProfessor());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerProfessores.setAdapter(spinnerAdapter);
}
private class GetTeachers extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("A processar professores..");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_TEACHERS, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray teachers = jsonObj
.getJSONArray("professores");
for (int i = 0; i < teachers.length(); i++) {
JSONObject TeaObj = (JSONObject) teachers.get(i);
Teacher Tea = new Teacher(TeaObj.getInt("Cod_Professor"),
TeaObj.getString("Professor"));
TeacherList.add(Tea);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
}
}
}
答案 0 :(得分:1)
当您离开Fragment
时,请将其删除,以便下次访问时使用FragmentMananger
和Transaction