一,SharedPreferences:
(1)简称:SP存储
(2)位置:用它时,将会默认在data/data/包名/下创建一个名字为:shared_prefs的文件夹,
然后再在shared_prefs目录下创建你命名的文件.
(3)创建步骤:
<1>获取上下文的SharedPreferences对象
<2>调用刚刚获取的SharedPreferences对象的editor()方法,返回一个Editor对象
<3>用editor对象的putXXX(参数1 ,参数2):方法来存储数据,是类似一个map集合存储
<4>调用editor对象的commit()方法提交数据
现在一般用apply()提交,以前用commit()
(4)创建举例:
//1,获取上下文对象的SharedPreferences对象 ,第一个参数:文件名,第二个:权限类型
SharedPreferences sp = context.getSharedPreferences("configure" , Context.MODE_PRIVATE);
//2,获取Editor对象
Editor editor = sp.edit();
//3.存放数据
editor.putString("username" , username);
editor.putString("password" , password);
editor.putFloat("float" , 12);
//4.用editor.commit()方法提交
editor.commit();
第4步,改为:
editor.apply(); //以前都是用commit
(5)取出数据:
<1>获取刚刚创建的SharedPreferences对象,并传入文件名和mode类型
<2> 调用SharedPreferences对象的getXXX方法,取出键值对,
如:
/调用方法保存
SaveLogin.saveLoginMessage(LoginActivity.this , strName , strWord );
//1.获取SharedPreferences对象
SharedPreferences sp = getSharedPreferences("configure" , Context.MODE_PRIVATE);
String sName = sp.getString("username" , "");
String sWord = sp.getString("password" , "");
Float flt = sp.getFloat("float" , 0);
Toast.makeText(LoginActivity.this , "名字是:" + sName + "\n密码: " +
sWord + "\n 值:" + flt, Toast.LENGTH_SHORT).show();
2,commit()与apply()比较:为什么现在常用apply提交?
看一下源码注释,大概意思:
/**commit与apply()的区别
* 1. apply没有返回值而commit返回boolean表明修改是否提交成功
2. apply是将修改数据原子提交到内存, 而后异步真正提交到硬件磁盘,
而commit是同步的提交到硬件磁盘,因此,在多个并发的提交commit的时候,
他们会等待正在处理的commit保存到磁盘后在操作,从而降低了效率。
而apply只是原子的提交到内容,后面有调用apply的函数的将会直接覆盖前面的内存数据,
这样从一定程度上提高了很多效率。
3. apply方法不会提示任何失败的提示。
由于在一个进程中,sharedPreference是单实例,一般不会出现并发冲突,
如果对提交的结果不关心的话,建议使用apply,当然需要确保提交成功且有后续操作的话,
还是需要用commit的*/
3,利用sp最常见的例子无疑就是记住用户名和密码,例子在最下面....
二,File存储:(java文件存取大家都很熟悉,就,,,)
1,简意:利用文件来存储
2,向文件写入:
相关:FileOutputStream---文件输出流
BufferedWriter
3,从文件中读取数据:
相关:FileInputStream
BufferedReader
很简单的例子:
/**
* FiLe存储监听
* @param view
*/
@OnClick(R.id.file_save)
public void save(View view){
//获取输入
String str = mEdtInput.getText().toString().trim();
//判空:null或者空字符串
if(!TextUtils.isEmpty(str)){
//文件输出流与BufferedWriter
FileOutputStream out = null;
BufferedWriter writer = null;
//写入
try{
out = openFileOutput("data" , Context.MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write(str);
}catch (IOException e){
e.printStackTrace();
}finally {
if(writer != null){
try {
//关闭流
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Toast.makeText(MainActivity.this , "save Success" , Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this , "save failure" , Toast.LENGTH_SHORT).show();
}
}
/**
* 文件读取
* @param view
*/
@OnClick(R.id.read)
public void read(View view){
//文件输入流与BufferedReader对象
FileInputStream in = null;
BufferedReader reader = null;
//用于追加结果
StringBuffer content = new StringBuffer();
//读取
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 {
try {
//关闭流
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//结果:判空并显示
String result = content.toString();
if(!TextUtils.isEmpty(result)){
mEdtInput.setText(result);
mEdtInput.setSelection(result.length());
Toast.makeText(MainActivity.this , "read Success" , Toast.LENGTH_SHORT).show();
}else {
mEdtInput.setText("");
Toast.makeText(MainActivity.this , "read failure" , Toast.LENGTH_SHORT).show();
}
}
4:常用方法
//判断是否插入sd卡
Environment.getExternalStorageState();
//获取外部存储器路径,也就是SD卡目录
Environment.getExternalStorageDirectory();
//(3)常用读写sd卡文件方法
FileInputStream,FileOutputStream, FileReader, FileWriter
//在应用程序下获取或创建name对应的子目录
public File getDir(String name, int mode)
//获取该应用程序的数据文件的绝对路径
File getFilesDir();
三,一个记住用户名和密码例子:
布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="60dp">
<TextView
android:layout_width="90dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:textSize="18sp"
android:text="Account:" />
<EditText
android:id="@+id/account"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center_vertical"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="60dp">
<TextView
android:layout_width="90dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:textSize="18sp"
android:text="Password:" />
<EditText
android:id="@+id/password"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center_vertical"
android:inputType="textPassword" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<CheckBox
android:id="@+id/remember_pass"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:text="Remember password" />
</LinearLayout>
<Button
android:id="@+id/login"
android:layout_width="match_parent"
android:layout_height="60dp"
android:text="Login" />
</LinearLayout>
Activity:
public class LoginActivity extends AppCompatActivity {
//用户名
@ViewInject(R.id.account)
private EditText accountEdit;
//密码
@ViewInject(R.id.password)
private EditText passwordEdit;
//登录
@ViewInject(R.id.login)
private Button login;
//记住密码checkBox
@ViewInject(R.id.remember_pass)
private CheckBox rememberPass;
//pref,pref.editor对象
private SharedPreferences pref;
private SharedPreferences.Editor editor ;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//初始化inject
ViewUtils.inject(this);
//获取pref
pref = PreferenceManager.getDefaultSharedPreferences(this);
//判断是否选中记住密码
boolean isRemember = pref.getBoolean("remember_password" , false);
if(isRemember){
String account = pref.getString("account" , "");
String password = pref.getString("password" , "");
accountEdit.setText(account);
passwordEdit.setText(password);
rememberPass.setChecked(true); //设置选中
}
}
/**
* 登录
* @param view
*/
@OnClick(R.id.login)
public void toLogin(View view){
//获取用户名和密码
String account = accountEdit.getText().toString().trim();
String password = passwordEdit.getText().toString().trim();
//判断用户名和密码是否正确
if(account.equals("maiyu") && password.equals("123456")){
//获取pref.edit()
editor = pref.edit();
//判断是否选中记住密码,是的话存储pref
if(rememberPass.isChecked()){
editor.putBoolean("remember_password" , true);
editor.putString("account" , account);
editor.putString("password" , password);
}else {
editor.clear(); //不存储
}
editor.apply();
//跳转
Intent intent = new Intent(LoginActivity.this , TestActivity.class);
startActivity(intent);
finish();
}else {
//密码或用户名错误
Toast.makeText(LoginActivity.this , "account or password is unvalid",Toast.LENGTH_SHORT).show();
}
}
}