如何使用控制你的电话和报文统计信息在机器储存、提取和编辑值[封闭]

StackOverflow https://stackoverflow.com/questions/3624280

  •  26-09-2019
  •  | 
  •  

我想商店的时间的价值和需要检索和编辑。我如何可以使用 SharedPreferences 要做到这一点?

有帮助吗?

解决方案

要获得共享偏好,使用以下方法 在您的活动:

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但启动一个的异步提交。 更详细地是此处

其他提示

要存储在共享偏好值:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name","Harneet");
editor.apply();

要从共享偏好检索值:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name", "");
if(!name.equalsIgnoreCase(""))
{
    name = name + "  Sethi";  /* Edit the value here*/
}

要的修改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);
  }*/
}

修改

我从API Demo示例这个片段。它有一个EditText盒子里。在这种context它不是required.I正在注释相同。

要写:

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();

要阅读:

SharedPreferences prfs = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
String Astatus = prfs.getString("Authentication_Status", "");

最简单的方法:

要保存:

getPreferences(MODE_PRIVATE).edit().putString("Name of variable",value).commit();

要检索:

your_variable = getPreferences(MODE_PRIVATE).getString("Name of variable",default value);

设置在偏好值:

// 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();

提取从偏好数据:

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.
}

的详细信息:

使用的共享偏好

共享偏好

要存储信息

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();

要重置首

SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();

的Singleton共享偏好类。它可以帮助别人的未来。

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();
    }
}

要获取SharedPref.init()MainActivity一次

SharedPref.init(getApplicationContext());

要写入数据

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.

要读取数据

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.

如果你在你的团队制作与其他开发者提供大量的应用程序,并打算生的一切,而不散乱的代码或不同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);

在任何应用中,存在能够通过PreferenceManager实例及其相关方法getDefaultSharedPreferences(Context)访问默认的偏好。

使用的SharedPreference实例可以检索与在 getInt的任何偏好的int值(String键,INT DEFVAL)即可。我们感兴趣的是这种情况下的优先级为计数器。

在我们的例子中,我们可以修改SharedPreference例如在使用编辑(我们的情况下),并使用putInt(String key, int newVal)我们增加了计数为我们的应用程序,presist超出了应用,并相应地显示出来。

要这进一步演示,重启和您再次申请,你会发现,计数将在每次重新启动应用程序的时间增加。

<强> 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存储简单的解决方案。

您可以扩展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);

商品在SharedPreferences

SharedPreferences preferences = getSharedPreferences("temp", getApplicationContext().MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putString("name", name);
editor.commit();

<强>取在SharedPreferences

SharedPreferences preferences=getSharedPreferences("temp", getApplicationContext().MODE_PRIVATE);
String name=preferences.getString("name",null);

注: “温度” 是sharedpreferences名称和 “name” 是输入值。如果值简化版,出口则返回null

修改

SharedPreferences pref = getSharedPreferences("YourPref", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("yourValue", value);
editor.commit();

SharedPreferences pref = getSharedPreferences("YourPref", MODE_PRIVATE);
value= pref.getString("yourValue", "");

基本的想法 控制你的电话和报文统计信息 是店里的东西在XML文件。

  1. 宣布你xml文件的道路。(如果你没有这个文件,机会创建它。如果你有这样的文件,安卓将访问。)

    SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
    
  2. 写价值的共享的喜好

    prefs.edit().putLong("preference_file_key", 1010101).apply();
    

    preference_file_key 是名称的共同优先文件。和 1010101 是的价值,你需要的商店。

    apply() 在最后一个被拯救的变化。如果你得到错误 apply(), ,改变它 commit().因此,这替换句话是

    prefs.edit().putLong("preference_file_key", 1010101).commit();
    
  3. 从中读取共同的喜好

    SharedPreferences sp = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
    long lsp = sp.getLong("preference_file_key", -1);
    

    lsp-1 如果 preference_file_key 没有价值。如果'preference_file_key'具有价值,它将返回的价值,这一点。

整个代码写的是

    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

可以使用这种方法节省值:

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();
    }

和使用这种方法,你可以从SharedPreferences值:

public String getPreferences(Context context, String prefKey) {
  SharedPreferences sharedPreferences = PreferenceManager
 .getDefaultSharedPreferences(context);
 return sharedPreferences.getString(prefKey, "");
}

下面prefKey是您用于保存特定值的键。感谢。

editor.putString("text", mSaved.getText().toString());

下面,mSaved可以从这里我们可以提取字符串任何TextViewEditText。你可以简单地指定一个字符串。这里文本将其保存从mSavedTextViewEditText)中获得的值的键。

SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);

另外,不需要使用包名称即“com.example.app”保存偏好文件。那么你可以说你自己喜欢的名字。希望这有助于!

有许多方法,人们建议如何使用 控制你的电话和报文统计信息.我已经做了一个 演示项目在这里.关键的一点在样品的使用 文和单控制你的电话和报文统计信息的对象.这说明了如何使用 控制你的电话和报文统计信息 与以下特点:

  • 使用singelton流入/更新控制你的电话和报文统计信息
  • 没有必要通过下文总是读写控制你的电话和报文统计信息
  • 它使用的申请()而不是提交()
  • 申请()是asynchronus保存,不回任何东西,它更新的价值中存储一改变写入磁盘后 asynchronusly.
  • commit()是synchronus保存,它返回true/false基于结果。更改写入磁盘synchronusly
  • 适用于安卓2.3版本

使用情况的示例如下:-

