android数据持久化存储(2)
SharedPreferences
将数据存储到SharedPreferences中:
不同于文件的存储方式,SharedPreferences是使用键值对的方式来存储数据的。也就是说当保存一条数据的时候,需要给这条数据提供一个对应的健,这样再读取数据的时候就可以通过这个健把相应的值去出来,而SharedPreferences还支持多种不同的数据类型存储,如果存储的数据类型是整形,那么读取出来的数据也是整形,存储数据是一个字符串,那么读取出来的数据仍然是字符串。这样就可以明显的感受到使用SharedPreferences来进行数据持久话要比使用文件方便很多。
具体的使用方法是:
首先要获取到SharedPreferences对象,android中主要提供了三种方法用于得到SharedPreferences对象:
1context类中的getSharedPreferences()方法
此方法接受两个参数,第一个参数用于指定SharedPreferences文件的名称,如果文件不存在则会创建i一个,第二个参数用于指定操作模式,主要有两种模式可以选择,MODE_PRIVATE和MODE_MULTI_PROCESS,MODE_PRIVATE仍然是默认的操作模式,和直接传入0效果相同,表示只有当前的应用程序才可以对这个SharedPreferences文件进行读写。MODE_MULTI_PROCESS则一般是用于会有多个进程中对同一个SharedPreferences文件进行读写的情况。
2 Activity类中的getPreferences()方法
这个方法只能接受一个操作模式参数,因为使用这个方法时会自动将当前活动的类名作为SharedPreferences的文件名。
3 SharedPreferences类中的getDefaultSharedPreferences()方法
这是一个静态方法,他接受一个context参数,并自动使用当前应用程序的包名作为前缀来命令SharedPreferences文件。
得到SharedPreferences对象之后,就可以开始向SharedPreferences文件中存储数据了,主要按照下面三个补助进行实现。
1 调用SharedPreferences对象的edit()方法来获取一个Sharedpreferences.Editor对象。
2 向SharedPreferences.Editoe对象中添加数据,比如添加一个字符串就使用putString()方法。
3 调用commit()方法将添加的数据提交,从而完成数据存储操作。
从SharedPreferences中读取数据:
从SharePreferences中读取数据相当简单,SharedPreferences提供了一系列的get方法用来存储的数据进行读取,每个get方法都对应了SharedPreferences.
具体实例:实现记住密码功能
布局文件代码:
<?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: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="com.example.apple.servicetest.MainActivity" android:orientation="vertical"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/user_name" android:hint="input your name" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/user_passwd" android:hint="password"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/remember_pass"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="remember passworld"/> </LinearLayout> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/login" android:text="save data"/> </LinearLayout>
功能代码
package com.example.apple.servicetest; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Message; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class MainActivity extends AppCompatActivity { private SharedPreferences pref; private SharedPreferences.Editor editor; private EditText username; private EditText password; private Button login; private CheckBox rememberpass; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); pref= PreferenceManager.getDefaultSharedPreferences(this); username=(EditText)findViewById(R.id.user_name); password=(EditText)findViewById(R.id.user_passwd); rememberpass=(CheckBox)findViewById(R.id.remember_pass); login=(Button)findViewById(R.id.login); boolean isremember=pref.getBoolean("remember_password",false); if (isremember){ String account=pref.getString("account",""); String passwd=pref.getString("password",""); username.setText(account); password.setText(passwd); rememberpass.setChecked(true); } login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String account=username.getText().toString(); String passwd=password.getText().toString(); editor=pref.edit(); if (rememberpass.isChecked()){ editor.putBoolean("remember_password",true); editor.putString("account",account); editor.putString("password",passwd); }else { editor.clear(); } editor.commit(); Intent intent=new Intent(MainActivity.this,second.class); startActivity(intent); finish(); } }); } public String load(){ FileInputStream in=null; BufferedReader reader=null; StringBuilder content=new StringBuilder(); try { in=openFileInput("data"); reader=new BufferedReader(new InputStreamReader(in)); String line=""; while ((line=reader.readLine())!=null){ content.append(line); } }catch (IOException e){ e.printStackTrace(); }finally { if (reader!=null){ try{ reader.close(); }catch (IOException e){ e.printStackTrace(); } } return content.toString(); } } public void save(String inputText) { FileOutputStream out = null; BufferedWriter writer = null; try { out = openFileOutput("data", Context.MODE_PRIVATE); writer = new BufferedWriter(new OutputStreamWriter(out)); writer.write(inputText); } catch (IOException e) { e.printStackTrace(); } finally { try { { if (writer != null) { writer.close(); } } } catch (IOException e) { e.printStackTrace(); } } } }
效果图为: