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

本文详细介绍了Android中SharedPreferences的存储原理、使用步骤及与SQLite数据库的对比,包括读取、存储数据的方法,以及其局限性和优势。通过具体代码示例展示了如何在布局中集成并操作SharedPreferences,为开发者提供了一套简洁高效的数据存储解决方案。

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

  一、根据Context获取SharedPreferences对象

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

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

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

  具体实现代码如下:

 1 package com.example.sharedpreference;
 2 import android.annotation.SuppressLint;
 3 import android.app.Activity;
 4 import android.content.SharedPreferences;
 5 import android.os.Bundle;
 6 import android.util.Log;
 7 import android.view.View;
 8 import android.widget.Button;
 9 import android.widget.EditText;
10 import android.widget.TextView;
11 import android.widget.Toast;
12 import com.example.lesson14.R;
13 
14 @SuppressLint("WorldWriteableFiles")
15 public class SharedPreferencesActivity extends Activity {
16     private EditText nameEditText;
17     private EditText ageEditText;
18     private Button saveBtn;
19     private Button showBtn;
20     private TextView resultText;
21     @Override
22     public void onCreate(Bundle savedInstanceState) {
23         super.onCreate(savedInstanceState);
24         setContentView(R.layout.preference_layout);
25         nameEditText = (EditText)this.findViewById(R.id.name);
26         ageEditText = (EditText)this.findViewById(R.id.age);
27         resultText = (TextView)this.findViewById(R.id.showText);             
28         saveBtn = (Button)this.findViewById(R.id.saveButton);
29         showBtn = (Button)this.findViewById(R.id.showButton);
30         saveBtn.setOnClickListener(listener);
31         showBtn.setOnClickListener(listener);
32 //        read a SharedPreferences
33 //      SharedPreferences mSP = getSharedPreferences("SP", MODE_PRIVATE);
34 //        String name = mSP.getString("NAME", "");
35 //        String age = mSP.getString("Age", "");
36 //        nameEditText.setText(name);
37 //        ageEditText.setText(age);
38 
39     }
40     
41     private View.OnClickListener listener = new View.OnClickListener(){
42         public void onClick(View v) {
43             Button button = (Button)v;
44             switch (button.getId()) {
45             case R.id.saveButton:
46                 SaveData();
47                 Toast.makeText(SharedPreferencesActivity.this, "保存成功", Toast.LENGTH_LONG).show();
48                 break;
49             case R.id.showButton:
50                 ShowData();
51                 break;
52             }
53         }
54     };
55     public void SaveData(){
56         String nameString = nameEditText.getText().toString();
57         int ageInt = Integer.parseInt(ageEditText.getText().toString());
58         if (nameString.equals("")|| ageInt == 0) {
59             Toast.makeText(getApplicationContext(), "username or age is null or uncrect,please input again", Toast.LENGTH_LONG).show();
60         }    else{
61             // get name,age
62                 SharedPreferences mSharedPreferences = getSharedPreferences("SP", MODE_PRIVATE);
63                 SharedPreferences.Editor editor = mSharedPreferences.edit();
64                 editor.putString("NAME", nameString);
65                 editor.putInt("Age", ageInt);
66                 editor.apply();
67                 Log.i("Tag", "name: "+nameString +" pwd:"+ageInt);
68     }
69 }
70     public void ShowData() {
71         SharedPreferences mSharedPreferences = getSharedPreferences("SP", MODE_PRIVATE);
72         String name = mSharedPreferences.getString("NAME", "");
73         int age =mSharedPreferences.getInt("Age",1 );
74         resultText.setText("姓名:" + name + ",年龄:" + age);        
75     }
76 }

 

这段代码执行过后,即在/data/data/com.test/shared_prefs目录下生成了一个SP.xml文件,一个应用可以创建多个这样的xml文件。图就不贴了

下面是它的布局

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:orientation="vertical" 
 4     android:layout_width="fill_parent"
 5     android:layout_height="fill_parent">
 6     <RelativeLayout
 7         android:layout_width="wrap_content"
 8         android:layout_height="wrap_content">
 9         <TextView android:layout_width="wrap_content"
10             android:layout_height="wrap_content" 
11             android:text="@string/name"
12             android:textSize="20px"
13             android:id="@+id/nameLable" />
14         <EditText android:layout_width="fill_parent"
15             android:layout_height="wrap_content" 
16             android:layout_toRightOf="@id/nameLable"
17             android:layout_alignTop="@id/nameLable"
18             android:layout_marginLeft="10px"
19             android:id="@+id/name" />
20     </RelativeLayout>
21     <RelativeLayout
22         android:layout_width="wrap_content"
23         android:layout_height="wrap_content">
24         <TextView android:layout_width="wrap_content"
25             android:layout_height="wrap_content" 
26             android:textSize="20px"
27             android:text="@string/age"
28             android:id="@+id/ageLable" />
29         <EditText android:layout_width="fill_parent"
30             android:layout_height="wrap_content" 
31             android:layout_toRightOf="@id/ageLable"
32             android:layout_alignTop="@id/ageLable"
33             android:layout_marginLeft="10px"
34             android:id="@+id/age" 
35             android:numeric="integer"/>
36     </RelativeLayout>
37     <RelativeLayout
38 
39         android:layout_width="wrap_content"
40         android:layout_height="wrap_content">
41         <Button android:layout_width="wrap_content"
42             android:layout_height="wrap_content" 
43             android:text="@string/button"
44             android:id="@+id/saveButton" />
45         <Button android:layout_width="wrap_content"
46             android:layout_height="wrap_content" 
47             android:text="@string/showButton"
48             android:layout_toRightOf="@id/saveButton"
49             android:layout_alignTop="@id/saveButton"
50             android:id="@+id/showButton" />
51     </RelativeLayout>
52     <TextView android:layout_width="fill_parent"
53             android:layout_height="wrap_content" 
54             android:textSize="20px"
55             android:id="@+id/showText" />
56 </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的函数的将会直接覆盖前面的内存数据,这样从一定程度上提高了很多效率。

转载于:https://www.cnblogs.com/lyc602/p/3867375.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值