I'm developing a Dictionary app. There is a Favourite button on the app that allows users to:
- short-click to add the currently-viewed word into the Favourite list;
- long-click to view the Favourite list (of added words).
So far, I have coded as follows:
UPDATED CODE:
//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;
}});
}
However, the Favourite button does not work with the above code lines.
The file myFavourite.txt does exits (in data/data/my_project/files in Eclipse) but it only contains one recently added word. Furthermore, the app is force-closed when the Favourite button is long-clicked.
What have I been doing wrong? I am very grateful if you guys can help me solve this problem. Thank you very much.
========
EDIT
Thank you very much for your help. I updated my code to reflect your comments and prompts. By now, there have been some improvements: The Favourite words have been written to the file myFavourite.txt like word2 word2 word3... (though I want them to appear in new lines).
However, the Favourite list is still not loaded when the Favourite button is long-clicked.
In fact, my purpose is to make it possible to load the Favourite list inside the app and allow users to choose the word(s) to look up again.
Many thanks for your help.