我想存储一个时间值,需要检索和编辑它。我如何使用SharedPreferences来做到这一点?
当前回答
editor.putString("text", mSaved.getText().toString());
这里,mSaved可以是任何TextView或EditText,从中我们可以提取一个字符串。您可以简单地指定一个字符串。这里的text将是键,它持有从mSaved (TextView或EditText)获得的值。
SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
此外,不需要使用包名保存首选项文件,即“com.example.app”。你可以提到自己喜欢的名字。希望这能有所帮助!
其他回答
我创建了一个Helper类来简化我的生活。这是一个泛型类,有很多在应用程序中常用的方法,如共享首选项,电子邮件有效性,日期时间格式。在代码中复制这个类,并在任何需要的地方访问它的方法。
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.support.v4.app.FragmentActivity;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* Created by Zohaib Hassan on 3/4/2016.
*/
public class Helper {
private static ProgressDialog pd;
public static void saveData(String key, String value, Context context) {
SharedPreferences sp = context.getApplicationContext()
.getSharedPreferences("appData", 0);
SharedPreferences.Editor editor;
editor = sp.edit();
editor.putString(key, value);
editor.commit();
}
public static void deleteData(String key, Context context){
SharedPreferences sp = context.getApplicationContext()
.getSharedPreferences("appData", 0);
SharedPreferences.Editor editor;
editor = sp.edit();
editor.remove(key);
editor.commit();
}
public static String getSaveData(String key, Context context) {
SharedPreferences sp = context.getApplicationContext()
.getSharedPreferences("appData", 0);
String data = sp.getString(key, "");
return data;
}
public static long dateToUnix(String dt, String format) {
SimpleDateFormat formatter;
Date date = null;
long unixtime;
formatter = new SimpleDateFormat(format);
try {
date = formatter.parse(dt);
} catch (Exception ex) {
ex.printStackTrace();
}
unixtime = date.getTime();
return unixtime;
}
public static String getData(long unixTime, String formate) {
long unixSeconds = unixTime;
Date date = new Date(unixSeconds);
SimpleDateFormat sdf = new SimpleDateFormat(formate);
String formattedDate = sdf.format(date);
return formattedDate;
}
public static String getFormattedDate(String date, String currentFormat,
String desiredFormat) {
return getData(dateToUnix(date, currentFormat), desiredFormat);
}
public static double distance(double lat1, double lon1, double lat2,
double lon2, char unit) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2))
+ Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2))
* Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
if (unit == 'K') {
dist = dist * 1.609344;
} else if (unit == 'N') {
dist = dist * 0.8684;
}
return (dist);
}
/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
/* :: This function converts decimal degrees to radians : */
/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
private static double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
/* :: This function converts radians to decimal degrees : */
/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
private static double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
public static int getRendNumber() {
Random r = new Random();
return r.nextInt(360);
}
public static void hideKeyboard(Context context, EditText editText) {
InputMethodManager imm = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
public static void showLoder(Context context, String message) {
pd = new ProgressDialog(context);
pd.setCancelable(false);
pd.setMessage(message);
pd.show();
}
public static void showLoderImage(Context context, String message) {
pd = new ProgressDialog(context);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setCancelable(false);
pd.setMessage(message);
pd.show();
}
public static void dismissLoder() {
pd.dismiss();
}
public static void toast(Context context, String text) {
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
}
/*
public static Boolean connection(Context context) {
ConnectionDetector connection = new ConnectionDetector(context);
if (!connection.isConnectingToInternet()) {
Helper.showAlert(context, "No Internet access...!");
//Helper.toast(context, "No internet access..!");
return false;
} else
return true;
}*/
public static void removeMapFrgment(FragmentActivity fa, int id) {
android.support.v4.app.Fragment fragment;
android.support.v4.app.FragmentManager fm;
android.support.v4.app.FragmentTransaction ft;
fm = fa.getSupportFragmentManager();
fragment = fm.findFragmentById(id);
ft = fa.getSupportFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
}
public static AlertDialog showDialog(Context context, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
// TODO Auto-generated method stub
}
});
return builder.create();
}
public static void showAlert(Context context, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Alert");
builder.setMessage(message)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
}).show();
}
public static boolean isURL(String url) {
if (url == null)
return false;
boolean foundMatch = false;
try {
Pattern regex = Pattern
.compile(
"\\b(?:(https?|ftp|file)://|www\\.)?[-A-Z0-9+&#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$]\\.[-A-Z0-9+&@#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$]",
Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher regexMatcher = regex.matcher(url);
foundMatch = regexMatcher.matches();
return foundMatch;
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
return false;
}
}
public static boolean atLeastOneChr(String string) {
if (string == null)
return false;
boolean foundMatch = false;
try {
Pattern regex = Pattern.compile("[a-zA-Z0-9]",
Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher regexMatcher = regex.matcher(string);
foundMatch = regexMatcher.matches();
return foundMatch;
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
return false;
}
}
public static boolean isValidEmail(String email, Context context) {
String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
return true;
} else {
// Helper.toast(context, "Email is not valid..!");
return false;
}
}
public static boolean isValidUserName(String email, Context context) {
String expression = "^[0-9a-zA-Z]+$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
return true;
} else {
Helper.toast(context, "Username is not valid..!");
return false;
}
}
public static boolean isValidDateSlash(String inDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
dateFormat.setLenient(false);
try {
dateFormat.parse(inDate.trim());
} catch (ParseException pe) {
return false;
}
return true;
}
public static boolean isValidDateDash(String inDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy");
dateFormat.setLenient(false);
try {
dateFormat.parse(inDate.trim());
} catch (ParseException pe) {
return false;
}
return true;
}
public static boolean isValidDateDot(String inDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.mm.yyyy");
dateFormat.setLenient(false);
try {
dateFormat.parse(inDate.trim());
} catch (ParseException pe) {
return false;
}
return true;
}
}
为了节省
PreferenceManager.getDefaultSharedPreferences(this).edit().putString("VarName","your value").apply();
收回:
String name = PreferenceManager.getDefaultSharedPreferences(this).getString("VarName","defaultValue");
默认值为:如果该首选项不存在则返回的值。 你可以用getActivity()或getApplicationContext()来改变“this” 某些情况下
如何通过SharedPreferences存储登录值的简单解决方案。
您可以扩展MainActivity类或其他存储“想要保留的值”的类。把这些放到作者和读者课程中:
public static final String GAME_PREFERENCES_LOGIN = "Login";
这里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();
现在你可以在其他地方使用它,比如其他类。下面是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);
在任何应用程序中,都有可以通过PreferenceManager实例及其相关方法getDefaultSharedPreferences(Context)访问的默认首选项。
使用SharedPreference实例,可以使用getInt(String key, int defVal)检索任意首选项的int值。在这种情况下,我们更倾向于使用计数器。
在我们的例子中,我们可以使用edit()并使用putInt(String key, int newVal)来修改SharedPreference实例。我们增加了应用程序的计数,这些计数超出了应用程序并相应地显示。
为了进一步演示这一点,再次重新启动应用程序,您将注意到每次重新启动应用程序时计数都会增加。
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
}
}
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>
最好的实践
创建命名为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");
希望这对你有所帮助。
推荐文章
- 如何隐藏动作栏之前的活动被创建,然后再显示它?
- 是否有一种方法以编程方式滚动滚动视图到特定的编辑文本?
- 在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)如何均匀地拉伸所有子元素
- 如何让一个片段删除自己,即它的等效完成()?