使用sharepreferences 1、创建名诗词数据表,字段主要包括:id、题名、作者姓名、全文。 2、实现添加、查询、修改、删除诗词信息的功能。
时间: 2023-09-29 08:07:33 浏览: 169
以下是使用SharedPreferences实现诗词数据表的示例代码:
1. 创建名诗词数据表,字段主要包括:id、题名、作者姓名、全文。
```java
public class Poem {
private int id;
private String title;
private String author;
private String content;
public Poem(int id, String title, String author, String content) {
this.id = id;
this.title = title;
this.author = author;
this.content = content;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getContent() {
return content;
}
}
```
2. 实现添加、查询、修改、删除诗词信息的功能。
```java
public class PoemManager {
private static final String POEM_PREFS_NAME = "poem_prefs";
private static final String POEM_KEY_PREFIX = "poem_";
private Context mContext;
private SharedPreferences mPrefs;
public PoemManager(Context context) {
mContext = context;
mPrefs = context.getSharedPreferences(POEM_PREFS_NAME, Context.MODE_PRIVATE);
}
public void addPoem(Poem poem) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString(POEM_KEY_PREFIX + poem.getId(), poemToString(poem));
editor.apply();
}
public Poem getPoem(int id) {
String poemString = mPrefs.getString(POEM_KEY_PREFIX + id, null);
if (poemString != null) {
return stringToPoem(poemString);
}
return null;
}
public void updatePoem(Poem poem) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString(POEM_KEY_PREFIX + poem.getId(), poemToString(poem));
editor.apply();
}
public void deletePoem(int id) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.remove(POEM_KEY_PREFIX + id);
editor.apply();
}
public List<Poem> getAllPoems() {
List<Poem> poemList = new ArrayList<>();
Map<String, ?> allEntries = mPrefs.getAll();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
if (entry.getKey().startsWith(POEM_KEY_PREFIX)) {
Poem poem = stringToPoem((String) entry.getValue());
if (poem != null) {
poemList.add(poem);
}
}
}
return poemList;
}
private String poemToString(Poem poem) {
return poem.getId() + "," + poem.getTitle() + "," + poem.getAuthor() + "," + poem.getContent();
}
private Poem stringToPoem(String poemString) {
String[] parts = poemString.split(",");
if (parts.length == 4) {
int id = Integer.parseInt(parts[0]);
String title = parts[1];
String author = parts[2];
String content = parts[3];
return new Poem(id, title, author, content);
}
return null;
}
}
```
使用示例:
```java
// 创建诗词管理器
PoemManager poemManager = new PoemManager(context);
// 添加诗词
Poem poem = new Poem(1, "静夜思", "李白", "床前明月光,疑是地上霜。举头望明月,低头思故乡。");
poemManager.addPoem(poem);
// 查询诗词
Poem queriedPoem = poemManager.getPoem(1);
// 修改诗词
if (queriedPoem != null) {
queriedPoem.setTitle("静夜思(改)");
poemManager.updatePoem(queriedPoem);
}
// 删除诗词
poemManager.deletePoem(1);
// 获取所有诗词
List<Poem> poemList = poemManager.getAllPoems();
```
阅读全文