Android-SharedPreference自动保存和手动保存数据-刘宇

什么是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:Brycen Liu

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android Studio中的SharedPreferences是Android开发中一种用于存储小量数据的方式。它提供了一种简单的键对存储机制,用于存储应用程序的用户配置信息或其他简单数据SharedPreferences存储的数据是以XML文件形式保存在设备上。每个SharedPreferences文件都有一个唯一的名称,通过该名称可以访问对应的SharedPreferences对象。可以使用SharedPreferences对象的putXXX()方法存储不同类型的数据,如字符串、整数、布尔等。 得注意的是,SharedPreferences中的数据是以键对的形式存储的。我们可以通过特定的键来获取相应的,也可以通过键来删除或修改对应的SharedPreferences存储的数据是私有的,只能被相同应用程序的组件访问,其他应用程序无法读取或修改。 为了使用SharedPreferences,首先需要获取SharedPreferences对象。可以通过Context的getSharedPreferences()方法或PreferenceManager的getDefaultSharedPreferences()方法来获取SharedPreferences对象。然后可以通过SharedPreferences对象进行数据的存储、读取、删除等操作。 SharedPreferences的使用非常简便,适用于存储一些简单的配置信息或用户偏好设置。例如,可以使用SharedPreferences存储用户的登录状态、音量设置、主题颜色等。它还可以用于存储应用程序的运行状态,以便下次启动应用程序时可以恢复之前的状态。 总的来说,SharedPreferences是Android开发中非常方便的一种数据存储方式,适用于存储小量数据。它的使用简单且效率较高,对于一些简单的应用场景非常实用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值