Я пытаюсь обновить данные ListView
«s после загруженных JSON данных, но это не сработало, потому что onCreate
и onCreateView
методы работают только при первый раз. Я заметил это, когда я поставил точку отладки на два метода, но строка отладки никогда туда не вводилась. Ответ json верен, но пользовательский интерфейс не может быть обновлен путем разбора ListViewFragment.init(myNewDataList)
. Вот мой ListViewFragment,ListViewFragment (фрагмент, содержащий ListView) создается только один раз, в первый раз
public class ListViewFragment extends Fragment{
ListView listView;
ArrayList<Incident> incidentLists;
public static ListViewFragment init(ArrayList<Incident> incidentLists) {
ListViewFragment listViewFragment = new ListViewFragment();
listViewFragment.setIncientLists(incidentLists);
return listViewFragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_listview, container,
false);
initUI(view);
adapter = new ListViewAdapter(getActivity(), incidentLists);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
return view;
}
public ArrayList<Incident> getIncientLists() {
return incidentLists;
}
public void setIncientLists(ArrayList<Incident> incientLists) {
this.incidentLists = incientLists;
}
}
И я анализирую данные распадаться после того, как JSON загружен как следующий фрагмент кода, это onSuccess
метод AsyncHttpClient
«s.
@Override
public void onSuccess(int statusCode, Header[] headers,
String content) {
try {
ArrayList<Incident> incidentList = new ArrayList<Incident>();
JSONObject content_ = new JSONObject(content);
JSONArray response = content_.getJSONArray("nodes");
for (int i = 0; i < response.length(); i++) {
JSONObject nodeObj = response.getJSONObject(i)
.getJSONObject("node");
Incident incident = Utils.parseNodeObjectToIncident(nodeObj);
incidentList.add(incident);
}
Fragment fragment = ListViewFragment.init(incidentList);
Utils.replaceFragment(fragment, MainActivity.this);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),"JSON Exception", Toast.LENGTH_LONG).show();
}
}
Я сомневаюсь, что мой ListViewFragment случается только один раз в первый раз, потому что это сбивает с толку с BackStack и сделкой питания на Utils.replaceFragment().
public static void replaceFragment(Fragment fragment,
AppCompatActivity activity) {
String backStateName = fragment.getClass().getName();
String fragmentTag = backStateName;
FragmentManager fragmentManager = activity.getSupportFragmentManager();
boolean fragmentPopped = fragmentManager.popBackStackImmediate(
backStateName, 0);
if (!fragmentPopped
&& fragmentManager.findFragmentByTag(fragmentTag) == null) {
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, fragment,
fragmentTag);
// fragmentTransaction.add(R.id.frame_container, fragment);
fragmentTransaction
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragmentTransaction.addToBackStack(backStateName);
// fragmentTransaction.commitAllowingStateLoss();
fragmentTransaction.commitAllowingStateLoss();
}
}
Любая помощь?
1. Почему вы overide ' 'OnCreate'' при использовании' 'Fragment'' 2. в' 'success'', вы просто обновляете значение' 'caseLists'', где вы вызываете' 'adapter.notifyDataSetChanged();' '??? –
overiding OnCreate предназначен для размещения точки отладки, если она введена или нет. Я вызываю адаптер.notifyDataSetChanged() в onCreateView. Ничего плохого? –
Потому что вы просто вызываете '' adapter.notifyDataSetChanged(); '' один раз в '' OnCreateView'', поэтому listview не обновляется после того, как вы изменили значение '' caseLists''. Попробуйте инициализировать ** Listview ** и ** адаптер ** те же ** caseLists ** и вызвать функцию '' adapter.notifyDataSetChanged(); '' при обновлении '' инцидентLists'' –