我想存储一个时间值,需要检索和编辑它。我如何使用SharedPreferences来做到这一点?
当前回答
在共享首选项中存储值:
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", "");
其他回答
简单的方法:
保存:
getPreferences(MODE_PRIVATE).edit().putString("Name of variable",value).commit();
检索:
your_variable = getPreferences(MODE_PRIVATE).getString("Name of variable",default value);
以函数的方式存储和检索全局变量。 要测试,请确保页面上有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" />
在任何应用程序中,都有可以通过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>
如果你正在与团队中的其他开发人员一起开发一个大型应用程序,并打算让所有内容都很好地组织起来,而不是分散的代码或不同的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);
}
}
在您的活动中,您可以这样保存SharedPreferences
//saving a boolean into prefs
SharedPrefs.savePref(this, SharedPrefs.KEY_MY_SHARED_BOOLEAN, booleanVar);
你可以这样检索你的SharedPreferences
//getting a boolean from prefs
booleanVar = SharedPrefs.getBoolean(this, SharedPrefs.KEY_MY_SHARED_BOOLEAN);
我创建了一个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;
}
}
推荐文章
- 如何隐藏动作栏之前的活动被创建,然后再显示它?
- 是否有一种方法以编程方式滚动滚动视图到特定的编辑文本?
- 在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)如何均匀地拉伸所有子元素
- 如何让一个片段删除自己,即它的等效完成()?