我正在開發一個詞典應用程序。有上,允許用戶應用程序收藏夾按鈕:如何在Android中寫入和讀取文本文件?
- 短點擊當前觀看的單詞添加到收藏夾列表;
- 長按可查看收藏夾列表(添加的單詞)。
到目前爲止,我已經編碼如下:
更新的代碼:
//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不會退出(數據/數據/ MY_PROJECT /文件在Eclipse中),但它僅包含一個最近增加的單詞。此外,當長按「收藏夾」按鈕時,應用程序會強制關閉。
有什麼我已經做錯了嗎?如果你們能幫我解決這個問題,我非常感激。非常感謝你。
========
編輯
非常感謝您的幫助。我更新了我的代碼以反映您的意見和提示。截至目前,已經有一些改進:最喜歡的詞已被寫入到文件myFavourite.txt像單詞2單詞2 WORD3 ...(不過我希望他們能夠出現在新的生產線)。
然而,當收藏夾按鈕是長期的點擊仍然沒有加載收藏夾列表。
事實上,我的目的是使人們有可能加載應用程序內的收藏夾列表,並允許用戶選擇字(S)再次擡頭。
非常感謝您的幫助。
'openFileOut'方法在上下文中定義,並且大概這個代碼存在於一個活動中。 –
啊,不知道Android本身,但這確實回答了我的水晶球問題:) –
@Mark Rotteveel:非常感謝您的幫助。請查看我的更新代碼,這些代碼可以反映您的意見。 –