SharedPreferences储存初试

#登录以及记住密码

package com.bawei.a20200622homework;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

public class Main2Activity extends AppCompatActivity {

    private Button downjson;
    private TextView jsontext;
    private Button downpic;
    private ImageView pic;
    private Button showjson;
    private Button showpic;


    @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) {
            Toast.makeText(this, "同意", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "不同意", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        //动态请求
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
        }

        showjson = findViewById(R.id.showjson);
        showpic = findViewById(R.id.showpic);
        downjson = findViewById(R.id.downjson);
        jsontext = findViewById(R.id.jsontext);
        downpic = findViewById(R.id.downpic);
        pic = findViewById(R.id.pic);

        downjson.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String json = "{\n" +
                        "  \"rst\": 10086,\n" +
                        "  \"msg\": \"真香\",\n" +
                        "  \"data\": {\n" +
                        "    \"cookie\": \"小龙虾,葱,姜,蒜,辣椒酱\"\n" +
                        "  }\n" +
                        "}";
                Gson gson = new Gson();
                JavaBean javaBean = gson.fromJson(json, JavaBean.class);
                File file = Environment.getExternalStorageDirectory();
                try {
                    FileOutputStream fileOutputStream = new FileOutputStream(new File(file, "json.txt"));
                    fileOutputStream.write(javaBean.getData().getCookie().getBytes());
                    fileOutputStream.flush();
                    fileOutputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        showjson.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File file = Environment.getExternalStorageDirectory();
                try {
                    FileInputStream fileInputStream = new FileInputStream(new File(file, "json.txt"));
                    byte[] bytes = new byte[1024];
                    int len = 0;
                    StringBuffer stringBuffer = new StringBuffer();
                    while ((len = fileInputStream.read(bytes)) != -1) {
                        String s = new String(bytes, 0, len);
                        stringBuffer.append(s);
                    }
                    jsontext.setText(stringBuffer.toString());
                    fileInputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });

        showpic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File file = Environment.getExternalStorageDirectory();
                try {
                    FileInputStream fileInputStream = new FileInputStream(new File(file, "image.jpg"));
                    Bitmap bitmap = BitmapFactory.decodeStream(fileInputStream);
                    pic.setImageBitmap(bitmap);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    public void loadImage(View view) {
        downpic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                downpic(v);
            }
        });
    }

    private void downpic(View v) {
        try {
            URL url = new URL("https://img.ivsky.com/img/tupian/pre/202001/19/dalou.jpg");
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.connect();
            if (connection.getResponseCode() == 200) {
                InputStream is = connection.getInputStream();
                File file = Environment.getExternalStorageDirectory();
                FileOutputStream outputStream = new FileOutputStream(new File(file, "a.jpg"));
                byte[] bytes = new byte[1024];
                int len = 0;
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    while ((len = is.read(bytes)) != -1) {
                        outputStream.write(bytes, 0, len);
                        outputStream.flush();
                    }
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

#对应的布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:gravity="center"
    tools:context=".MainActivity"
    android:background="@mipmap/b">

    <EditText
        android:text=""
        android:id="@+id/user"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:hint="用户名"></EditText>

    <EditText
        android:text=""
        android:id="@+id/pwd"
        android:layout_marginTop="50dp"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:hint="密码"></EditText>
    <CheckBox
        android:id="@+id/check"
        android:layout_marginTop="100dp"
        android:layout_marginLeft="0dp"
        android:text="记住密码"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"></CheckBox>
    <Button
        android:onClick="login"
        android:layout_marginTop="130dp"
        android:text="登录"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"></Button>
</RelativeLayout>

#json解析、图片下载及显示

package com.bawei.a20200622homework;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

public class Main2Activity extends AppCompatActivity {

    private Button downjson;
    private TextView jsontext;
    private Button downpic;
    private ImageView pic;
    private Button showjson;
    private Button showpic;


    @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) {
            Toast.makeText(this, "同意", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "不同意", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        //动态请求
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
        }

        showjson = findViewById(R.id.showjson);
        showpic = findViewById(R.id.showpic);
        downjson = findViewById(R.id.downjson);
        jsontext = findViewById(R.id.jsontext);
        downpic = findViewById(R.id.downpic);
        pic = findViewById(R.id.pic);

        downjson.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String json = "{\n" +
                        "  \"rst\": 10086,\n" +
                        "  \"msg\": \"真香\",\n" +
                        "  \"data\": {\n" +
                        "    \"cookie\": \"小龙虾,葱,姜,蒜,辣椒酱\"\n" +
                        "  }\n" +
                        "}";
                Gson gson = new Gson();
                JavaBean javaBean = gson.fromJson(json, JavaBean.class);
                File file = Environment.getExternalStorageDirectory();
                try {
                    FileOutputStream fileOutputStream = new FileOutputStream(new File(file, "json.txt"));
                    fileOutputStream.write(javaBean.getData().getCookie().getBytes());
                    fileOutputStream.flush();
                    fileOutputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        showjson.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File file = Environment.getExternalStorageDirectory();
                try {
                    FileInputStream fileInputStream = new FileInputStream(new File(file, "json.txt"));
                    byte[] bytes = new byte[1024];
                    int len = 0;
                    StringBuffer stringBuffer = new StringBuffer();
                    while ((len = fileInputStream.read(bytes)) != -1) {
                        String s = new String(bytes, 0, len);
                        stringBuffer.append(s);
                    }
                    jsontext.setText(stringBuffer.toString());
                    fileInputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });

        showpic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File file = Environment.getExternalStorageDirectory();
                try {
                    FileInputStream fileInputStream = new FileInputStream(new File(file, "image.jpg"));
                    Bitmap bitmap = BitmapFactory.decodeStream(fileInputStream);
                    pic.setImageBitmap(bitmap);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    public void loadImage(View view) {
        downpic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                downpic(v);
            }
        });
    }

    private void downpic(View v) {
        try {
            URL url = new URL("https://img.ivsky.com/img/tupian/pre/202001/19/dalou.jpg");
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.connect();
            if (connection.getResponseCode() == 200) {
                InputStream is = connection.getInputStream();
                File file = Environment.getExternalStorageDirectory();
                FileOutputStream outputStream = new FileOutputStream(new File(file, "a.jpg"));
                byte[] bytes = new byte[1024];
                int len = 0;
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    while ((len = is.read(bytes)) != -1) {
                        outputStream.write(bytes, 0, len);
                        outputStream.flush();
                    }
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

#对应页面

<?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=".Main2Activity">

    <Button
        android:id="@+id/downjson"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="下载json" />

    <Button
        android:id="@+id/showjson"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="展示json"/>

    <TextView
        android:id="@+id/jsontext"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:text="json展示"/>

    <Button
        android:id="@+id/downpic"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="下载图片"
        android:onClick="loadImage"/>

    <Button
        android:id="@+id/showpic"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="展示图片"/>

    <ImageView
        android:id="@+id/pic"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@mipmap/ic_launcher_round"/>
</LinearLayout>

#json对象

package com.bawei.a20200622homework;

public class JavaBean {

    private int rst;
    private String msg;
    private Data data;
    public void setRst(int rst) {
        this.rst = rst;
    }
    public int getRst() {
        return rst;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
    public String getMsg() {
        return msg;
    }

    public void setData(Data data) {
        this.data = data;
    }
    public Data getData() {
        return data;
    }
    public class Data {

        private String cookie;
        public void setCookie(String cookie) {
            this.cookie = cookie;
        }
        public String getCookie() {
            return cookie;
        }
    }
}

#需要的依赖

implementation 'com.google.code.gson:gson:2.8.2'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'

#权限

 <uses-permission android:name="android.permission.INTERNET"/>
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值