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

Android数据的四种存储方式SharedPreferences、SQLite、Content Provider和File 之 —— SharedPreferences

2014-07-25 10:21 495 查看
除了SQLite数据库外,SharedPreferences也是一种轻型的数据存储方式,它的本质是基于XML文件存储key-value键值 对数据,通常用来存储一些简单的配置信息。其存储位置在/data/data/<包名>/shared_prefs目录下。 SharedPreferences对象本身只能获取数据而不支持存储和修改,存储修改是通过Editor对象实现。实现 SharedPreferences存储的步骤如下:

  一、根据Context获取SharedPreferences对象

  二、利用edit()方法获取Editor对象。

  三、通过Editor对象存储key-value键值对数据。

  四、通过commit()方法提交数据。

  具体实现代码如下:

package com.example.sharedpreference;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.lesson14.R;

@SuppressLint("WorldWriteableFiles")
public class SharedPreferencesActivity extends Activity {
private EditText nameEditText;
private EditText ageEditText;
private Button saveBtn;
private Button showBtn;
private TextView resultText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.preference_layout);
nameEditText = (EditText)this.findViewById(R.id.name);
ageEditText = (EditText)this.findViewById(R.id.age);
resultText = (TextView)this.findViewById(R.id.showText);
saveBtn = (Button)this.findViewById(R.id.saveButton);
showBtn = (Button)this.findViewById(R.id.showButton);
saveBtn.setOnClickListener(listener);
showBtn.setOnClickListener(listener);
//        read a SharedPreferences
//      SharedPreferences mSP = getSharedPreferences("SP", MODE_PRIVATE);
//        String name = mSP.getString("NAME", "");
//        String age = mSP.getString("Age", "");
//        nameEditText.setText(name);
//        ageEditText.setText(age);

}

private View.OnClickListener listener = new View.OnClickListener(){
public void onClick(View v) {
Button button = (Button)v;
switch (button.getId()) {
case R.id.saveButton:
SaveData();
Toast.makeText(SharedPreferencesActivity.this, "保存成功", Toast.LENGTH_LONG).show();
break;
case R.id.showButton:
ShowData();
break;
}
}
};
public void SaveData(){
String nameString = nameEditText.getText().toString();
int ageInt = Integer.parseInt(ageEditText.getText().toString());
if (nameString.equals("")|| ageInt == 0) {
Toast.makeText(getApplicationContext(), "username or age is null or uncrect,please input again", Toast.LENGTH_LONG).show();
}    else{
// get name,age
SharedPreferences mSharedPreferences = getSharedPreferences("SP", MODE_PRIVATE);
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString("NAME", nameString);
editor.putInt("Age", ageInt);
editor.apply();
Log.i("Tag", "name: "+nameString +" pwd:"+ageInt);
}
}
public void ShowData() {
SharedPreferences mSharedPreferences = getSharedPreferences("SP", MODE_PRIVATE);
String name = mSharedPreferences.getString("NAME", "");
int age =mSharedPreferences.getInt("Age",1 );
resultText.setText("姓名:" + name + ",年龄:" + age);
}
}


这段代码执行过后,即在/data/data/com.test/shared_prefs目录下生成了一个SP.xml文件,一个应用可以创建多个这样的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
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="fill_parent"
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
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="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/ageLable"
android:layout_alignTop="@id/ageLable"
android:layout_marginLeft="10px"
android:id="@+id/age"
android:numeric="integer"/>
</RelativeLayout>
<RelativeLayout

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/saveButton" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/showButton"
android:layout_toRightOf="@id/saveButton"
android:layout_alignTop="@id/saveButton"
android:id="@+id/showButton" />
</RelativeLayout>
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="20px"
android:id="@+id/showText" />
</LinearLayout>


View Code
SharedPreferences对象与SQLite数据库相比,免去了创建数据库,创建表,写SQL语句等诸多操作,相对而言更加方便,简洁。但是 SharedPreferences也有其自身缺陷,比如其职能存储boolean,int,float,long和String五种简单的数据类型,比 如其无法进行条件查询等。所以不论SharedPreferences的数据存储操作是如何简单,它也只能是存储方式的一种补充,而无法完全替代如 SQLite数据库这样的其他数据存储方式。

在上面的提交的步骤用到了两种方法:editor.commit();editor.apply();

注意:这两个方法的区别在于:

1. apply没有返回值而commit返回boolean表明修改是否提交成功

2. apply是将修改数据原子提交到内存, 而后异步真正提交到硬件磁盘, 而commit是同步的提交到硬件磁盘,因此,在多个并发的提交commit的时候,他们会等待正在处理的commit保存到磁盘后在操作,从而降低了效率。而apply只是原子的提交到内容,后面有调用apply的函数的将会直接覆盖前面的内存数据,这样从一定程度上提高了很多效率。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