SharedPreferences存储+SD卡存储
SharedPreferences
SharedPreferences简称Sp(后面都会称Sp),是一种轻量级的数据存储方式,采用Key/value的方式 进行映射,最终会在手机的/data/data/package_name/shared_prefs/目录下以xml的格式存在。
Sp通常用于记录一些参数配置、行为标记等!因为其使用简单,所以大多数开发者用起来很爽!
但是 请注意:千万不要使用Sp去存储量大的数据,也千万不要去让你的Sp文件超级大,否则会大大影响应用性能, 甚至出现ANR(程序无响应)
特点:
保存少量的数据,且这些数据的格式非常简单。 存储5种原始数据类型: boolean, float, int, long, String
比如应用程序的各种配置信息(如是否打开音效、是否使用震动效果、小游戏的玩家积分等),记住密码功能,音乐播放器播放模式。
技能要点: (1)如何存储数据 (2)如何获取数据
使用方式
步骤1: 得到SharedPreferences对象 getSharedPreferences(“文件的名称”,“文件的类型”);
(1).Context.MODE_PRIVATE:指定该SharedPreferences数据只能被应用程序读写
(2)MODE_APPEND:检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
以下不在建议使用
(3).Context.MODE_WORLD_READABLE:指定该SharedPreferences数据能被其他
应用程序读,但不能写。
(4).Context,MODE_WORLD_WRITEABLE:指定该SharedPreferences数据能被其他应用程序写,但不能读。
步骤2: 得到 SharedPreferences.Editor编辑对象
SharedPreferences.Editor editor=sp.edit();
步骤3: 添加数据
editor.putBoolean(key,value)
editor.putString()
editor.putInt()
editor.putFloat()
editor.putLong()
步骤4: 提交数据 editor.commit()或者apply()(推荐用这个.异步提交)
Editor其他方法: editor.clear() 清除数据 editor.remove(key) 移除指定key对应的数据
写数据
SharedPreferences preferences = getSharedPreferences("write", MODE_PRIVATE);
//TODO 2:获得编辑对象
SharedPreferences.Editor editor = preferences.edit();
//TODO 3:写数据
editor.putString("username","写数据");
editor.putInt("age",18);
editor.putBoolean("isMan",false);
editor.putFloat("price",12.4f);
editor.putLong("id",5425054250l);
//TODO 4:提交数据
editor.commit();
读数据
步骤1:得到SharedPreferences对象 getSharedPreferences(“文件的名称”,“文件的类型”);
步骤2:读取数据 String msg = sp.getString(key,defValue);
//TODO 1:得到SharedPreferences对象
//参数一 xml文件的名字 参数二 模式 MODE_PRIVATE 指定该SharedPreferences数据只能被本应用程序读写
SharedPreferences preferences = getSharedPreferences("write", MODE_PRIVATE);
//TODO 2:直接读取
//参数一 键 参数二 找不到的时候给默认值
String username=preferences.getString("username","");
int age=preferences.getInt("age",0);
boolean isMan=preferences.getBoolean("isMan",false);
float price=preferences.getFloat("price",0.0f);
long id=preferences.getLong("id",0l);
Toast.makeText(this, username+":"+age+":"+isMan+":"+price+":"+id, Toast.LENGTH_SHORT).show();
使用案例1
xml布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Main2Activity"
android:orientation="vertical"
android:gravity="center">
<EditText
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:id="@+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:id="@+id/password"
android:inputType="textPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<RelativeLayout
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<CheckBox
android:layout_alignParentLeft="true"
android:id="@+id/cb_remember"
android:text="记住密码"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_alignParentRight="true"
android:id="@+id/login"
android:text="登录"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
</LinearLayout>
java代码
private EditText username;
private EditText password;
private CheckBox cbRemember;
private Button login;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
init();
}
private void init() {
username = findViewById(R.id.username);
password = findViewById(R.id.password);
cbRemember = findViewById(R.id.cb_remember);
login = findViewById(R.id.login);
SharedPreferences preferences = getSharedPreferences("loadStory", MODE_PRIVATE);
String name = preferences.getString("name", "");
String pwd = preferences.getString("password", "");
Boolean isChecked = preferences.getBoolean("isChecked", false);
if(name!=null&&password!=null&&isChecked!=false){
username.setText(name);
password.setText(pwd);
cbRemember.setChecked(true);
}
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(cbRemember.isChecked()){
SharedPreferences preferences = getSharedPreferences("loadStory", MODE_PRIVATE);
SharedPreferences.Editor edit = preferences.edit();
edit.putString("name",username.getText().toString());
edit.putString("password",password.getText().toString());
edit.putBoolean("isChecked",true);
edit.commit();
}else {
SharedPreferences preferences = getSharedPreferences("loadStory", MODE_PRIVATE);
SharedPreferences.Editor edit = preferences.edit();
edit.putBoolean("isChecked",false);
edit.putBoolean("load", true);
edit.commit();
}
}
});
文件存储:
内部文件存储
openFileOutput
与java 操作文件没有区别.只是路径是唯一的
FileInputStream fileInputStream = null;
try {
fileInputStream= openFileInput("aa.json");
byte[] b = new byte[1024];
int len = 0;
while((len = fileInputStream.read(b)) != -1){
Log.i(TAG, "onClick: "+new String(b,0,len));
}
} catch (Exception e) {
e.printStackTrace();
}
外部文件存储(SD卡)
1.SD卡介绍:
一般手机文件管理 根路径 /storage/emulated/0/或者/mnt/shell/emulated/0
2.重要代码:
(1)Environment.getExternalStorageState();// 判断SD卡是否
(2)Environment.getExternalStorageDirectory(); 获取SD卡的根目录
(3)Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); 获取SD卡公开目录pictures文件夹
3.必须要添加读写SD卡的权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
private Button login;
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String externalStorageState = Environment.getExternalStorageState();
Log.i(TAG, "onCreate: "+externalStorageState);
File externalStorageDirectory = Environment.getExternalStorageDirectory();
Log.i(TAG, "onCreate: "+externalStorageDirectory.toString());
File externalStoragePublicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
Log.i(TAG, "onCreate: "+externalStoragePublicDirectory);
login = findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i(TAG, "onClick: ");
//运行时权限
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},100);
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//获取SD卡根路径:
File file = Environment.getExternalStorageDirectory();
FileOutputStream out = null;
try {
//创建输出流
out = new FileOutputStream(new File(file, "json.txt"));
out.write("呵呵呵俺哥哥".getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == 100){
if(grantResults != null && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this, "ok", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "不行啊", Toast.LENGTH_SHORT).show();
}
}
}
}
改进后的代码
把文件操作写到同意授权的回调方法里.
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == 100 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File file = Environment.getExternalStorageDirectory();
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(new File(file,"aa.json"));
fileOutputStream.write("aaa".getBytes());
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}else{
Toast.makeText(this, "没有权限", Toast.LENGTH_SHORT).show();
}
}