Android-SharedPreference自动保存和手动保存数据-Oak先生

来源:互联网 发布:网络外推软件 编辑:程序博客网 时间:2024/06/11 19:58

什么是SharedPreference呢,他是安卓里面的一个轻量级的存储器,以键值对的方式存在,保存的目录在应用程序下的一个文件夹中。下面我们来看看如何使用这个SharedPreference来手动保存数据以及PreferenceActivity的界面交互自动保存数据。


手动保存数据效果图:


自动保存数据效果图:



1、手动保存数据很简单,只需要获取到SharedPreference实例和Editor对于的编辑器即可

代码如下:

activity_main.xml布局代码:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.oak.d1_sharedpreference.MainActivity">    <EditText        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/et"        android:hint="请输入文字"/>    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/bt_read"        android:text="读取"/>    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/bt_write"        android:text="写入"/></LinearLayout>

MainActivity.java代码:

package com.oak.d1_sharedpreference;import android.app.Activity;import android.content.Intent;import android.content.SharedPreferences;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;public class MainActivity extends AppCompatActivity {    private SharedPreferences sharedPreferences;//获取到轻量级存储器辩论    private SharedPreferences.Editor editor;//获取轻量级存储器的编辑器    private EditText editText;    private Button bt_read;    private Button bt_wirte;    public static final String KEY = "MyValue";//定义一个键值对的键,通过这个来取值    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //获取sharedPreferences实例        sharedPreferences = getPreferences(Activity.MODE_PRIVATE);        //获取sharedPreferences编辑器        editor = sharedPreferences.edit();        //获取编辑框        editText = (EditText) findViewById(R.id.et);        //获取到读按钮        bt_read = (Button) findViewById(R.id.bt_read);        //获取到写按钮        bt_wirte = (Button) findViewById(R.id.bt_write);        //为读按钮添加侦听事件        bt_read.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                //通过键来获取sharedPreferences中的数据,如果未找到则显示“未找到值”                String txt = sharedPreferences.getString(KEY, "未找到值");                //以吐司的方式显示出来                Toast.makeText(getApplicationContext(), txt, Toast.LENGTH_SHORT).show();            }        });        //为写按钮添加侦听事件        bt_wirte.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                //获取到编辑框中的内容                String txt = editText.getText().toString();                //将编辑框中的内容写入到轻量级存储器中                editor.putString(KEY, txt);                //提交                editor.commit();                //吐司提示用户保存成功                Toast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_SHORT).show();            }        });    }}
到这里手动保存SharedPreference数据就完成了。


2、下面我们来试试怎么通过界面交互来自动保存SharedPreference数据

需要做如下准备:

1)、创建一个java类,继承PreferenceActivity,我把他命名为:MyPreferenceActivity.java

2)、在res文件夹下创建一个xml文件夹,在xml文件夹下创建一个mypreference.xml文件,这个相当于MyPreferenceActivity.java的布局文件

3)、由于自动保存数据的界面用到ListPreference,所以要在values文件夹中创建一个mylistpreference.xml文件

4)、由于要启动一个PreferenceActivity,所以要在AndroidManifest文件中添加声明activity


代码如下:

MainActivity.java代码:

