在我的应用程序中,当用户单击“添加”菜单按钮时,将显示列表视图,其中包含从文本文件加载的项目。 所以现在用户可以再添加一个项目到列表视图。将它添加到数组后,新项目将写入文本文件,但不会进入listview,因为我想通过将文件读取到数组来完成它,然后用它填充ListView。问题是这不起作用。填充的arrayadapter位于onCreate(Bundle savedInstanceState){}方法中,但是添加位于其外部,因为通过按菜单调用它。
public class Connection extends Activity {
ListView lv1;
ArrayList<String> assignArr0 = new ArrayList<String>();
ArrayList<String> assignArr00 = new ArrayList<String>();
ArrayAdapter<String> adapter1;
ArrayAdapter<String> adapter2;
public void onCreate(Bundle savedInstanceState) {
...
//filereading to assingArr0. Lines of the file are added to the listview.
lv1 = (ListView) findViewById(R.id.ListView01);
adapter1 = new ArrayAdapter<String>(Connection.this,R.layout.list_black_text,R.id.list_content, assignArr0);
lv1.setAdapter(adapter1);
adapter1.notifyDataSetChanged();
//now, if there were any lines in the text file, the ListView is populated with them.
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.Menu1:
//this is where user adds an item to an array and item gets written out to the text file
//and this is also the part where the listview should be cleared, the lines of the text file should be read into an array, and the listview should be populated with the items of that array.
//The filereading is ok. Lines are read into assignArr00. Now what?
break;
}
return true;
}
}
这是我在将行读入assignArr00后尝试这样做的方式:
if (fileisempty == false) //i set this boolean var at the beginning
{
adapter1.clear();
// adapter1 = new ArrayAdapter<String>(Connection.this,R.layout.list_black_text,R.id.list_content, assignArr00);
//lv1.setAdapter(adapter1);
//adapter1.notifyDataSetChanged();
}
else
{
adapter1 = new ArrayAdapter<String>(Connection.this,R.layout.list_black_text,R.id.list_content, assignArr00);
lv1.setAdapter(adapter1);
adapter1.notifyDataSetChanged();
}
}
最后一个代码的else部分导致强制关闭(不要忘记这是第一次运行,因此文本文件为空,这就是为什么else部分被激活。
我对这件事情不太确定。 也许声明在错误的地方。
感谢任何帮助。
编辑:我已设法解决它。解决方案可以在下面找到。
答案 0 :(得分:0)
找到了解决办法:我不得不重新宣布lv1 = (ListView) findViewById(R.id.ListView01);
我不是这背后的原因,但我花了4个小时才找到它。
if (fileisempty == false)
{
adapter1.clear();
adapter1.notifyDataSetChanged();
lv1 = (ListView) findViewById(R.id.ListView01);
ArrayAdapter<String> adapter11;
adapter11 = new ArrayAdapter<String>(Connection.this,R.layout.list_black_text,R.id.list_content, assignArr00);
lv1.setAdapter(adapter11);
adapter11.notifyDataSetChanged();
}
else
{
lv1 = (ListView) findViewById(R.id.ListView01);
ArrayAdapter<String> adapter11;
adapter11 = new ArrayAdapter<String>(Connection.this,R.layout.list_black_text,R.id.list_content, assignArr00);
lv1.setAdapter(adapter11);
adapter11.notifyDataSetChanged();
}