SharedPreferences储存+SD卡储存

SharedPreferences

写数据

    //文件的名字
    final SharedPreferences login = getSharedPreferences("login", MODE_PRIVATE);
    //获取编辑的对象
    SharedPreferences.Editor edit = login.edit();
    //编写数据
    edit.putBoolean("boolean",true);
    edit.putFloat("float",11f);
    edit.putInt("int",100);
    edit.putLong("long",111);
    edit.putString("string","广安");
    //提交数据
    edit.commit();

读数据

		btnClick.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //文件的名字
            SharedPreferences login1 = getSharedPreferences("login", MODE_PRIVATE);
            //直接获取数据
            boolean aBoolean = login1.getBoolean("boolean", false);
            String string = login1.getString("string", "");
            int anInt = login1.getInt("int", 0);
            long aLong = login1.getLong("long", 0l);
            float aFloat = login1.getFloat("float", 0.0f);
            Toast.makeText(MainActivity.this, aBoolean+"-"+string+"-"+anInt+"-"+aLong+"-"+aFloat, Toast.LENGTH_SHORT).show();

        }
    });

注意事项

1、查找所写的文件是在右下角的 Device File Explorer 中的Date/Date 下去找到你的所在模块的包名。
2、必须得在运行完之后才能找到,也就才会有数据,不然没有数据。
3、写数据的时候getSharedPreferences() 之后还得获取编辑的对象才能写数据,而读取数据确实直接读取。
4、文件的模式一般只用一种:MODE_PRIVATE。

案列(登录 记住密码)

代码展示
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=".LoginActivity"
android:orientation="vertical">
<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/username"/>
<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/password"/>
<CheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/ck"
    />
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="登录"
    android:textSize="30sp"
    android:id="@+id/btn_login"/>
##### acticity中的代码
private EditText username;
private EditText password;
private CheckBox ck;
private Button btn_Login;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    //初始化控件
    username = (EditText) findViewById(R.id.username);
    password = (EditText) findViewById(R.id.password);
    ck = (CheckBox) findViewById(R.id.ck);
    btn_Login = (Button) findViewById(R.id.btn_login);
    //在加载APP之前先获取数据  判断是否记住密码(第二次登录)
    final SharedPreferences welcome = getSharedPreferences("welcome", MODE_PRIVATE);
    boolean ischeck = welcome.getBoolean("ischeck", false);
    //根据是否记住密码进行下一步
    if(ischeck){
        //读取用户名 密码 赋值给控件
        ck.setChecked(true);
        String username1 = welcome.getString("username", "");
        String password1 = welcome.getString("password", "");
        username.setText(username1);
        password.setText(password1);
    } else{
        //反之给记住密码的checkbox 添加false
        ck.setChecked(false);
    }
    //第一次登录的时候 点击登录的时候
    btn_Login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //获取输入框的数据
            String u = username.getText().toString();
            String p = password.getText().toString();
            //判断 记住密码 checlbox 的状态
            if(ck.isChecked()){
                //获取编辑对象  再把数据给存进去
                SharedPreferences.Editor edit = welcome.edit();
                edit.putString("username",u);
                edit.putString("password",p);
                edit.putBoolean("ischeck",true);
                //提交
                edit.commit();
            } else{
                //反之 把记住密码 false 的状态提交  以便于第二次登录的时候使用
                SharedPreferences.Editor edit = welcome.edit();
                edit.putBoolean("ischeck",false);
                edit.commit();
            }
        }
    });
}
效果展示
第一次登陆场景

在这里插入图片描述

点击记住密码 并且登录之后 退出 第二次登录

在这里插入图片描述

注意事项

全程用于储存的对象可以是一个
final SharedPreferences welcome = getSharedPreferences(“welcome”, MODE_PRIVATE);
这样 方便写代码,只需要用的时候获取编辑对象即可。

文件储存

内部文件储存

写数据(openFileOutput)

