【发布时间】:2017-01-21 14:51:06
【问题描述】:
我刚刚开始使用 Android Studio,目前正在尝试制作一个简单的应用程序,让您可以做笔记并保存它们,也许还有一些“待办事项”功能。我正在尝试使用 Json / Gson 将它们存储在 SharedPreferences 中。遵循了一些在线教程,但似乎无法使其正常工作。这里的类似问题也无济于事。到目前为止,这是我的代码:
MainActivity.java:
public class MainActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NoteHandler noteHandler = new NoteHandler();
noteHandler.newNote("test", 1);
}
}
Note.java:
public class Note {
public enum State { TODO, DONE };
private String content;
private State state;
private Date date;
private int id;
private Note parent;
public Note(String content, State state, Date date, Note parent, int id) {
this.content = content;
this.state = state;
this.date = date;
this.parent = parent;
this.id = id;
}
/* Getters and setters */
}
NoteHandler.java:
public class NoteHandler {
NotePrefs notePrefs = new NotePrefs(ContextGetter.getAppContext());
void newNote(String content, int id) {
newNote(content, null, id);
}
void newNote(String content, Note parent, int id) {
Note newNote = new Note(content, Note.State.TODO, new Date(), parent, id);
notePrefs.saveNote(newNote);
}
Note getNote(int id) {
return notePrefs.loadNote(id);
}
}
NotePrefs.java:
public class NotePrefs {
private final String PREFS_NAME = "notes.NotePrefs";
private static SharedPreferences settings;
private static SharedPreferences.Editor editor;
private static Gson gson = new Gson();
public NotePrefs(Context ctx) {
if(settings == null) {
settings = ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
}
editor = settings.edit();
}
public static void saveNote(Note note) {
editor.putString("" + note.getId(), gson.toJson(note));
editor.apply();
}
public static Note loadNote(int id) {
String noteJson = settings.getString("" + id, "");
return gson.fromJson(noteJson, Note.class);
}
public static List<Note> loadAllNotes() {
return null;
}
}
ContextGetter.java:
public class ContextGetter extends Application {
private static Context context;
public void onCreate(){
super.onCreate();
context = getApplicationContext();
}
public static Context getAppContext() {
return context;
}
}
例外:
java.lang.RuntimeException:无法启动活动 ComponentInfo{notes/notes.MainActivity}:java.lang.NullPointerException:尝试调用虚拟方法 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang .String, int)' 在空对象引用上
我似乎仍然无法理解上下文的内容。任何帮助表示赞赏!
另外,实现 loadAllNotes() 的好方法是什么?
干杯
【问题讨论】:
-
嗯,看来这个
ContextGetter工作不正常。为什么不能将活动实例作为context传递给NoteHandler,然后再传递给NotePrefs? -
另一条评论已经让它工作了。你到底建议了什么,你能用代码写吗?我真的不知道活动和上下文(还)......
-
请发布堆栈跟踪。还有什么线导致 NPE?
标签: java android nullpointerexception sharedpreferences