1

I have a ListView that I am trying to update from a database after adding to the database.

While the data is into the List, and also getting into the ListView, the ListView isn't updating the number of items in the List.

So if my list was {1, 3, 6, 8, 12} After adding 4 to the List and sorting, my list view shows {1, 3, 4, 6 ,8} not showing the 6th item 12.

This problem compounds itself as I add more to the list, where if I were to add another item, this ListView would still only show the first 5.

Here is the code area having problems

TourGroup group = data.getParcelableExtra(TOURGROUP);

DatabaseHandler db = new DatabaseHandler(this);
db.addGroup(group);

mainList = db.getAllGroups();

db.close();

Collections.sort(mainList, new CustomComparator());

ListView groupList = (ListView) findViewById(R.id.groupList);
ArrayAdapter adapter = (ArrayAdapter) groupList.getAdapter();
adapter.notifyDataSetChanged();

If I replace

mainList = db.getAllGroups();

With

mainList.add(group);

then the ListView updates correctly. But this is not the solution I want, as this wouldn't be updating the List view from the database.

I've been banging my head on this problem for hours now, any help would be appreciated.

2
  • What is the data type returned by db.getAllGroups() Commented Jul 11, 2013 at 21:49
  • If the problem is at mainList = db.getAllGroups(), then you'll have to show us the implementation of getAllGroups(). For all we know, it could be doing a ton of bad things. Commented Jul 11, 2013 at 21:56

1 Answer 1

3

But this is not the solution I want, as this wouldn't be updating the List view from the database.

Your ArrayAdapter is wrapping around some ArrayList. Whatever that ArrayList is, it is not the ArrayList returned by getAllGroups(). There, I am willing to bet that you just created a new ArrayList. If so, your ArrayAdapter does not know about any of the changes you made to the database, because it's a different ArrayList.

Either:

  • Update your existing ArrayList, or

  • Use add(), addAll(), clear(),insert(),remove(), and/orsort()on yourArrayAdapter(which also saves you the trouble of callingnotifyDataSetChanged()`, or

  • Create a new ArrayAdapter for your new ArrayList and attach the new ArrayAdapter to your ListView

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you I got it to work with mainList.clear(); mainList.addAll(db.getAllGroups()); I hope this is an appropriate way to do it.
@bleem313: That should be OK.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.