0

I am trying to update a String in a ListView, and have the update be reflected in the ListView. Here are the basics of what's going on:

testStrings = {"String", "String", String"};
ListView l = (ListView) findViewById( R.id.listView1 );
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.simple_list_item_1, testStrings);
l.setAdapter(adapter);    

Later, testStrings is update like so:

testStrings[1] = "new string";

Note, just the text is changing, not the cardinality of the String array.

On a Samsung Galaxy Nexus with Android 4.3, the text in the ListView is updated as expected, with no additional calls to the adapter.

On a Google Nexus 7 running Android 4.4.2, nothing happens. On the Nexus 7, I've tried calling notifyDataSetChanged(); on the adapter, and that doesn't do anything either.

I've seen a number of questions about ListViews not updating, but those examples seem to be doing something more complicated than what I'm trying to do. Why is one device working fine, but not the other? How do I get the ListView on the Nexus 7 updating correctly?

1 Answer 1

2

I think you need to be more direct about modifying the adapter. When I walk through the Android code that constructs ArrayAdapter using a String array, it first makes an ArrayList from your String[], and then makes the ArrayAdapter from the ArrayList. While the source does seem to point to the ArrayList and then the array, it does seem a risky proposition to expect ArrayAdapter to be aware that you have modified the String[] deep inside it. It is interesting that calling notifyDataSetChanged works on one device and not another. But I think a much better approach is to remove and then add the strings from the adapter. This way the adapter will know that something is happening to it.

adapter.remove(adapter.get(1));
adapter.insert("new string", 1);
Sign up to request clarification or add additional context in comments.

1 Comment

Hi Bruce - actually, I don't even bother calling .notifyDataSetChanged on the first devices. I just update the string array, and everything else happens automatically. The functionality has been consistent across all of the test phones I have (a variety of Android versions), as well as the emulators I've tried, just not on the Nexus 7.

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.