package com.oak.d1_sharedpreference;import android.app.Activity;import android.content.Intent;import android.content.SharedPreferences;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;public class MainActivity extends AppCompatActivity {    private SharedPreferences sharedPreferences;//获取到轻量级存储器辩论    private SharedPreferences.Editor editor;//获取轻量级存储器的编辑器    private EditText editText;    private Button bt_read;    private Button bt_wirte;    private Button bt_preference;    public static final String KEY = "MyValue";//定义一个键值对的键,通过这个来取值    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //获取sharedPreferences实例        sharedPreferences = getPreferences(Activity.MODE_PRIVATE);        //获取sharedPreferences编辑器        editor = sharedPreferences.edit();        //获取编辑框        editText = (EditText) findViewById(R.id.et);        //获取到读按钮        bt_read = (Button) findViewById(R.id.bt_read);        //获取到写按钮        bt_wirte = (Button) findViewById(R.id.bt_write);        //获取到自动保存修改首选项按钮        bt_preference = (Button) findViewById(R.id.bt_preference);        //为读按钮添加侦听事件        bt_read.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                //通过键来获取sharedPreferences中的数据,如果未找到则显示“未找到值”                String txt = sharedPreferences.getString(KEY, "未找到值");                //以吐司的方式显示出来                Toast.makeText(getApplicationContext(), txt, Toast.LENGTH_SHORT).show();            }        });        //为写按钮添加侦听事件        bt_wirte.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                //获取到编辑框中的内容                String txt = editText.getText().toString();                //将编辑框中的内容写入到轻量级存储器中                editor.putString(KEY, txt);                //提交                editor.commit();                //吐司提示用户保存成功                Toast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_SHORT).show();            }        });        //为自动修改首选项按钮添加侦听事件        bt_preference.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                //跳转到自动保存修改首选项界面                startActivity(new Intent(getApplicationContext(), MyPreferenceActivity.class));            }        });    }}
activity_main.xml代码:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.oak.d1_sharedpreference.MainActivity">    <EditText        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/et"        android:hint="请输入文字"/>    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/bt_read"        android:text="读取"/>    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/bt_write"        android:text="写入"/>    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/bt_preference"        android:text="自动保存首先选"/></LinearLayout>

MyPreferenceActivity.java代码:

package com.oak.d1_sharedpreference;import android.os.Bundle;import android.preference.CheckBoxPreference;import android.preference.EditTextPreference;import android.preference.ListPreference;import android.preference.PreferenceActivity;import android.preference.PreferenceManager;import android.widget.Toast;public class MyPreferenceActivity extends PreferenceActivity {    private PreferenceManager preferenceManager;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        //将自定义的preference布局界面添加进来        addPreferencesFromResource(R.xml.mypreference);        //获取到preference管理器        preferenceManager = getPreferenceManager();        //获取到preference界面的CheckBoxPreference组件内容        CheckBoxPreference checkBoxPreference = (CheckBoxPreference) preferenceManager.findPreference("checkbox");        Toast.makeText(getApplicationContext(), checkBoxPreference.isChecked()+"", Toast.LENGTH_SHORT).show();        //获取到preference界面的ListPreference组件内容        ListPreference listPreference = (ListPreference) preferenceManager.findPreference("list");        Toast.makeText(getApplicationContext(), listPreference.getEntry()+"的开发语软件是"+listPreference.getValue(), Toast.LENGTH_SHORT).show();        //获取到preference界面的EditTextPreference组件内容        EditTextPreference editTextPreference = (EditTextPreference) preferenceManager.findPreference("edit");        Toast.makeText(getApplicationContext(), "您的姓名:"+editTextPreference.getText(), Toast.LENGTH_SHORT).show();    }}

mypreference.xml代码:相当于Preference界面的布局文件

<?xml version="1.0" encoding="utf-8"?><!--PreferenceActivity的布局文件--><PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">    <!--定义一个CheckBoxPreference组件-->    <CheckBoxPreference        android:key="checkbox"        android:summaryOff="已经关闭"        android:summaryOn="已经开启"        android:title="是否开启"        />    <!--定义一个ListPreference组件-->    <ListPreference        android:key="list"        android:title="请选择一个项目"        android:summary="点击选择"        android:entries="@array/entries"        android:entryValues="@array/values" />    <!--定义一个EditTextPreference组件-->    <EditTextPreference        android:key="edit"        android:title="请输入名字"        android:summary="点击输入名字"        android:dialogTitle="输入框"        android:dialogMessage="在下面的编辑框中输入您的姓名"/></PreferenceScreen>
mylistpreference.xml代码:

<?xml version="1.0" encoding="utf-8"?><resources>    <!--这里用于存放ListPreference的键值对值-->    <string-array name="entries">        <item>Java</item>        <item>Swift</item>        <item>C#</item>    </string-array>    <string-array name="values">        <item>Eclipse</item>        <item>Xcode</item>        <item>Visual Studio</item>    </string-array></resources>

AndroidManifest.xml:声明MyPreferenceActivity界面

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.oak.d1_sharedpreference">    <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:supportsRtl="true"        android:theme="@style/AppTheme">        <activity android:name=".MainActivity">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <!--声明Preference界面-->        <activity android:name=".MyPreferenceActivity"></activity>    </application></manifest>

到这里手动保存和自动保存数据就完成了,不懂的童鞋们可以留言给我,我会第一时间解答的。

By:Mr.Oak

2 0