ListViewFragment (фрагмент, содержащий ListView), созданный только один раз, в первый раз

Я пытаюсь обновить ListViewданные после загрузки данных JSON, но это не сработало, потому что onCreate а также onCreateView методы работают только в первый раз. Я заметил это, когда поставил точку отладки этим двум методам, но строка отладки там никогда не вводилась. Ответ json верен, но пользовательский интерфейс не может быть обновлен при разборе ListViewFragment.init(myNewDataList), Вот мой ListViewFragment,

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, как в следующем фрагменте, это AsyncHttpClient"s onSuccess метод.

@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 ответ

В основном ваша проблема заключается в том, что вы не можете обновить список, когда вы получили последний набор информации с сервера. Я бы решил эту проблему с помощью кода ниже:

В адаптере представления списка сохраните метод, как написано ниже:

public class ListFragmentAdapter extends <your adapter extension>{

private Context context;
private List<Incident> incidents;
//constructor
public ListFragmentAdapter (Context context,List<Incident> initialIncidentList){

this.context = context;
this.incidents = initialIncidentList;
}
public void updateListFragment(List<Incident> latestIncidents){
incidents.addAll(latestIncidents);
this.notifyDataSetChanged();
}
}

Комментарий ниже, если у вас есть какие-либо сомнения

Другие вопросы по тегам