您的位置:首页 > 移动开发 > Android开发

Android存储之ShredPreferences

2016-04-08 16:53 483 查看
If you have a relatively small collection of key-values that you’d like to save, you should use the SharedPreferences APIs. A SharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them. Each SharedPreferences file is managed by the framework and can be private or shared.

This class shows you how to use the SharedPreferences APIs to store and retrieve simple values

根据官方介绍SharedPreferences适合存储比较小的键值对形式的数据,项目中也经常用到比如登录之后记录一些信息,和登录状态,实现免登陆等等等吧!现在我们来用下他们的API



首先我们在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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="bs.sharedpreferences.MainActivity">

<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<Button
android:id="@+id/write"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="write"
android:text="Write" />

<Button
android:id="@+id/read"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="read"
android:text="Read" />
</LinearLayout>


2.JAVA直接看代码吧!!!!!!

package bs.sharedpreferences;

import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

SharedPreferences mSharedPreferences;
SharedPreferences.Editor mEditor;
private TextView mValue;

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

mValue = (TextView) findViewById(R.id.text);

/**
* 假如需要一个SharedPreferences可用这个内部是通过调用getLocalClassName()方法进行作为文件名
*/
mSharedPreferences = getPreferences(MODE_PRIVATE);

/**
* 假如你有多个存储文件就用这个,文件名自己定义
*/
//mSharedPreferences = this.getSharedPreferences("name", MODE_PRIVATE);
mEditor = mSharedPreferences.edit();

}

public void write(View view) {

/***
*想包存值就put 任意put
*/
mEditor.putString("key", "已保存");
/**没有返回值,而commit返回个boolean值
* 如果不考虑返回结果尽量用apply方法效率会高点
*/
mEditor.apply();
//        mEditor.commit();

}

public void read(View view) {

/**
* 当看到显示已保存说明我们已经取到值
*/
mValue.setText(mSharedPreferences.getString("key", "没有取到值"));

}

}


我这里有个方便的工具类,相信你会用的到的 :

http://blog.csdn.net/u014360817/article/details/51065634
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 存储