我正在开发一个字典应用程序。应用程序上有一个收藏按钮,允许用户:
- 短按将当前查看的单词添加到收藏夹列表中;
- 长按查看收藏列表(添加的单词)。
到目前为止,我的编码如下:
更新代码:
//Writing lines to myFavourite.txt
btnAddFavourite = (ImageButton) findViewById(R.id.btnAddFavourite);
btnAddFavourite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Writing the content
try {
// opening myFavourite.txt for writing
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("myFavourite.txt", MODE_APPEND));
// writing the ID of the added word to the file
out.write(mCurrentWord);
// closing the file
out.close();
} catch (java.io.IOException e) {
//doing something if an IOException occurs.
}
Toast toast = Toast.makeText(ContentView.this, R.string.messageWordAddedToFarvourite, Toast.LENGTH_SHORT);
toast.show();
}
});
//Reading lines from myFavourite.txt
btnAddFavourite.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
//trying opening the myFavourite.txt
try {
// opening the file for reading
InputStream instream = openFileInput("myFavourite.txt");
// if file the available for reading
if (instream != null) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
// reading every line of the file into the line-variable, on line at the time
try {
while ((line = buffreader.readLine()) != null) {
// do something with the settings from the file
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// closing the file again
try {
instream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (java.io.FileNotFoundException e) {
// ding something if the myFavourite.txt does not exits
}
return false;
}});
}
但是,收藏按钮不适用于上述代码行。
文件myFavourite.txt确实存在(在 Eclipse 中的 data/data/my_project/files 中),但它只包含一个最近添加的单词。此外,当长按收藏按钮时,应用程序会被强制关闭。
我做错了什么?如果你们能帮我解决这个问题,我将不胜感激。非常感谢。
========
编辑
非常感谢您的帮助。我更新了我的代码以反映您的评论和提示。到现在为止,已经有了一些改进: 最喜欢的单词已被写入文件myFavourite.txt,如word2 word2 word3 ...(尽管我希望它们出现在新行中)。
但是,当长按收藏按钮时,收藏列表仍未加载。
事实上,我的目的是让在应用程序中加载收藏夹列表并允许用户选择要再次查找的单词成为可能。
非常感谢您的帮助。