我有一个包含listview的片段,它使用Volley从网络中获取数据,并且在响应时,检索到的列表使用自定义arrayadapter显示在listview中。
问题是第一次加载时,一切正常;但是当关闭活动并返回时,列表视图永远不会在响应时刷新。我需要强制关闭应用程序才能再次使用它。我注意到的一件事是getActivity()在这个阶段是null。 this.activity不是。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_interests, container, false);
// Set the adapter
mListView = (AbsListView) view.findViewById(android.R.id.list);
((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter);
// Set OnItemClickListener so we can be notified on item clicks
mListView.setOnItemClickListener(this);
return view;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SelectionListContent.getItems().clear();
SelectionListContent.ITEMS.add(new SelectionListContent.Item("0", "Loading...", false));
mAdapter = new SelectionListViewAdapter(this.activity,
R.layout.listviewcheckbox, SelectionListContent.ITEMS);
}
@Override
public void onResume() {
super.onResume();
CategoriesData.getInstance(this.activity, new CategoriesData.CategoriesDataListener() {
@Override
public void gotCategories(List<HashMap<String, Object>> categories) {
InterestsFragment.this.categories = categories;
reloadtable();
}
}).getCategories();
}
public void reloadtable() {
SelectionListContent.ITEMS.clear();
Object interests = ParseUser.getCurrentUser().get("interests");
List<HashMap<String, String>> selected = new ArrayList<HashMap<String, String>>();
if (interests != null) {
selected = (List<HashMap<String, String>>) interests;
}
for (HashMap<String, Object> obj : categories) {
boolean found = false;
for (HashMap<String, String> o : selected) {
if (o.containsKey(obj.get("id").toString())) {
found = true;
}
}
SelectionListContent.Item i = new SelectionListContent.Item((String) obj.get("id"), (String) obj.get("name"), found);
SelectionListContent.ITEMS.add(i);
}
mListView.destroyDrawingCache();
mListView.setVisibility(ListView.INVISIBLE);
mListView.setVisibility(ListView.VISIBLE);
((ArrayAdapter)mAdapter).notifyDataSetChanged();
}
更新1:似乎调用了notifyDataSetChanged(),在第二次获取数据后,适配器内的getView()停止被调用。
更新2:尝试将notifyDataSetChanged()更改为
mAdapter = new SelectionListViewAdapter(getActivity(),
R.layout.listviewcheckbox, SelectionListContent.ITEMS);
mListView = (AbsListView) view.findViewById(android.R.id.list);
((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter);
它在第一行崩溃了。 getActivity()在此阶段为null。如果我使用作为片段中的属性保存的指针引用,则不会发生这种情况。不确定这是否会导致原始问题
答案 0 :(得分:0)
((ArrayAdapter)mAdapter).notifyDataSetChanged();
在此之前使用此
mAdapter.clear();
mAdapter.addAll(newlist);
((ArrayAdapter)mAdapter).notifyDataSetChanged();