androidAndroid开发Android开发经验谈

Android:这是一份全面 & 详细的SharePrefere

2019-10-08  本文已影响0人  Carson带你学安卓

前言


目录

示意图

1. 简介


2. 对比

除了SharedPreferencesAndroid常见的数据存储方式主要包括:

具体介绍如下:

示意图

3. 具体使用

对于SharePreferences的使用,主要包括保存数据 & 读取数据。

3.1 保存数据

// 步骤1
SharedPreferences sharedPreferences =getSharedPreferences("mltest", Context.MODE_PRIVATE);
    // 参数1:指定该文件的名称,名称不用带后缀,后缀会由Android自动加上
    // 参数2:指定文件的操作模式,共有4种操作模式,分别是:
    // Context.MODE_PRIVATE = 0:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容
    // Context.MODE_APPEND = 32768:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
    // Context.MODE_WORLD_READABLE = 1:表示当前文件可以被其他应用读取
    // Context.MODE_WORLD_WRITEABLE = 2:表示当前文件可以被其他应用写入

// 步骤2:通过Editor获取编辑器对象
Editor editor = sharedPreferences.edit();

// 步骤3:以键值对的方式写入数据
editor.putString("name", "四种模式");
editor.putInt("age", 4);

// 步骤4:提交修改
editor.commit();

3.2 读取数据

// 步骤1
SharedPreferences sharedPreferences = getSharedPreferences("ljq", Context.MODE_PRIVATE);
    // 参数1:指定该文件的名称,名称不用带后缀,后缀会由Android自动加上
    // 参数2:指定文件的操作模式,共有4种操作模式,分别是:
    // Context.MODE_PRIVATE = 0:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容
    // Context.MODE_APPEND = 32768:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
    // Context.MODE_WORLD_READABLE = 1:表示当前文件可以被其他应用读取
    // Context.MODE_WORLD_WRITEABLE = 2:表示当前文件可以被其他应用写入

// 步骤2
String name = sharedPreferences.getString("name", "");
int age = sharedPreferences.getInt("age", 1);
// getxxx():xxx为获取数据的数据类型
// 参数1:要获取的key
// 参数2:缺省值,即preference中不存在该key时返回默认值

4. 实例说明

本节将采用完整实例来说明SharePreferences的使用 = 保存数据 + 读取数据。

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">
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content" 
            android:text="@string/name"
            android:textSize="20px"
            android:id="@+id/nameLable" />
        <EditText android:layout_width="80px"
            android:layout_height="wrap_content" 
            android:layout_toRightOf="@id/nameLable"
            android:layout_alignTop="@id/nameLable"
            android:layout_marginLeft="10px"
            android:id="@+id/name" />
    </RelativeLayout>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content" 
            android:textSize="20px"
            android:text="@string/age"
            android:id="@+id/ageLable" />
        <EditText android:layout_width="80px"
            android:layout_height="wrap_content" 
            android:layout_toRightOf="@id/ageLable"
            android:layout_alignTop="@id/ageLable"
            android:layout_marginLeft="10px"
            android:id="@+id/age" />
    </RelativeLayout>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <Button android:layout_width="wrap_content"
            android:layout_height="wrap_content" 
            android:text="@string/button"
            android:id="@+id/button" />
        <Button android:layout_width="wrap_content"
            android:layout_height="wrap_content" 
            android:text="@string/showButton"
            android:layout_toRightOf="@id/button"
            android:layout_alignTop="@id/button"
            android:id="@+id/showButton" />
    </RelativeLayout>
    <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content" 
            android:textSize="20px"
            android:id="@+id/showText" />
</LinearLayout>

Java文件

package com.ljq.activity;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class SpActivity extends Activity {
    private EditText nameText;
    private EditText ageText;
    private TextView resultText;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        nameText = (EditText)this.findViewById(R.id.name);
        ageText = (EditText)this.findViewById(R.id.age);
        resultText = (TextView)this.findViewById(R.id.showText);
        
        Button button = (Button)this.findViewById(R.id.button);
        Button showButton = (Button)this.findViewById(R.id.showButton);
        button.setOnClickListener(listener);
        showButton.setOnClickListener(listener);
        
        // 回显
        SharedPreferences sharedPreferences=getSharedPreferences("ljq123", 
                Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);
        String nameValue = sharedPreferences.getString("name", "");
        int ageValue = sharedPreferences.getInt("age", 1);
        nameText.setText(nameValue);
        ageText.setText(String.valueOf(ageValue));
    }
    
    private View.OnClickListener listener = new View.OnClickListener(){
        public void onClick(View v) {
            Button button = (Button)v;
            //ljq123文件存放在/data/data/<package name>/shared_prefs目录下
            SharedPreferences sharedPreferences=getSharedPreferences("ljq123", 
                    Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);
            switch (button.getId()) {
            case R.id.button:
                String name = nameText.getText().toString();
                int age = Integer.parseInt(ageText.getText().toString());
                Editor editor = sharedPreferences.edit(); //获取编辑器
                editor.putString("name", name);
                editor.putInt("age", age);
                editor.commit();//提交修改
                Toast.makeText(SpActivity.this, "保存成功", Toast.LENGTH_LONG).show();
                break;
            case R.id.showButton:
                String nameValue = sharedPreferences.getString("name", "");
                int ageValue = sharedPreferences.getInt("age", 1);
                resultText.setText("姓名:" + nameValue + ",年龄:" + ageValue);
                break;
            }
        }
    };
}

5. 总结


请点赞!因为你的鼓励是我写作的最大动力!

相关文章阅读
Android开发:最全面、最易懂的Android屏幕适配解决方案
Android事件分发机制详解:史上最全面、最易懂
Android开发:史上最全的Android消息推送解决方案
Android开发:最全面、最易懂的Webview详解
Android开发:JSON简介及最全面解析方法!
Android四大组件:Service服务史上最全面解析
Android四大组件:BroadcastReceiver史上最全面解析


欢迎关注Carson_Ho的简书!

不定期分享关于安卓开发的干货,追求短、平、快,但却不缺深度

上一篇 下一篇

猜你喜欢

热点阅读