第8天SharedPreferences存储+SD卡存储

安卓的5大存储

在这里插入图片描述

一.SharedPreferences(******)

1.sp介绍

  • 保存少量的数据,且这些数据的格式非常简单。 存储5种原始数据类型: boolean, float, int, long, String

  • 比如应用程序的各种配置信息(如是否打开音效、是否使用震动效果、小游戏的玩家积分等),记住密码功能,音乐播放器播放模式。

  • 存哪了: /data/data/应用程序包名/shared_prefs/Xxx.xml文件,以Key-Value的格式存储

  • 技能要点: (1)如何存储数据 (2)如何获取数据

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()

Editor其他方法: editor.clear() 清除数据 editor.remove(key) 移除指定key对应的数据

 //SP写数据
    private void write() {
        //TODO  1:得到SharedPreferences对象
        //参数一 xml文件的名字 参数二 模式 MODE_PRIVATE 指定该SharedPreferences数据只能被本应用程序读写
        SharedPreferences preferences = getSharedPreferences("songdingxing", 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();
    }

3.如何读取数据

步骤1:得到SharedPreferences对象 getSharedPreferences(“文件的名称”,“文件的类型”);
步骤2:读取数据 String msg = sp.getString(key,defValue);

//读数据
    private void read() {
        //TODO  1:得到SharedPreferences对象
        //参数一 xml文件的名字 参数二 模式 MODE_PRIVATE 指定该SharedPreferences数据只能被本应用程序读写
        SharedPreferences preferences = getSharedPreferences("songdingxing", 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();
    }

3.单例模式封装工具类

复习一下单例模式:https://www.cnblogs.com/lixiansheng/p/11382462.html
记住:要求只有一个实例,必须会

public class SPUtils {
 //单例模式
    private static SPUtils spUtils;
    private SPUtils(Context context){
    }
    public synchronized static SPUtils getInstance(Context context){
        if(spUtils == null){
            spUtils = new SPUtils(context);
        }
        return spUtils;
    }
}    
/**
 * 项目中sp工具类的使用:单例模式
 */
public class SPUtils {
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    //单例模式
    private static SPUtils spUtils;
    private SPUtils(Context context){
        sharedPreferences = context.getSharedPreferences("yao",Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
    }
    public synchronized static SPUtils getInstance(Context context){
        if(spUtils == null){
            spUtils = new SPUtils(context);
        }
        return spUtils;
    }
    //存
    public void putString(String key,String value){
        editor.putString(key,value);
        editor.commit();
    }
    //取
    public String  getString(String key){
        return  sharedPreferences.getString(key,"");
    }
    //清空
    public void clear(){
        editor.clear();
        editor.commit();
    }
}

4.案例一:记住密码功能

在这里插入图片描述
(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"
    android:orientation="vertical"
    tools:context=".LoginActivity">
    <EditText
        android:hint="请输入用户名"
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></EditText>
    <EditText
        android:hint="请输入密码"
        android:id="@+id/passwod"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></EditText>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <CheckBox
            android:id="@+id/cb"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"></CheckBox>
        <TextView
            android:text="记住密码"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"></TextView>

    </LinearLayout>
    <Button
        android:id="@+id/bt_login"
        android:text="登陆"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></Button>

</LinearLayout>

(2)Java代码

package com.example.day8_shareprefrences_sdcard;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

public class LoginActivity extends AppCompatActivity {
    private EditText et_name,et_password;
    private Button bt_login;
    private CheckBox checkBox;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();

        String name = SPUtils.getInstance(this).getString("name");
        String password = SPUtils.getInstance(this).getString("password");
        et_name.setText(name);
        et_password.setText(password);
        if(!name.equals("")){
            checkBox.setChecked(true);
        }


    }

    private void initView() {
        et_name = findViewById(R.id.name);
        et_password = findViewById(R.id.passwod);
        bt_login = findViewById(R.id.bt_login);
        checkBox = findViewById(R.id.cb);
        bt_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });
    }
    //登陆
    private void login() {
        //TODO :判断是否选中
        if(checkBox.isChecked()){
            String name = et_name.getText().toString();
            String password = et_password.getText().toString();

            SPUtils.getInstance(this).putString("name",name);
            SPUtils.getInstance(this).putString("password",password);

        }else{
            SPUtils.getInstance(this).putString("name","");
            SPUtils.getInstance(this).putString("password","");
        }

    }
}

5.案例二:第一次打开app显示引导页,下次打开不显示引导页,直接显示主页面

6.案例三:音乐播放器播放模式

二.安卓6.0动态权限:

在这里插入图片描述
在这里插入图片描述

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //TODO 1:判断当前版本号
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){//23
                //TODO 2:动态授予权限
                //参数一 :string数组 参数二:请求码
                requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},101);
            
        }
    }
    //TODO 3:处理结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode  == 101){
            int grantResult = grantResults[0];//结果
            if(grantResult ==PackageManager.PERMISSION_GRANTED){
                Toast.makeText(this, "授予成功", Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(this, "授予失败", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

1.手机内存图

在这里插入图片描述

2.SD卡介绍:

1.一般手机文件管理 根路径 /storage/emulated/0/或者/sdcard/
在这里插入图片描述

2.重要代码:
(1)Environment.getExternalStorageState();// 判断SD卡是否挂载
(2)Environment.getExternalStorageDirectory(); 获取SD卡的根目录
(3)Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); 获取SD卡公开目录pictures文件夹
3.必须要添加读写SD卡的权限
在这里插入图片描述

3.代码

(1)添加读写SD卡的 权限
(2)FileUtils.java:四个方法:实现向SD卡中读写Bitmap图片和json字符串

 public class FileUtils {
    //方法1:向SD卡中写json串
    public static void write_json(String json)  {
        //判断是否挂载
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            //获取SD卡根路径:mnt/shell/emulated/0
            File file=Environment.getExternalStorageDirectory();
            FileOutputStream out=null;
            try {
                //创建输出流
                out= new FileOutputStream(new File(file,"json.txt"));
                out.write(json.getBytes());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally{
                if(out!=null){
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }
    //方法2:从SD卡中读取json串
    public static String read_json() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File file = Environment.getExternalStorageDirectory();
            FileInputStream inputStream = null;
            StringBuffer sb=new StringBuffer();
            try {
                inputStream=new FileInputStream(new File(file,"json.txt"));
                byte[] b=new byte[1024];
                int len=0;
                while((len=inputStream.read(b))!=-1){
                    sb.append(new String(b,0,len));
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally{
                if(inputStream!=null){
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return  sb.toString();
        }else{
            return "";
        }
    }

    //方法3:从SD卡中读取一张图片
    public  static  Bitmap read_bitmap(String filename) {//filename图片名字
        Bitmap bitmap=null;
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            File file=Environment.getExternalStorageDirectory();
            File file1 = new File(file, filename);
            //BitmapFactory可以直接根据SD卡图片路径转成一个bitmap对象
             bitmap= BitmapFactory.decodeFile(file1.getAbsolutePath());
        }
        return bitmap;
    }
    //方法4:网络下载一张图片存储到SD卡中
    public  static  void write_bitmap(String url) {//网址
       new MyTask().execute(url);
    }
    static class MyTask extends AsyncTask<String,String,String> {
        @Override
        protected String doInBackground(String... strings) {
            FileOutputStream out=null;
            InputStream inputStream=null;//网络连接的输入流
            HttpURLConnection connection=null;//向SD卡写的输出流
            try {
                URL url= new URL(strings[0]);
                connection= (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(5*1000);
                connection.setReadTimeout(5*1000);
                if (connection.getResponseCode()==200){
                    inputStream = connection.getInputStream();
                    //TODO 获取SD卡的路径
                    if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {//是否挂载
                        File file = Environment.getExternalStorageDirectory();
                        out = new FileOutputStream(new File(file,"xiaoyueyue.jpg"));
                        byte[] bytes=new byte[1024];
                        int len=0;
                        while((len=inputStream.read(bytes))!=-1){
                            out.write(bytes,0,len);
                        }
                    }
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                //关流
                if(out!=null){
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(inputStream!=null){
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(connection!=null){
                    connection.disconnect();
                }
            }
            return null;
        }
    }
}

三.SQLite数据库存储:第9单元讲(******)

四.ContentProvider存储:第10+11单元讲(******)

五.网络存储:java后台:云服务

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值