I've been reading lots of questions and answers on Stckoverflow. But still can't find when do I actually use adapter.notifyDataSetChanged
.
Previously, after adding all items into an ArrayList, I did
adapter = new ListViewAdapter(MainActivity.this, menuItems);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
It had no crashes AT ALL on my phone, emulators and only a minority had this crash.
Then, I did.
adapter = new ListViewAdapter(MainActivity.this, menuItems);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
Same result as above.
But I hate crashes. I hate that people downloading my apps have FCs. And then I tried this, knowing that maybe the adapter have to refresh, THEN I can set a new one.
adapter.notifyDataSetChanged();
adapter = new ListViewAdapter(MainActivity.this, menuItems);
lv.setAdapter(adapter);
And the result is that after scrolling down a few pages [never-ending listview], it crashes on my phone.
Maybe it's me who don't understand. But when do we ACTUALLY use adapter.notifyDataSetChanged
?
And if it helps, this is my full code.
`
private class firstLoad extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
setSupportProgressBarIndeterminateVisibility(true);
if (lv.getVisibility() == View.VISIBLE) {
lv.setVisibility(View.GONE);
}
}
protected Void doInBackground(Void... unused) {
try {
xml = parser.getXmlFromUrl(getURLFromXML + "main.php");
doc = parser.getDomElement(xml);
NodeList nl = doc.getElementsByTagName(Consts.KEY_ITEM);
for (int i = 0; i < nl.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
map.put(Consts.KEY_NAME,
parser.getValue(e, Consts.KEY_NAME));
map.put(Consts.KEY_DATE,
parser.getValue(e, Consts.KEY_DATE));
menuItems.add(map);
}
} catch (Exception e) {
Log.e(TAG, "Error loading first page", e);
}
return (null);
}
protected void onPostExecute(Void unused) {
setSupportProgressBarIndeterminateVisibility(false);
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
//adapter.notifyDataSetChanged();
adapter = new ListViewAdapter(MainActivity.this,
menuItems);
lv.setAdapter(adapter);
lv.setVisibility(View.VISIBLE);
loadingMore = false;
lv.setSelectionFromTop(0, 0);
lv.setOnScrollListener(new OnScrollListener() {
public void onScrollStateChanged(AbsListView view,
int scrollState) {
}
public void onScroll(AbsListView view,
int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
int lastInScreen = firstVisibleItem
+ visibleItemCount;
if ((lastInScreen == totalItemCount)
&& !(loadingMore)) {
new loadMoreListView().execute();
}
}
});
}
});
}
}`
Thanks in advance.