FileOutputStream fileOutputStream = null;
try {
fileOutputStream = openFileOutput(“aa.json”, MODE_PRIVATE);
fileOutputStream.write(“hello”.getBytes());
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}

读数据(openFileInput)

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

获取网络权限和读取权限



代码展示

private Button read;
private Button write;
private String s;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //判断是否需要动态授权
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
        //动态的响应码
        String[] str = {Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_APN_SETTINGS};
        requestPermissions(str,100);
    }

    write = (Button) findViewById(R.id.write);
    read = (Button) findViewById(R.id.read);
    //读取SD卡中的内容
    write.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            File file = Environment.getExternalStorageDirectory();
            try {
                FileInputStream is = new FileInputStream(new File(file, "a.txt"));
                int len = 0;
                byte[] bys = new byte[1024];
                while ((len = is.read(bys)) != -1){
                    s = new String(bys, 0, len);
                }
                Toast.makeText(MainActivity.this, ""+s, Toast.LENGTH_SHORT).show();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

    read.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //获取SD卡的根目录路径
            File file = Environment.getExternalStorageDirectory();
            try {
                FileOutputStream os = new FileOutputStream(new File(file, "a.txt"));
                os.write("哈哈".getBytes());
                os.flush();
                os.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } 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, "同意", Toast.LENGTH_SHORT).show();
        } else{
            Toast.makeText(this, "不同意", Toast.LENGTH_SHORT).show();
        }
    }
}
效果展示
第一次登录进去会问你是否同意,也就是以上代码后面的效果,如果不同意会直接退出去,同意了才可以获取SD卡内容

在这里插入图片描述

点击读取之后会吐司SD卡的内容

在这里插入图片描述

注意事项

在这里插入图片描述

SD卡案列

代码展示

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">
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="下载图片"
    android:id="@+id/xia"
    android:textSize="30sp"/>
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="读取图片"
    android:id="@+id/du"
    android:textSize="30sp"/>
<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/iv_iamge"
    android:src="@mipmap/ic_launcher"/>
acticity的代码

private Button xia;
private Button du;
private ImageView iv_Iamge;
private Bitmap bitmap1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    xia = (Button) findViewById(R.id.xia);
    du = (Button) findViewById(R.id.du);
    iv_Iamge = (ImageView) findViewById(R.id.iv_iamge);
    du.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            File file = Environment.getExternalStorageDirectory();

// File file1 = new File(file,file.getName());
// Bitmap bitmap = BitmapFactory.decodeFile(file1.getAbsolutePath());
try {
bitmap1 = BitmapFactory.decodeStream(new FileInputStream(new File(file, “xiao.jpg”)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
iv_Iamge.setImageBitmap(bitmap1);
}
});

    xia.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            new MyTask().execute("https://dss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1035415831,1465727770&fm=26&gp=0.jpg");
        }
    });
}
异步任务的代码

class MyTask extends AsyncTask<String,Void,String> {
@Override
protected String doInBackground(String… strings) {
String urlString = strings[0];
InputStream is = null;
try {
URL url = new URL(urlString);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod(“GET”);
connection.setConnectTimeout(10005);
connection.setReadTimeout(1000
60);
connection.connect();
if(connection.getResponseCode() == 200){
is = connection.getInputStream();
//获取SD卡的根目录
File file = Environment.getExternalStorageDirectory();
FileOutputStream os = new FileOutputStream(new File(file, “xiao.jpg”));
int len = 0;
byte[] bys = new byte[1024];
while ((len = is.read(bys)) != -1){
os.write(bys,0,len);
}
return “ok”;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    if(s != null){
        Log.i("---","下载完成");
    }
}

}

效果展示

点击下载图片 然后读取图片之后

在这里插入图片描述

注意事项

异步任务的3个参数
第一个是: 网址
第二个是: 进度条, 没有就可以写Void
第三个是: 返回值

然后 代码中下载完成的提示我是在控制台输出的。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值