我想存储一个时间值,需要检索和编辑它。我如何使用SharedPreferences来做到这一点?
当前回答
我为sharedpreferences写了一个helper类:
import android.content.Context;
import android.content.SharedPreferences;
/**
* Created by mete_ on 23.12.2016.
*/
public class HelperSharedPref {
Context mContext;
public HelperSharedPref(Context mContext) {
this.mContext = mContext;
}
/**
*
* @param key Constant RC
* @param value Only String, Integer, Long, Float, Boolean types
*/
public void saveToSharedPref(String key, Object value) throws Exception {
SharedPreferences.Editor editor = mContext.getSharedPreferences(key, Context.MODE_PRIVATE).edit();
if (value instanceof String) {
editor.putString(key, (String) value);
} else if (value instanceof Integer) {
editor.putInt(key, (Integer) value);
} else if (value instanceof Long) {
editor.putLong(key, (Long) value);
} else if (value instanceof Float) {
editor.putFloat(key, (Float) value);
} else if (value instanceof Boolean) {
editor.putBoolean(key, (Boolean) value);
} else {
throw new Exception("Unacceptable object type");
}
editor.commit();
}
/**
* Return String
* @param key
* @return null default is null
*/
public String loadStringFromSharedPref(String key) throws Exception {
SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
String restoredText = prefs.getString(key, null);
return restoredText;
}
/**
* Return int
* @param key
* @return null default is -1
*/
public Integer loadIntegerFromSharedPref(String key) throws Exception {
SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
Integer restoredText = prefs.getInt(key, -1);
return restoredText;
}
/**
* Return float
* @param key
* @return null default is -1
*/
public Float loadFloatFromSharedPref(String key) throws Exception {
SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
Float restoredText = prefs.getFloat(key, -1);
return restoredText;
}
/**
* Return long
* @param key
* @return null default is -1
*/
public Long loadLongFromSharedPref(String key) throws Exception {
SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
Long restoredText = prefs.getLong(key, -1);
return restoredText;
}
/**
* Return boolean
* @param key
* @return null default is false
*/
public Boolean loadBooleanFromSharedPref(String key) throws Exception {
SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
Boolean restoredText = prefs.getBoolean(key, false);
return restoredText;
}
}
其他回答
要获得共享首选项,请使用以下方法 在活动中:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
读取首选项:
String dateTimeKey = "com.example.app.datetime";
// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime());
编辑和保存首选项
Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();
android sdk的示例目录包含一个检索和存储共享首选项的示例。它位于:
<android-sdk-home>/samples/android-<platformversion>/ApiDemos directory
编辑= = >
我注意到,在这里写commit()和apply()之间的区别也很重要。
如果保存成功,Commit()返回true,否则返回false。它同步保存值到SharedPreferences。
Apply()是在2.3中添加的,无论成功还是失败都不返回任何值。它会立即将值保存到SharedPreferences,但会启动异步提交。 更多细节在这里。
简单和无麻烦::"Android-SharedPreferences-Helper"库
迟到总比不到好:我创建了“Android-SharedPreferences-Helper”库来帮助降低使用SharedPreferences的复杂性和工作量。它还提供了一些扩展功能。它提供的一些东西如下:
一行初始化和设置 轻松选择是使用默认首选项还是自定义首选项文件 每种数据类型的预定义(默认数据类型)和自定义(您可以选择的)默认值 能力设置不同的默认值为单一使用,只是一个额外的参数 你可以注册和取消注册OnSharedPreferenceChangeListener,因为你做的默认类
dependencies {
...
...
compile(group: 'com.viralypatel.sharedpreferenceshelper', name: 'library', version: '1.1.0', ext: 'aar')
}
SharedPreferencesHelper对象的声明:(建议在类中 级)
SharedPreferencesHelper sph;
SharedPreferencesHelper对象的实例化:(建议在 onCreate()方法)
// use one of the following ways to instantiate
sph = new SharedPreferencesHelper(this); //this will use default shared preferences
sph = new SharedPreferencesHelper(this, "myappprefs"); // this will create a named shared preference file
sph = new SharedPreferencesHelper(this, "myappprefs", 0); // this will allow you to specify a mode
将价值观融入到共同的偏好中
非常简单!不像默认的方式(当使用SharedPreferences类时),你不需要调用.edit()和.commit()。
sph.putBoolean("boolKey", true);
sph.putInt("intKey", 123);
sph.putString("stringKey", "string value");
sph.putLong("longKey", 456876451);
sph.putFloat("floatKey", 1.51f);
// putStringSet is supported only for android versions above HONEYCOMB
Set name = new HashSet();
name.add("Viral");
name.add("Patel");
sph.putStringSet("name", name);
就是这样!您的值存储在共享首选项中。
从共享首选项中获取值
同样,这只是一个使用键名的简单方法调用。
sph.getBoolean("boolKey");
sph.getInt("intKey");
sph.getString("stringKey");
sph.getLong("longKey");
sph.getFloat("floatKey");
// getStringSet is supported only for android versions above HONEYCOMB
sph.getStringSet("name");
它还有很多其他扩展功能
在GitHub知识库页面上查看扩展功能的详细信息,使用和安装说明等。
使用这个例子简单明了
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
public class MainActivity extends AppCompatActivity {
EditText ed1,ed2,ed3;
Button b1;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
public static final String Email = "emailKey";
SharedPreferences sharedpreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);
b1=(Button)findViewById(R.id.button);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String n = ed1.getText().toString();
String ph = ed2.getText().toString();
String e = ed3.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.commit();
Toast.makeText(MainActivity.this,"Thanks",Toast.LENGTH_LONG).show();
}
});
}
}
写:
SharedPreferences preferences = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Authentication_Id",userid.getText().toString());
editor.putString("Authentication_Password",password.getText().toString());
editor.putString("Authentication_Status","true");
editor.apply();
阅读:
SharedPreferences prfs = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
String Astatus = prfs.getString("Authentication_Status", "");
SharedPreferences的基本思想是将内容存储在XML文件中。
Declare your xml file path.(if you don't have this file, Android will create it. If you have this file, Android will access it.) SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE); Write value to Shared Preferences prefs.edit().putLong("preference_file_key", 1010101).apply(); the preference_file_key is the name of shared preference files. And the 1010101 is the value you need to store. apply() at last is to save the changes. If you get error from apply(), change it to commit(). So this alternative sentence is prefs.edit().putLong("preference_file_key", 1010101).commit(); Read from Shared Preferences SharedPreferences sp = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE); long lsp = sp.getLong("preference_file_key", -1); lsp will be -1 if preference_file_key has no value. If 'preference_file_key' has a value, it will return the value of this.
整个代码是
SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE); // Declare xml file
prefs.edit().putLong("preference_file_key", 1010101).apply(); // Write the value to key.
阅读的代码是
SharedPreferences sf = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE); // Declare xml file
long lsp = sp.getLong("preference_file_key", -1); // Read the key and store in lsp
推荐文章
- 如何隐藏动作栏之前的活动被创建,然后再显示它?
- 是否有一种方法以编程方式滚动滚动视图到特定的编辑文本?
- 在Android中将字符串转换为Uri
- 如何在NestedScrollView内使用RecyclerView ?
- 移动到另一个EditText时,软键盘下一步点击Android
- Android应用中的GridView VS GridLayout
- Activity和FragmentActivity的区别
- 右对齐文本在android TextView
- 权限拒绝:start前台需要android.permission.FOREGROUND_SERVICE
- 如何更改android操作栏的标题和图标
- Android Split字符串
- 让一个链接在安卓浏览器启动我的应用程序?
- 如何在Android工作室的外部库中添加一个jar ?
- GridLayout(不是GridView)如何均匀地拉伸所有子元素
- 如何让一个片段删除自己,即它的等效完成()?