我试图ListView
在下载JSON数据后更新数据,但它没有用,因为onCreate
方法onCreateView
只在第一次工作。当我将调试点指向这两种方法时,我注意到了这一点,但调试行从未进入那里。响应 json 正确,但无法通过解析更新 UI 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
'sonSuccess
方法。
@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 第一次只发生一次,因为它与Utils.replaceFragment() 中的BackStack和事务内容混淆。
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();
}
}
有什么帮助吗?