Android中的数据存储(一):SharedPreferences 2017-05-24 10:35 64人阅读 评论(1) 收藏

SharedPreferences
这是本人(菜鸟)学习android数据存储时接触的有关SharedPreferences的知识以及本人自己写的一个简单地demo,为初学者学习和使用SharedPreferences提供一些帮助。。

下面是有关SharedPreferences的相关知识:
  一:使用范围
    SharedPreferences只能保存少量的数据,且这些数据的格式非常简单:字符串型、基本类型的值。比如应用程序的各种配置信息(如是否打开音效、是否使用震动效果、小游戏的玩家积分等),解锁口 令密码等。


二:核心原理:
保存基于XML文件存储的key-value键值对数据通常用来存储一些简单的配置信息。通过DDMS的File Explorer面板,展开文件浏览树,很明显SharedPreferences数据总是存储在/data/data/<package name>/shared_prefs目录下。


三:注意事项:
1.SharedPreferences对象本身只能获取数据而不支持存储和修改,存储修改是通过SharedPreferences.edit()获取的内部接口Editor对象实现。 
2.SharedPreferences本身是一 个接口,程序无法直接创建SharedPreferences实例,只能通过Context提供的getSharedPreferences(String name, int mode)方法来获取SharedPreferences实例。该方法中name表示要操作的xml文件名,第二个参数具体如下:

   Context.MODE_PRIVATE: 指定该SharedPreferences数据只能被本应用程序读、写。
Context.MODE_WORLD_READABLE:  指定该SharedPreferences数据能被其他应用程序读,但不能写。
Context.MODE_WORLD_WRITEABLE:  指定该SharedPreferences数据能被其他应用程序读,写



四:Editor中的方法:
SharedPreferences.Editor clear():清空SharedPreferences里所有数据
SharedPreferences.Editor putXxx(String key , xxx value): 向SharedPreferences存入指定key对应的数据,其中xxx 可以是boolean,float,int等各种基本类型据
SharedPreferences.Editor remove(): 删除SharedPreferences中指定key对应的数据项
boolean commit(): 当Editor编辑完成后,使用该方法提交修改

当你看完上面的内容,想必你对SharedPreferences有一定的了解了,接下来通过实际案例来加深一下理解。
先看一下布局,非常简单:

这是ui的代码:红色为EditText,蓝色为Button
<?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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.star.sharedpreferences.activity.MainActivity"
    android:orientation="vertical"
    android:gravity="center"
    android:background="#d7d5d5">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:orientation="horizontal">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:text="保存"
            android:background="#fff"
            android:textSize="20dp"/>

        <EditText
            android:id="@+id/save"
            android:layout_marginLeft="20dp"
            android:layout_width="100dp"
            android:layout_height="40dp"
            android:background="#fff"
            />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:orientation="horizontal"
        android:layout_marginTop="20dp">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:text="获取"
            android:textSize="20dp"
            android:background="#fff"
            android:id="@+id/textView" />

        <EditText
            android:id="@+id/get"
            android:layout_marginLeft="20dp"
            android:layout_width="100dp"
            android:layout_height="40dp"
            android:background="#fff"/>
    </LinearLayout>

    <Button
        android:id="@+id/bt_save"
        android:layout_marginTop="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="保存"
        android:background="#fff"/>

    <Button
        android:id="@+id/bt_get"
        android:layout_marginTop="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="获取"
        android:background="#fff"/>


</LinearLayout>
ui是不是很简单,初学者都能轻易的看懂,好了完成基本的ui布局后,我们再来看avtivity里:activity里的初始化控件直接用的butterknife,可以少些很多代码,让代码更简练。下面代码中红色部分是存储数据的方法(此处要注意:在editor编辑之后一定要调用commit方法提交一下,否则操作无效果),蓝色部分是获取数据的方法。
package com.example.star.sharedpreferences.activity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.example.star.sharedpreferences.R;
import com.example.star.sharedpreferences.utils.MyToast;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {


    @BindView(R.id.save)
    EditText mEditTextSave;
    @BindView(R.id.get)
    EditText mEditTextGet;
    @BindView(R.id.bt_save)
    Button mButtonSave;
    @BindView(R.id.bt_get)
    Button mButtonGet;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

    }

    @OnClick({R.id.bt_save, R.id.bt_get})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_save:
                String data = mEditTextSave.getText().toString().trim();
                if (TextUtils.isEmpty(data)){
                    MyToast.show(getApplicationContext(),"不能为空");
                    return;
                }
                SharedPreferences.Editor editor = getSharedPreferences("text",MODE_PRIVATE).edit();
                editor.putString("data",data);
                editor.commit();
                MyToast.show(getApplicationContext(),"数据保存成功");
                break;
            case R.id.bt_get:
                SharedPreferences sp = getSharedPreferences("text",MODE_PRIVATE);
                String dataGet = sp.getString("data","");
                mEditTextGet.setText(dataGet);
                MyToast.show(getApplicationContext(),"数据提取成功");
                break;
        }
    }
}


看完activity的代码,是不是觉着SharedPreferences很简单了,好了,本篇内容就到此结束了,欢迎各路大神指教以及各位初学者一起研讨。
QQ:2235792398












posted @ 2017-05-24 10:35  环球移动团队  阅读(397)  评论(0编辑  收藏  举报