具有共享偏好的Android待办事项列表应用

时间:2015-04-16 18:35:34

标签: android android-intent android-activity sharedpreferences

我有一个用于输入待办事项的文本字段,一个用户选择的微调器,如果它是工作,个人或其他,我有一个日期/时间选择器。我需要使用共享首选项保存所有这些,然后在主页面的表视图中填充它们。我无法弄清楚如何将它们全部保存并将它们发送到主屏幕上的不同列。

2 个答案:

答案 0 :(得分:2)

使用以下代码将值保存在SharedPreferences

        SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE); 
        Editor editor = pref.edit();
        editor.putString("id", "iddata");  
        editor.commit(); 

使用SharedPreferences

中的以下代码反向值
String id=pref.getString("id", null);

答案 1 :(得分:-1)

首先,您需要创建一个处理会话数据的java类,并使用get和set方法来使用共享首选项设置和获取数据。

public class SessionManager
 {
   // LogCat tag
    private static String TAG = SessionManager.class.getSimpleName();
   SharedPreferences pref;

Editor editor;
Context _context;

// Shared pref mode
int PRIVATE_MODE = 0;
 // Shared preferences file name
private static final String PREF_NAME = "yourprefname";

private static final String KEY_IS_NAME = "isname";
private static final String KEY_IS_DATE="isdate";
private static final String KEY_IS_TIME="istime";

   public SessionManager(Context context) {
    this._context = context;
    pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    editor = pref.edit();

}
 public void setTime(String time)
{
editor.putString(KEY_IS_TIME,time);
editor.commit();
}

public String getTime()
{
    return pref.getString(KEY_IS_TIME,null);
}

}

之后你需要通过在任何活动中创建对象来使用sessionManager类,比如

SessionManager session = new SessionManager(this);
//to set the values , use set method
session.setTime(time);
//to get the values, use get method
String time=Session.getTime();
相关问题