我开始编写用于记笔记的应用程序,例如 Evernote 或基本的预装备忘录应用程序,以便我可以学习和练习编码。
目前我将用户输入保存在一个 .txt 文件中,这样每个笔记在存储中都会有一个自己的文本文件,其中包含笔记内容。 还有哪些其他方法可以将用户输入保存在存储中(您无需解释,关键字就可以),这样做的优点或缺点是什么?像我现在这样保存文本文件有什么缺点?
最佳答案
- 将内容保存到应用缓存中的文件
- 如果内容是纯文本(并且不太长),您可以轻松地使用
SharedPreferences
来保存内容 - 你可以使用数据库
请注意,如果内容是富文本,您可以对其进行格式化(例如,使用 HTML、JSON 或 XML 并将文件(如图像)保存在指定文件夹中,并将文件的位置写入格式化的文本),然后保存到数据库。
入门的有用链接:
使用数据库:
- https://developer.android.com/training/data-storage/sqlite
- https://developer.android.com/training/data-storage/room
- https://www.tutorialspoint.com/android/android_sqlite_database.htm
富文本编辑器:
如何获取缓存目录?
File cacheDir = this.getCacheDir();
或
File cacheDir = this.getApplicationContext().getCacheDir();
请注意,如果内容很重要,您可以在存储中创建一个新文件夹(如“我的应用名称文件”)并将内容保存到该文件夹中。
如果您使用的是 EditText:
我将 EditText 命名为 uinput
。我们开始吧:
private void saveContent() {
String content = uinput.getText().toString();
String name = "Note 1"; // You can create a new EditText for getting name
// Using SharedPreferences (the simple way)
SharedPreferences sp = this.getApplicationContext().getSharedPreferences("notes", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString(name, content);
editor.apply();
}
private Map<String, ?> getAllNotes() {
SharedPreferences sp = this.getApplicationContext().getSharedPreferences("notes", Context.MODE_PRIVATE);
return sp.getAll();
}
private String getNoteContent(String noteName) {
SharedPreferences sp = this.getApplicationContext().getSharedPreferences("notes", Context.MODE_PRIVATE);
return sp.getString(noteName, "Default Value (If not exists)");
}
不要在 SharedPreferences "notes"
中保存其他内容。
关于java - 保存笔记等用户输入的方法(Android Studio/Java编程)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58219395/