【发布时间】:2020-08-30 20:33:41
【问题描述】:
我是 Java 和 Android 开发的新手。我有一个包含性别、电话号码、姓名和爱好数组的数据库。我想用 SharedPreferences 存储在我的活动中,但我不知道如何应用 Gson 类。这是我的代码:
public class SessionManager {
SharedPreferences usersSession;
SharedPreferences.Editor editor;
Context context;
public static final String IS_LOGIN = "IsLoggedIn";
public static final String KEY_NAME = "name";
public static final String KEY_BIRTHDATE = "birthdate";
public static final String KEY_GENDER = "gender";
public static final String KEY_PHONE = "phone";
public static final ArrayList<String> KEY_HOBBIES = new ArrayList<>();
public SessionManager(Context _context) {
context = _context;
usersSession = _context.getSharedPreferences("userLoginSession", Context.MODE_PRIVATE);
editor = usersSession.edit();
Gson gson = new Gson();
String json = gson.toJson(KEY_HOBBIES);
}
public void createLoginSession(String name, String birthdate, String gender, String phone, ArrayList<String> hobbies) {
editor.putBoolean(IS_LOGIN, true);
Gson gson = new Gson();
String json = gson.toJson(KEY_HOBBIES);
editor.putString(KEY_NAME, name);
editor.putString(KEY_BIRTHDATE, birthdate);
editor.putString(KEY_GENDER, gender);
editor.putString(KEY_PHONE, phone);
editor.putString(KEY_HOBBIES, json);
editor.commit();
}
我在这段代码中犯了 2-3 个错误,如何将这个 Arraylist 与其他字符串值一起存储。谢谢
【问题讨论】: