我写了一个简单的应用程序,它只有一个MainActivity
.
MainActivity
有 onlyListView
和 simpleArrayAdapter
显示整数。
当用户add
从菜单中单击按钮时,再添加一个值并将listView
所有整数保存在文件中。
当用户单击时,正如预期的那样,从But nothing done to filedelete
中删除了一个值。
这是一个完整的代码:listview
public class MainActivity extends Activity {
private ArrayList<Integer> list;
private static final String fileName = "any_path";
private int ADD_ID = 0;
private int DELETE_ID = 1;
ArrayAdapter<Integer> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
load();
ListView view = new ListView(this);
setContentView(view);
adapter = new ArrayAdapter<Integer>(this,android.R.layout.simple_list_item_1, list);
view.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, ADD_ID,1, "Add");
menu.add(0, DELETE_ID,0, "Delete");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == ADD_ID) { // if add was clicked
adapter.add(adapter.getCount());
save(); // SAVING HAPPENS HERE
return true;
} else if (item.getItemId() == DELETE_ID) {
list.remove(list.size()-1);
adapter.notifyDataSetChanged();
return true; // NOTHING DONE TO FILE
} else {
return super.onOptionsItemSelected(item);
}
}
@Override
public void onStop() {
super.onStop();
save();
}
private void save() {
JSONArray array = new JSONArray();
for (int el:list) {
array.put(el);
}
Writer writer = null;
try {
OutputStream out = this.openFileOutput(fileName, Context.MODE_PRIVATE);
writer = new OutputStreamWriter(out);
writer.write(array.toString());
} catch (IOException e) {}
try {
writer.close();
} catch (IOException e) {}
}
private void load() {
list = new ArrayList<Integer>();
StringBuilder data = new StringBuilder();
BufferedReader reader = null;
try {
InputStream in = this.openFileInput(fileName);
reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
data.append(line);
}
JSONArray array = (JSONArray)new JSONTokener(data.toString()).nextValue();
for (int i=0;i<array.length(); i++)
list.add(array.getInt(i));
} catch (Exception e) {}
}
}
一切正常,但我不明白如何从文件中神奇地删除值。
更准确地说:
1)用户点击add
了五次,所以'0 1 2 3 4'将被保存在文件中:
2)用户点击delete
了两次,所以列表将是0 1 2
但文件没有任何反应
3)如果我重新启动一个我看到的应用程序0 1 2
,而不是0 1 2 3 4
为什么?