数据存储之Preferences

来源:互联网 发布:php 反射机制 编辑:程序博客网 时间:2024/05/18 05:33

数据存储之Preferences

这里介绍的PreferencesAndroid系统中应用程序内部的轻量级的数据存储方案。我们一般用他来存储一些应用程序的配置信息,例如实际项目中,我们可以将用户的个人信息记录在这里。当然了,Preferences一般使用来存储和查询简单的数据类型的而设的,是我们的应用程序对于数据的处理更加灵活实用,它支持存储的数据类型包括:booleanintlongfloatString等。存储数据的方式是以类似于map的键值对来记录存储数据,将数据存储放在应用程序的私有文件夹下,如果我们想要将这个生成的Preferences文件删除掉的话,我们可以使用adb工具,进入到Android系统中,将对应的Preferences文件删除掉即可。

我们可以使用两种方式来获得SharedPreferences对象,而且这两种方法获得的对象并不相同,区别如下:

A、使用Context的方法getSharedPreferences获取的SharedPreferences对象可以被同一个应用程序中的其他组件共享这个对象。

B、使用Activity的方法getPreferences获得的SharedPreferences对象只能被相应的应用程序所访问操作。

注意:实际上,Preferencs文件经过转义之后是xml文件。

下面举例说明,具体代码如下:

Main.xml:

<RelativeLayout 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"

    tools:context=".DataStorePreferencesAct" >

    <EditText

        android:id="@+id/et"

        android:layout_width="200dp"

        android:layout_height="wrap_content"

        android:layout_centerHorizontal="true"

        android:layout_centerVertical="true"

        android:hint="@string/hint_text"/>

    <TextView

        android:id="@+id/tip"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_centerHorizontal="true"

        android:layout_below="@+id/et"/>

</RelativeLayout>

DataStorePreferences.java:

package com.david.datastorepreferences;

import android.app.Activity;

import android.content.SharedPreferences;

import android.os.Bundle;

import android.widget.EditText;

import android.widget.TextView;

public class DataStorePreferencesAct extends Activity {

EditText et;

TextView tip;

SharedPreferences sp;

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        

        et = (EditText) findViewById(R.id.et);

        tip = (TextView) findViewById(R.id.tip);

        

        sp = this.getPreferences(MODE_PRIVATE);

        String result = sp.getString("STATUS",null);

        

        if (result != null)

         tip.setText("您上一次记住的数据是:" + result);

        else

         tip.setText("当前的Preferences中并未写入数据哦!");

    }

    

    protected void onDestroy() {

     SharedPreferences.Editor edit = sp.edit();

     edit.putString("STATUS",et.getText().toString());

     edit.commit();

    

     super.onDestroy();

    }

}

效果图如下,当我们推出应用程序的时候,会将相关内容写入到SharedPreferences中,在下次进入应用程序时将存储的内容显示在屏幕中,效果图如下:

在这里,我只列出了使用ActivitygetPreferences方法获取对象的方式;而使用另一种获取方式的使用方法同理。下一篇文章的内容是Android系统中的轻量级数据库SQLite的使用方法分析。敬请期待!!!

希望兴趣相投的同学来一起研究学习!群号是:179914858