Muh*_*man 599 android sharedpreferences
我想存储一个时间值,需要检索和编辑它.我SharedPreferences该怎么用呢?
nai*_*kus 829
要获取共享首选项,请在您的活动中使用以下方法:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
Run Code Online (Sandbox Code Playgroud)
要阅读首选项:
String dateTimeKey = "com.example.app.datetime";
// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime());
Run Code Online (Sandbox Code Playgroud)
编辑和保存首选项
Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();
Run Code Online (Sandbox Code Playgroud)
android sdk的示例目录包含检索和存储共享首选项的示例.它位于:
<android-sdk-home>/samples/android-<platformversion>/ApiDemos directory
Run Code Online (Sandbox Code Playgroud)
编辑==>
我注意到,重要的是在这里commit()和apply()这里写下区别.
commit()true如果值成功保存,则返回false.它同步将值保存到SharedPreferences .
apply()在2.3中添加,并且在成功或失败时不返回任何值.它会立即将值保存到SharedPreferences,但会启动异步提交.更多细节在这里.
Har*_*aur 277
要在共享首选项中存储值:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name","Harneet");
editor.apply();
Run Code Online (Sandbox Code Playgroud)
要从共享首选项中检索值:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name", "");
if(!name.equalsIgnoreCase(""))
{
name = name + " Sethi"; /* Edit the value here*/
}
Run Code Online (Sandbox Code Playgroud)
DeR*_*gan 163
要编辑从数据sharedpreference
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("text", mSaved.getText().toString());
editor.putInt("selection-start", mSaved.getSelectionStart());
editor.putInt("selection-end", mSaved.getSelectionEnd());
editor.apply();
Run Code Online (Sandbox Code Playgroud)
为了获取从数据sharedpreference
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null)
{
//mSaved.setText(restoredText, TextView.BufferType.EDITABLE);
int selectionStart = prefs.getInt("selection-start", -1);
int selectionEnd = prefs.getInt("selection-end", -1);
/*if (selectionStart != -1 && selectionEnd != -1)
{
mSaved.setSelection(selectionStart, selectionEnd);
}*/
}
Run Code Online (Sandbox Code Playgroud)
编辑
我从API Demo示例中获取了这个片段.那里有一个EditText盒子.在这context不是必需的.我正在评论相同的.
sta*_*low 39
来写 :
SharedPreferences preferences = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_WORLD_WRITEABLE);
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();
Run Code Online (Sandbox Code Playgroud)
阅读 :
SharedPreferences prfs = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
String Astatus = prfs.getString("Authentication_Status", "");
Run Code Online (Sandbox Code Playgroud)
Arc*_*are 28
最简单的方法:
要保存:
getPreferences(MODE_PRIVATE).edit().putString("Name of variable",value).commit();
Run Code Online (Sandbox Code Playgroud)
要检索:
your_variable = getPreferences(MODE_PRIVATE).getString("Name of variable",default value);
Run Code Online (Sandbox Code Playgroud)
Jor*_*sys 18
// MY_PREFS_NAME - a static String variable like:
//public static final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.commit();
Run Code Online (Sandbox Code Playgroud)
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.
}
Run Code Online (Sandbox Code Playgroud)
更多信息:
Mag*_*ian 16
单身共享首选项类.它可能在将来对其他人有所帮助.
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
public class SharedPref
{
private static SharedPreferences mSharedPref;
public static final String NAME = "NAME";
public static final String AGE = "AGE";
public static final String IS_SELECT = "IS_SELECT";
private SharedPref()
{
}
public static void init(Context context)
{
if(mSharedPref == null)
mSharedPref = context.getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
}
public static String read(String key, String defValue) {
return mSharedPref.getString(key, defValue);
}
public static void write(String key, String value) {
SharedPreferences.Editor prefsEditor = mSharedPref.edit();
prefsEditor.putString(key, value);
prefsEditor.commit();
}
public static boolean read(String key, boolean defValue) {
return mSharedPref.getBoolean(key, defValue);
}
public static void write(String key, boolean value) {
SharedPreferences.Editor prefsEditor = mSharedPref.edit();
prefsEditor.putBoolean(key, value);
prefsEditor.commit();
}
public static Integer read(String key, int defValue) {
return mSharedPref.getInt(key, defValue);
}
public static void write(String key, Integer value) {
SharedPreferences.Editor prefsEditor = mSharedPref.edit();
prefsEditor.putInt(key, value).commit();
}
}
Run Code Online (Sandbox Code Playgroud)
只需在MainActivity上调用SharedPref.init()一次即可
SharedPref.init(getApplicationContext());
Run Code Online (Sandbox Code Playgroud)
写数据
SharedPref.write(SharedPref.NAME, "XXXX");//save string in shared preference.
SharedPref.write(SharedPref.AGE, 25);//save int in shared preference.
SharedPref.write(SharedPref.IS_SELECT, true);//save boolean in shared preference.
Run Code Online (Sandbox Code Playgroud)
阅读数据
String name = SharedPref.read(SharedPref.NAME, null);//read string in shared preference.
int age = SharedPref.read(SharedPref.AGE, 0);//read int in shared preference.
boolean isSelect = SharedPref.read(SharedPref.IS_SELECT, false);//read boolean in shared preference.
Run Code Online (Sandbox Code Playgroud)
fid*_*zik 15
存储信息
SharedPreferences preferences = getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("username", username.getText().toString());
editor.putString("password", password.getText().toString());
editor.putString("logged", "logged");
editor.commit();
Run Code Online (Sandbox Code Playgroud)
重置您的偏好
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
Run Code Online (Sandbox Code Playgroud)
Sat*_*ish 12
在任何应用程序中,都可以通过PreferenceManager实例及其相关方法访问默认首选项getDefaultSharedPreferences(Context).
使用SharedPreference实例,可以使用getInt(String key,int defVal)检索任何首选项的int值.我们对这种情况感兴趣的偏好是反制的.
在我们的例子中,我们可以SharedPreference使用edit()修改我们案例中的实例,并使用putInt(String key, int newVal)我们增加应用程序的计数,该应用程序超出应用程序并且相应地显示.
要进一步演示此操作,重新启动并重新启动应用程序,您会注意到每次重新启动应用程序时计数都会增加.
PreferencesDemo.java
码:
package org.example.preferences;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.TextView;
public class PreferencesDemo extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the app's shared preferences
SharedPreferences app_preferences =
PreferenceManager.getDefaultSharedPreferences(this);
// Get the value for the run counter
int counter = app_preferences.getInt("counter", 0);
// Update the TextView
TextView text = (TextView) findViewById(R.id.text);
text.setText("This app has been started " + counter + " times.");
// Increment the counter
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("counter", ++counter);
editor.commit(); // Very important
}
}
Run Code Online (Sandbox Code Playgroud)
main.xml中
码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)
ale*_*exm 12
如果您正在与团队中的其他开发人员一起制作大型应用程序,并且打算在没有分散代码或不同SharedPreferences实例的情况下完成所有组织,那么您可以执行以下操作:
//SharedPreferences manager class
public class SharedPrefs {
//SharedPreferences file name
private static String SHARED_PREFS_FILE_NAME = "my_app_shared_prefs";
//here you can centralize all your shared prefs keys
public static String KEY_MY_SHARED_BOOLEAN = "my_shared_boolean";
public static String KEY_MY_SHARED_FOO = "my_shared_foo";
//get the SharedPreferences object instance
//create SharedPreferences file if not present
private static SharedPreferences getPrefs(Context context) {
return context.getSharedPreferences(SHARED_PREFS_FILE_NAME, Context.MODE_PRIVATE);
}
//Save Booleans
public static void savePref(Context context, String key, boolean value) {
getPrefs(context).edit().putBoolean(key, value).commit();
}
//Get Booleans
public static boolean getBoolean(Context context, String key) {
return getPrefs(context).getBoolean(key, false);
}
//Get Booleans if not found return a predefined default value
public static boolean getBoolean(Context context, String key, boolean defaultValue) {
return getPrefs(context).getBoolean(key, defaultValue);
}
//Strings
public static void save(Context context, String key, String value) {
getPrefs(context).edit().putString(key, value).commit();
}
public static String getString(Context context, String key) {
return getPrefs(context).getString(key, "");
}
public static String getString(Context context, String key, String defaultValue) {
return getPrefs(context).getString(key, defaultValue);
}
//Integers
public static void save(Context context, String key, int value) {
getPrefs(context).edit().putInt(key, value).commit();
}
public static int getInt(Context context, String key) {
return getPrefs(context).getInt(key, 0);
}
public static int getInt(Context context, String key, int defaultValue) {
return getPrefs(context).getInt(key, defaultValue);
}
//Floats
public static void save(Context context, String key, float value) {
getPrefs(context).edit().putFloat(key, value).commit();
}
public static float getFloat(Context context, String key) {
return getPrefs(context).getFloat(key, 0);
}
public static float getFloat(Context context, String key, float defaultValue) {
return getPrefs(context).getFloat(key, defaultValue);
}
//Longs
public static void save(Context context, String key, long value) {
getPrefs(context).edit().putLong(key, value).commit();
}
public static long getLong(Context context, String key) {
return getPrefs(context).getLong(key, 0);
}
public static long getLong(Context context, String key, long defaultValue) {
return getPrefs(context).getLong(key, defaultValue);
}
//StringSets
public static void save(Context context, String key, Set<String> value) {
getPrefs(context).edit().putStringSet(key, value).commit();
}
public static Set<String> getStringSet(Context context, String key) {
return getPrefs(context).getStringSet(key, null);
}
public static Set<String> getStringSet(Context context, String key, Set<String> defaultValue) {
return getPrefs(context).getStringSet(key, defaultValue);
}
}
Run Code Online (Sandbox Code Playgroud)
在您的活动中,您可以通过这种方式保存SharedPreferences
//saving a boolean into prefs
SharedPrefs.savePref(this, SharedPrefs.KEY_MY_SHARED_BOOLEAN, booleanVar);
Run Code Online (Sandbox Code Playgroud)
并且您可以通过这种方式检索您的SharedPreferences
//getting a boolean from prefs
booleanVar = SharedPrefs.getBoolean(this, SharedPrefs.KEY_MY_SHARED_BOOLEAN);
Run Code Online (Sandbox Code Playgroud)
如何存储登录值的简单解决方案SharedPreferences.
您可以扩展MainActivity类或其他类,您将存储"您想要保留的值的值".把它放入作家和读者类:
public static final String GAME_PREFERENCES_LOGIN = "Login";
Run Code Online (Sandbox Code Playgroud)
这里分别InputClass是输入和OutputClass输出类.
// This is a storage, put this in a class which you can extend or in both classes:
//(input and output)
public static final String GAME_PREFERENCES_LOGIN = "Login";
// String from the text input (can be from anywhere)
String login = inputLogin.getText().toString();
// then to add a value in InputCalss "SAVE",
SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0);
Editor editor = example.edit();
editor.putString("value", login);
editor.commit();
Run Code Online (Sandbox Code Playgroud)
现在你可以像其他类一样在其他地方使用它.以下是OutputClass.
SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0);
String userString = example.getString("value", "defValue");
// the following will print it out in console
Logger.getLogger("Name of a OutputClass".class.getName()).log(Level.INFO, userString);
Run Code Online (Sandbox Code Playgroud)
存储在SharedPreferences中
SharedPreferences preferences = getSharedPreferences("temp", getApplicationContext().MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putString("name", name);
editor.commit();
Run Code Online (Sandbox Code Playgroud)
获取SharedPreferences
SharedPreferences preferences=getSharedPreferences("temp", getApplicationContext().MODE_PRIVATE);
String name=preferences.getString("name",null);
Run Code Online (Sandbox Code Playgroud)
注意:"temp"是sharedpreferences名称,"name"是输入值.如果值没有退出则返回null
编辑
SharedPreferences pref = getSharedPreferences("YourPref", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("yourValue", value);
editor.commit();
Run Code Online (Sandbox Code Playgroud)
读
SharedPreferences pref = getSharedPreferences("YourPref", MODE_PRIVATE);
value= pref.getString("yourValue", "");
Run Code Online (Sandbox Code Playgroud)
editor.putString("text", mSaved.getText().toString());
Run Code Online (Sandbox Code Playgroud)
在这里,mSaved可以是任何TextView或EditText从这里我们可以提取字符串.你可以简单地指定一个字符串.这里的文本将是保存从mSaved(TextView或EditText)获得的值的键.
SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
Run Code Online (Sandbox Code Playgroud)
此外,无需使用包名称保存首选项文件,即"com.example.app".您可以提及自己的首选名称.希望这可以帮助 !
小智 6
SharedPreferences的基本思想是将事物存储在XML文件中.
声明您的xml文件路径.(如果您没有此文件,Android将创建它.如果您有此文件,Android将访问它.)
SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
Run Code Online (Sandbox Code Playgroud)将值写入共享首选项
prefs.edit().putLong("preference_file_key", 1010101).apply();
Run Code Online (Sandbox Code Playgroud)
这preference_file_key是共享首选项文件的名称.这1010101是您需要存储的价值.
apply()最后是保存更改.如果您收到错误apply(),请将其更改为commit().所以这个替代句子是
prefs.edit().putLong("preference_file_key", 1010101).commit();
Run Code Online (Sandbox Code Playgroud)从共享首选项中读取
SharedPreferences sp = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
long lsp = sp.getLong("preference_file_key", -1);
Run Code Online (Sandbox Code Playgroud)
lsp会-1如果preference_file_key没有价值.如果'preference_file_key'有值,它将返回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.
Run Code Online (Sandbox Code Playgroud)
阅读代码是
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
Run Code Online (Sandbox Code Playgroud)
您可以使用此方法保存值:
public void savePreferencesForReasonCode(Context context,
String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
Run Code Online (Sandbox Code Playgroud)
使用此方法,您可以从SharedPreferences获取值:
public String getPreferences(Context context, String prefKey) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
return sharedPreferences.getString(prefKey, "");
}
Run Code Online (Sandbox Code Playgroud)
这prefKey是您用于保存特定值的密钥.谢谢.
保存
PreferenceManager.getDefaultSharedPreferences(this).edit().putString("VarName","your value").apply();
Run Code Online (Sandbox Code Playgroud)
检索:
String name = PreferenceManager.getDefaultSharedPreferences(this).getString("VarName","defaultValue");
Run Code Online (Sandbox Code Playgroud)
默认值为:如果此首选项不存在,则返回的值。
在某些情况下,您可以使用getActivity()或getApplicationContext()更改“ this ”
人们建议如何使用SharedPreferences有很多方法.我在这里做了一个演示项目.示例中的关键点是使用ApplicationContext和单个sharedpreferences对象.这演示了如何使用具有以下功能的SharedPreferences: -
用法示例如下: -
MyAppPreference.getInstance().setSampleStringKey("some_value");
String value= MyAppPreference.getInstance().getSampleStringKey();
Run Code Online (Sandbox Code Playgroud)
获取源代码在这里 和详细的API,可以发现这里的developer.android.com
最好的做法
创建使用PreferenceManager命名的接口:
// Interface to save values in shared preferences and also for retrieve values from shared preferences
public interface PreferenceManager {
SharedPreferences getPreferences();
Editor editPreferences();
void setString(String key, String value);
String getString(String key);
void setBoolean(String key, boolean value);
boolean getBoolean(String key);
void setInteger(String key, int value);
int getInteger(String key);
void setFloat(String key, float value);
float getFloat(String key);
}
Run Code Online (Sandbox Code Playgroud)
如何使用Activity/Fragment:
public class HomeActivity extends AppCompatActivity implements PreferenceManager{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout_activity_home);
}
@Override
public SharedPreferences getPreferences(){
return getSharedPreferences("SP_TITLE", Context.MODE_PRIVATE);
}
@Override
public SharedPreferences.Editor editPreferences(){
return getPreferences().edit();
}
@Override
public void setString(String key, String value) {
editPreferences().putString(key, value).commit();
}
@Override
public String getString(String key) {
return getPreferences().getString(key, "");
}
@Override
public void setBoolean(String key, boolean value) {
editPreferences().putBoolean(key, value).commit();
}
@Override
public boolean getBoolean(String key) {
return getPreferences().getBoolean(key, false);
}
@Override
public void setInteger(String key, int value) {
editPreferences().putInt(key, value).commit();
}
@Override
public int getInteger(String key) {
return getPreferences().getInt(key, 0);
}
@Override
public void setFloat(String key, float value) {
editPreferences().putFloat(key, value).commit();
}
@Override
public float getFloat(String key) {
return getPreferences().getFloat(key, 0);
}
}
Run Code Online (Sandbox Code Playgroud)
注意:将您的SharedPreference密钥替换为SP_TITLE.
例子:
在shareperence中存储字符串:
setString("my_key", "my_value");
Run Code Online (Sandbox Code Playgroud)
从shareperence 获取字符串:
String strValue = getString("my_key");
Run Code Online (Sandbox Code Playgroud)
希望这会帮助你.
小智 5
要将值存储在共享首选项中:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Name","Jayesh");
editor.commit();
Run Code Online (Sandbox Code Playgroud)
要从共享的首选项中检索值:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String name = sp.getString("Name", ""); // Second parameter is the default value.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
624173 次 |
| 最近记录: |