我想存储一个时间值,需要检索和编辑它。我如何使用SharedPreferences来做到这一点?
当前回答
简单的方法:
保存:
getPreferences(MODE_PRIVATE).edit().putString("Name of variable",value).commit();
检索:
your_variable = getPreferences(MODE_PRIVATE).getString("Name of variable",default value);
其他回答
编辑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();
从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);
}*/
}
Edit
我从API Demo样本中截取了这个片段。它有一个编辑文本框。在这种情况下,它不是必需的。我也有同样的看法。
我为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;
}
}
最好的实践
创建命名为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);
}
如何使用活动/片段:
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);
}
}
注意:用SP_TITLE替换你的SharedPreference键。
例子:
存储字符串在shareperence:
setString("my_key", "my_value");
从shareperence获取字符串:
String strValue = getString("my_key");
希望这对你有所帮助。
在共享首选项中存储值:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Name","Jayesh");
editor.commit();
从共享首选项中检索值:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String name = sp.getString("Name", "");
以函数的方式存储和检索全局变量。 要测试,请确保页面上有Textview项,取消代码中的两行注释并运行。然后再次注释这两行,然后运行。 这里TextView的id是用户名和密码。
在你想要使用它的每个Class中,在最后添加这两个例程。 我想这个例行程序是全球例行程序,但不知道如何。这个作品。
这些变量随处可见。 它将变量存储在“MyFile”中。你可以按自己的方式改变。
你称之为使用
storeSession("username","frans");
storeSession("password","!2#4%");***
变量username将用“frans”填充,密码为“!2#4%”。即使在重新启动后,它们仍然可用。
你用
password.setText(getSession(("password")));
usernames.setText(getSession(("username")));
下面是我的grid.java的全部代码
package nl.yentel.yenteldb2;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class Grid extends AppCompatActivity {
private TextView usernames;
private TextView password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
***// storeSession("username","frans.eilering@gmail.com");
//storeSession("password","mijn wachtwoord");***
password = (TextView) findViewById(R.id.password);
password.setText(getSession(("password")));
usernames=(TextView) findViewById(R.id.username);
usernames.setText(getSession(("username")));
}
public void storeSession(String key, String waarde) {
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyFile", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(key, waarde);
editor.commit();
}
public String getSession(String key) {
//http://androidexample.com/Android_SharedPreferences_Basics/index.php?view=article_discription&aid=126&aaid=146
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyFile", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
String output = pref.getString(key, null);
return output;
}
}
下面是textview项
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="usernames"
android:id="@+id/username"
android:layout_below="@+id/textView"
android:layout_alignParentStart="true"
android:layout_marginTop="39dp"
android:hint="hier komt de username" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="password"
android:id="@+id/password"
android:layout_below="@+id/user"
android:layout_alignParentStart="true"
android:hint="hier komt het wachtwoord" />
推荐文章
- 如何隐藏动作栏之前的活动被创建,然后再显示它?
- 是否有一种方法以编程方式滚动滚动视图到特定的编辑文本?
- 在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)如何均匀地拉伸所有子元素
- 如何让一个片段删除自己,即它的等效完成()?