【发布时间】:2015-08-13 03:56:15
【问题描述】:
我有一个包含列表视图的片段,它使用 Volley 从网络获取数据,并在响应时,使用自定义数组适配器将检索到的列表显示在列表视图中。
问题是第一次加载时,一切正常;但是当关闭活动并返回时,列表视图永远不会在响应时刷新。我需要强制关闭应用程序才能让它再次工作。我注意到的一件事是 getActivity() 在这个阶段为空。 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();
}
更新一:看来是调用了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() 在此阶段为空。如果我将指针引用用作片段中的属性,则不会发生这种情况。不确定这是否会导致原始问题
【问题讨论】:
-
这可能是因为当你回到活动时它会运行 OnResume 方法。尝试在 onResume 方法中重新加载数据。
-
不,它不会预算...出现加载项,但不显示数据。活动、列表视图和适配器不为空,并且数据存在。它只是神秘地从未出现在展览中。请注意,我每次都从网络重新获取数据。
-
使用 Onreusme 调用你的网络数据..
-
感谢您的了解!不幸的是,问题仍然存在......
-
放一些log看看reload data函数是否被调用,也放一些log到adapter的getView函数中,看看notifyDataSetChanged()函数后data数组的样子跨度>
标签: android listview android-fragments android-listview android-volley