Android开发之数据持久化存储二

一、目标

以QQ登陆为例,继续完成昨天没有完成的任务,实现数据的存储和回显读取,并且学会了存储信息

二、源程序代码

package com.example.qq_logindemo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;

public class MainActivity extends AppCompatActivity {
    private final static String TAG="MainActivity";
    private EditText account;
    private EditText password;
    private Button login;

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

        //第一步、获取控件
        initView();
        
        //第二步、设置监听
        
        initListener();
        

    }

    /**
     * 设置回写
     */
    @Override
    protected void onResume() {
        super.onResume();
//        File filesDir=this.getFilesDir();
//        File cacheDir=this.getCacheDir();

        try {
            FileInputStream fileInputStream = this.openFileInput("info.text");
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(fileInputStream));
            String info = bufferedReader.readLine();
            // fos.write((accountText+"***"+passwordText).getBytes());
            String[] splits = info.split("\*\*\*");

            String account=splits[0];
            String password=splits[1];

            this.account.setText(account);
            this.password.setText(password);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     *  设置监听
     */
    private void initListener() {
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handlerLoginEvent(v);
            }
        });
    }

    /**
     * 处理登陆事件
     * @param v
     */
    private void handlerLoginEvent(View v) {
        //获取账号和密码数据
        String accountText = account.getText().toString();
        String passwordText= password.getText().toString();
//        方法一
//        if (accountText.length()==0) {
//            Toast.makeText(this,"账号不能为空..",Toast.LENGTH_SHORT).show();
//            return;
//        }
//        if (passwordText.length()==0) {
//            Toast.makeText(this,"密码不能为空..",Toast.LENGTH_SHORT).show();
//            return;
//        }

        if (TextUtils.isEmpty(accountText)) {
            Toast.makeText(this,"账号不能为空..",Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(passwordText)) {
            Toast.makeText(this,"密码不能为空..",Toast.LENGTH_SHORT).show();
            return;
        }

        account.setText("");
        password.setText("");
        //存储
        saveInfo(accountText,passwordText);
    }

    /**
     * 存储信息到文件中
     *
     * @param accountText
     * @param passwordText
     */
    private void saveInfo(String accountText, String passwordText) {

        File filesDir=this.getFilesDir();

        File saveFile=new File(filesDir,"info.text");
        //存储路径

        File cacheDir=this.getCacheDir();
        //缓存路径

        Log.d(TAG, "saveInfo: "+saveFile.toString());
        Log.d(TAG, "saveInfo: "+cacheDir.toString());
        Log.d(TAG, "saveInfo: "+accountText+"---"+passwordText);
        try {
            if(!saveFile.exists()){
                saveFile.createNewFile();
            }
            FileOutputStream fos=new FileOutputStream(saveFile);
            fos.write((accountText+"***"+passwordText).getBytes());
            fos.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

        Toast.makeText(this,"保存成功",Toast.LENGTH_SHORT).show();
    }

    /**
     *  找到对应的控件
     * */

    private void initView() {
        account = this.findViewById(R.id.et_account);
        password = this.findViewById(R.id.et_password);
        login = this.findViewById(R.id.bt_login);
    }


}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <!--QQ登陆UI布局练习-->

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_marginTop="80dp"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="30dp">
        <TextView
            android:layout_width="wrap_content"
            android:drawableLeft="@mipmap/ic_launcher"
            android:text="QQ"
            android:textSize="40sp"
            android:layout_height="wrap_content"/>

        <EditText
            android:id="@+id/et_account"
            android:layout_marginTop="30dp"
            android:layout_width="match_parent"
            android:textSize="30sp"
            android:hint="QQ号码/手机号/邮箱"
            android:layout_height="wrap_content"/>

        <EditText
            android:id="@+id/et_password"
            android:inputType="textPassword"
            android:layout_width="match_parent"
            android:textSize="30sp"
            android:hint="登陆密码"
            android:layout_height="wrap_content"/>

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


        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:layout_marginTop="10dp"
                android:layout_width="wrap_content"
                android:textSize="20dp"
                android:text="忘记密码?"
                android:layout_height="wrap_content"/>
            <TextView
                android:layout_marginTop="10dp"
                android:layout_width="wrap_content"
                android:textSize="20dp"
                android:layout_alignParentRight="true"
                android:text="新用户注册"
                android:layout_height="wrap_content"/>
        </RelativeLayout>

    </LinearLayout>
    <TextView
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_marginBottom="40dp"
        android:layout_alignParentBottom="true"
        android:text="登录即代表阅读并同意阅读条款"
        android:layout_height="wrap_content"/>

</RelativeLayout>

三、心得体会

今天任务完成的还算合格,可能是之前对输入输出流的学习不是很入门,所以在涉及到数据存储和读入的时候效率较低,还需要加强之后的学习!

原文地址:https://www.cnblogs.com/suanai/p/12256695.html