MyAppPreference.getInstance().setSampleStringKey("some_value");
String value= MyAppPreference.getInstance().getSampleStringKey();

获得源代码在这里 和详细的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);

}

如何与使用活动 / <强>片段

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);
    }
}

注意:替换为您SharedPreference的关键 SP_TITLE

<强>示例:

商品串在的 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", ""); // Second parameter is the default value.

以保存

PreferenceManager.getDefaultSharedPreferences(this).edit().putString("VarName","your value").apply();

<强>中检索:

String name = PreferenceManager.getDefaultSharedPreferences(this).getString("VarName","defaultValue");
  

默认值是:值对,如果此偏好不存在返回

     

可以改变 “的 ” 是 getActivity() 或<强> getApplicationContext( ) 在   一些情况下

<强> 使用使用本实施例简单明了,并检查

<?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 ..

TinyDB tinydb = new TinyDB(context);

tinydb.putInt("clickCount", 2);

tinydb.putString("userName", "john");
tinydb.putBoolean("isUserMale", true); 

tinydb.putList("MyUsers", mUsersArray);
tinydb.putImagePNG("DropBox/WorkImages", "MeAtlunch.png", lunchBitmap);

//These plus the corresponding get methods are all Included

我想在这里补充一点,大多数的片段为这个问题的使用SharedPreferences时会碰到这样的MODE_PRIVATE。那么,MODE_PRIVATE意味着,无论你写的这个共享的喜好只能通过你的应用程序只。

阅读

无论键传递给getSharedPreferences()方法,机器人创建具有该名称并存储偏好数据到它的文件。 还记得getSharedPreferences()应该被用来当你打算有多个预置文件为您的应用程序。如果你打算使用单个首选项文件,并存储所有键值对到它然后使用getSharedPreference()方法。它的怪异,为什么大家(包括我自己),只需使用getSharedPreferences()的味道,甚至没有了解上述两个之间的区别。

在以下的视频教程应该帮助 https://www.youtube.com/watch?v=2PcAQ1NBy98

简单的理想免费的::"安卓-控制你的电话和报文统计信息-帮助"的图书馆

迟到总比不到好:我创造的 "机器人-控制你的电话和报文统计信息-帮助"的图书馆 为了帮助减少复杂性和努力的使用 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

把价值观纳入共同的喜好

相当简单!不同于默认的方式(当使用控制你的电话和报文统计信息类)你就不需要电话 .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");

它有很多其他的扩展功能

检查的详细信息的扩展功能,使用和安装的指示等等的 想库的网页.

我写sharedpreferences一个辅助类:

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.Editor editor = getSharedPreferences("identifier", 
MODE_PRIVATE).edit();
//identifier is the unique to fetch data from your SharedPreference.


editor.putInt("keyword", 0); 
// saved value place with 0.
//use this "keyword" to fetch saved value again.
editor.commit();//important line without this line your value is not stored in preference   

// fetch the stored data using ....

SharedPreferences prefs = getSharedPreferences("identifier", MODE_PRIVATE); 
// here both identifier will same

int fetchvalue = prefs.getInt("keyword", 0);
// here keyword will same as used above.
// 0 is default value when you nothing save in preference that time fetch value is 0.

您需要AdapterClass或任何其他使用SharedPreferences。 该时间只是使用此声明,并使用上述相同的屁股。

SharedPreferences.Editor editor = context.getSharedPreferences("idetifier", 
Context.MODE_PRIVATE).edit();
SharedPreferences prefs = context.getSharedPreferences("identifier", Context.MODE_PRIVATE);

//here context is your application context

有关的字符串或布尔值

editor.putString("stringkeyword", "your string"); 
editor.putBoolean("booleankeyword","your boolean value");
editor.commit();

取数据与上述相同的

String fetchvalue = prefs.getString("keyword", "");
Boolean fetchvalue = prefs.getBoolean("keyword", "");

2.对于存储共享prefrence

SharedPreferences.Editor editor = 
getSharedPreferences("DeviceToken",MODE_PRIVATE).edit();
                    editor.putString("DeviceTokenkey","ABABABABABABABB12345");
editor.apply();

2.对于检索相同用途

    SharedPreferences prefs = getSharedPreferences("DeviceToken", 
 MODE_PRIVATE);
  String deviceToken = prefs.getString("DeviceTokenkey", null);

下面我已经创建了一个辅助类来使用偏好的机器人。

这是助手类:

public class PrefsUtil {

public static SharedPreferences getPreference() {
    return PreferenceManager.getDefaultSharedPreferences(Applicatoin.getAppContext());
}

public static void putBoolean(String key, boolean value) {
    getPreference().edit().putBoolean(key, value)
            .apply();
}

public static boolean getBoolean(String key) {
    return getPreference().getBoolean(key, false);
}

public static void putInt(String key, int value) {

    getPreference().edit().putInt(key, value).apply();

}

public static void delKey(String key) {

    getPreference().edit().remove(key).apply();

}

}

要存储和检索功能的方法全局变量。 为了测试,确保你有你的页面上TextView的项目中,取消对两行代码并运行。然后再发表意见的两条线,并运行。点击 这里所述的TextView的id是用户名和密码。

在您要使用它,在末尾添加这两个程序的每个类。 我想这个程序是全球性的套路,但不知道怎么办。这个作品。

在variabels可用无处不在。 它存储在“MyFile的”变量。您可以用自己的方式改变它。

您使用称之为

 storeSession("username","frans");
 storeSession("password","!2#4%");***

可变的用户名将会填入“反式”,并与密码“!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" />

我创建了一个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;
}

}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top