In my activity there is a listview containing lines of a text file. To populate this listview i created an arrayadapter in the onCreate(Bundle savedInstanceState) method. The listview is populated with items if there are lines in the file. The arrayadapter part looks like this:
final ListView lv1 = (ListView) findViewById(R.id.ListView01);
ArrayAdapter<String> adapter1;
adapter1 = new ArrayAdapter<String>(Main.this,R.layout.list_black_text,R.id.list_content, assignArr0);
lv1.setAdapter(adapter1);
adapter1.notifyDataSetChanged();
Then by clicking on Menu item1 (so now we are outside the onCreate(Bundle savedInstanceStat) method i write one line in the text file. For now everything works fine. If i exit and reopen the app the new line appears in the listview. But the listview is not refreshed after adding the new line, so at the end of the " case R.id.Menu1:" part.
So after adding one line to the file I want to refresh the listview by reading the lines from the file to an array then populating the listview with that array. Problem is that i cannot do that, even if i put the ArrayAdapter<String> adapter1;
line outside the onCreate() method where the other arrays and variables are declared.
It does not see the listv开发者_开发百科iew (lv1 cannot be resolved). If i define the ListView where the other variables are (ListView lv1;) this whole part of the program is not working.
I also need to empty the listview (the adapter?) by adapter1.clear();
or sg before populating it.
Any ideas are welcome.
If you need those variables to be global, you should declare them as
private final ArrayList<String> assignArr0 = new ArrayList<String>();
private ListView lv1;
private ArrayAdapter<String> adapter1;
@Override
public void onCreate(Bundle icicle)
{
lv1 = (ListView) findViewById(R.id.ListView01);
adapter1 = new ArrayAdapter<String>(Main.this,R.layout.list_black_text,
R.id.list_content, assignArr0);
lv1.setAdapter(adapter1);
}
You should set the adapter to the ListView
only one time, inside the onCreate
method of your activity, and the notifiyDatasetChanged
should be called after you made changes to the list (the array used in your ListAdapter
).
Say you have a method to add the recently read lines not yet included in your list. After adding the lines to the ArrayList
used in the ListAdapter
, you should call the notifyDatasetChanged
method, to visualize the new items in the ListView
:
private void addLinesToList(final String... newLines)
{
assignArr0.addAll(Arrays.asList(newLines));
adapter1.notifyDataSetChanged();
}
If you are reading the whole file every time it changes, and populate it from top (not just inserting the new lines), you have to first remove all the elements of the list, so the first line of the addLinesToList
method should be:
assignArr0.clear();
精彩评论