android数据保存的三种方式
- 使用SharedPreferences存储简单的键值对数据
- 使用android的文件系统保存数据
使用SQite数据库存储
使用SharedPreferences 保存数据
Shared Preferences 适用于存储简单的键值对信息。比如应用的设置,用户信息,程序状态。使用SharedPrefence保存的信息在应用结束后仍然存在,下一次启动时可以从内存中获取这些信息,以提供良好的用户体验。
SharedPreferences 只能存储原始数据类型,即boolean,float,double,long ,int 和String。
SharedPrefences 接口提供了读写键值对的方法.SharedPrefences数据保存在/data/data/程序包名 下,需要用root账户才能进入Data目录,在终端执行下面命令,可以在android studio里的终端执行。
adb shell
进入shell,执行
su
获取root权限,然后
cd /data/data
进入相应的程序,即可查看该程序的SharedPrefences
- 获取SharedPrefences
一个应用有多个Activity,每个Activity可能有自己的SharedPreferences,或者有应用于整个应用的SharedPreferences,安卓提供了不同的方法来访问不同的SharedPreferences。使用Context的getSharedPreferences()可以根据SharedPreferences的名字获取Shareprefence对象,在程序的任何Context下都可调用这个方法,可以获取应用于整个应用的SharePreference,也可获取某个Activity下的SharedPrerences,如果SharedPreference不存在,则创建新的SharedPreferences。在Acitivty中,可以用getPreferences()获取和这个Acitivity相对应的SharedPreference,
下面的代码演示在Fragment中获取一个叫setting的SharedPreferences,使用private mode 来打开。private mode 表示这个文件只能由你的应用打开,其他应用不能打开。如果使用MODE_WORLD_READABLE或者MODE_WORLD_WRITEABLE,则其他应用可以访问你的SharedPreferences
Context context = getAcitivity()
String name = "setting";
SharedPreferences settingPref = context.getSharedPreferences(name,Context.MODE_PRIVATE);
要保证SharedPreference文件名的唯一性,使用包名加SharedPreference的名字的方式命名。
如果Acitivty中只有一个SharedPreference,使用getPreference方法来获得SharedPreference对象
SharedPreferences settingPref = getActivity().getPreference(Context.MODE_PRIVATE);
- 将数据写入到SharedPreferences
需要用SharePreferences.Editor对SharedPreferences进行写入操作,执行写入操作后用commit()提交写入操作。
下面代码将一个int 数据保存到settingPref中。
public static final String LEVEL = "level";
int level = 1;
SharedPreferences settingPref = getActivity.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settingPref.editor();
editor.putInt(LEVEL,level);
editor.commit();
- 从SharedPreference中读取数据
要读取SharedPreferences中的数据,使用相应的get方法即可,如读取int用getInt(),String 用getString()
下面代码读取前面存储的数值
SharedPreferens settingPref = getActivity.getPreferences(Context.MODE_PRIVATE);
int defaulLevel = settingPref.getInt(LEVEL);
- 实例:使用SharedPreference保存用户账号信息
下面用一个完整的实例来保存用户登入时的账户信息,如果用户选择保存用户的账号和密码项,则保存用户账号密码,用户下次登入时,不需要再重新输入账号密码。如果用户取消保存,则清除相关用户信息。
用户登入界面 /res/layout/login_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#85f5000c"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
>
<EditText
android:id="@+id/account_editor"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:hint="your account"
android:singleLine="true"
style="@style/Base.Widget.AppCompat.Button.Colored" />
<EditText
android:id="@+id/password_editor"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="your password"
android:layout_below="@id/account_editor"
android:singleLine="true"
style="@style/Base.Widget.AppCompat.Button.Colored"
/>
<CheckBox
android:id="@+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/password_editor"
android:text="remember password"
/>
<Button
android:id="@+id/login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/checkBox"
android:text="login"
/>
</RelativeLayout>
登入Activity Login.java
package com.example.test.testsharedpreference;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
/**
* A login screen that offers login via email/password.
*/
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
public static final String ACCOUNTPERFERANCE
= "com.example.test.testsharedpreference.account"; //the preferences file name
public static final String ACCOUNT = "acount";//the key used to store the account
public static final String PASSWORD = "password"; ///the key used to store password
public static final String SAVE = "save"; //the key to store the checkbox's state
private EditText mEditAcount; // acount editor
private EditText mEditPassword; // password editor
private CheckBox checkBox;
private Button mBtnLogin;
private SharedPreferences accountPref;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mEditAcount = (EditText) findViewById(R.id.account_editor);
mEditPassword = (EditText) findViewById(R.id.password_editor);
checkBox = (CheckBox) findViewById(R.id.checkBox);
mBtnLogin = (Button) findViewById(R.id.login);
mBtnLogin.setOnClickListener(this);
accountPref =
getSharedPreferences(ACCOUNTPERFERANCE, Context.MODE_PRIVATE);
boolean ischeckd = accountPref.getBoolean(SAVE,false);
//restore the user account if it was remember
if (ischeckd){
mEditAcount.setText(accountPref.getString(ACCOUNT,null));
mEditPassword.setText(accountPref.getString(PASSWORD,null));
checkBox.setChecked(ischeckd);
}else {
mEditAcount.setHint("your account");
mEditPassword.setHint("your password ");
checkBox.setChecked(false);
}
}
/**
* send the user to the main activity
* @param v
*/
@Override
public void onClick(View v) {
boolean isChcked = checkBox.isChecked();
SharedPreferences.Editor editor = accountPref.edit();
//save the account and password to the acountPres file if the user clicked remember password
if (isChcked){
editor.putString(ACCOUNT,mEditAcount.getText().toString());
editor.putString(PASSWORD,mEditPassword.getText().toString());
editor.putBoolean(SAVE, isChcked);
editor.commit();
}else {
editor.clear();
editor.commit();//all operator on a editor must commit
}
//start main Acitivty
Intent intent = new Intent(this,MainActivity.class);
startActivity(intent);
}
}
主界面 /res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</RelativeLayout>
主Activity MainAcitivity.java
package com.example.test.testsharedpreference;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}