37.Android資料儲存再整理

不爱美女爱辣条發表於2024-04-27

這次主要是對SD卡外部儲存和SharedPreferences儲存的補充說明
還是以qq案例來說

首先外部儲存

儲存的位置為/storage/emulated/0目錄下 具體為你定義的地方這裡也有個小坑
還有就是不需要使用內部儲存的openFileOutput方法和openFileInput方法
image

首先要在清單檔案裡申請SD卡寫讀檔案的許可權
兩種方式靜態和動態申請
自然在清單檔案裡配置靜態申請簡單了
    </application>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
然後看工具類的編寫
也就是對內部儲存的更改

package com.example.store;

import android.content.Context;
import android.os.Environment;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

//工具類 實現QQ的賬號密碼儲存和讀取
public class SDTool_qqAcitivity {
    public static boolean saveUser(Context context, String user, String pwd) {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
//            File path = Environment.getExternalStorageDirectory();
            File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
//            File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
            File file = new File(path, "haha.txt");
            FileOutputStream fos = null;
            try {
//                fos = context.openFileOutput("haha.txt", Context.MODE_PRIVATE);
                fos= new FileOutputStream(file);
                //將資料轉換為位元組碼的形式寫入haha.txt中
                fos.write((user + ":" + pwd).getBytes());
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        return false;
                    }
                }
            }
            return true;
        } else {
            return false;
        }

    }

    public static Map<String, String> getUser(Context context) {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
//            File path = Environment.getExternalStorageDirectory();
           File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);


            File file = new File(path, "haha.txt");
            String str = "";
            FileInputStream fis = null;
            try {
//                fis = context.openFileInput("haha.txt");
                fis=new FileInputStream(file);
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                str = new String(buffer);
                HashMap<String, String> map = new HashMap<String, String>();
                String[] split = str.split(":");
                map.put("user", split[0]);
                map.put("pwd", split[1]);
                return map;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }


}

坑坑坑 如果你獲取路徑寫的是如下的活 會實現不了儲存密碼也不會在檔案裡找到
// File path = Environment.getExternalStorageDirectory();
你必須給他一個確定的地方
例如:
Filepath=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
這樣檔案就儲存到DOWNLOADS目錄下了

還有個重要的坑

就是我一直想實現不了密碼儲存
原因是
// Map<String, String> user =SDTool_qqAcitivity.getUser(this);
boolean b = SPTool_qqAcitivity.saveUser(QQ_Activity.this, user, pwd);
你要確定你呼叫的是哪個工具


然後就是SharedPreferences儲存

它主要是一個輕量級的 儲存介紹方法嗎 都在33裡面介紹了 就不贅婿了
然後就是檔案儲存在:
image
對的儲存的格式為xml

然後咱們看工具類的編寫
主要就是呼叫編輯器方法
package com.example.store;

import android.content.Context;
import android.content.SharedPreferences;

//工具類 實現QQ的賬號密碼儲存和讀取
public class SPTool_qqAcitivity {
    public static boolean saveUser(Context context, String user, String pwd) {
        SharedPreferences sharedPreferences = context.getSharedPreferences("haha", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putString("user", user);
        edit.putString("pwd", pwd);
        edit.commit();
        return true;
    }

    public static String getUser(Context context, String key) {
        SharedPreferences sharedPreferences = context.getSharedPreferences("haha", Context.MODE_PRIVATE);
        String string = sharedPreferences.getString(key, "沒找到");
        return string;
    }
}

注意注意要在主檔案中修改你呼叫的工具同上一樣:
略微修改
因為改成了String方法

//        Map<String, String> user =SDTool_qqAcitivity.getUser(this);
//        user = Tool_qqAcitivity.getUser(this);
//        if (user != null) {
//            et_account.setText(user.get("user"));
//            et_password.setText(user.get("pwd"));
//        }
        String user = SPTool_qqAcitivity.getUser(this, "user");
        String pwd = SPTool_qqAcitivity.getUser(this, "pwd");
        et_account.setText(user);
        et_password.setText(pwd);

再來個小補充把 就是我33並沒有trycatch處理異常

這樣是不對的 所以在這裡小小補充下程式碼

package com.example.store;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

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

import java.io.IOException;
import java.util.Map;

public class QQ_Activity extends AppCompatActivity {
    //初始化
    private EditText et_account;
    private EditText et_password;
    private Button btn_login;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qq);
        et_account = findViewById(R.id.et_account);
        et_password = findViewById(R.id.et_password);
        btn_login = findViewById(R.id.btn_login);
//        Map<String, String> user =SDTool_qqAcitivity.getUser(this);
//        user = Tool_qqAcitivity.getUser(this);
//        if (user != null) {
//            et_account.setText(user.get("user"));
//            et_password.setText(user.get("pwd"));
//        }
        String user = SPTool_qqAcitivity.getUser(this, "user");
        String pwd = SPTool_qqAcitivity.getUser(this, "pwd");
        et_account.setText(user);
        et_password.setText(pwd);


        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String user = et_account.getText().toString().trim();
                String pwd = et_password.getText().toString();
                //檢查是否為空
                if (TextUtils.isEmpty(user)) {
                    Toast.makeText(QQ_Activity.this, "請輸入賬號", Toast.LENGTH_SHORT).show();
                }
                if (TextUtils.isEmpty(pwd)) {
                    Toast.makeText(QQ_Activity.this, "請輸入密碼", Toast.LENGTH_SHORT).show();
                }
                Toast.makeText(QQ_Activity.this, "登入成功", Toast.LENGTH_SHORT).show();
                //儲存使用者資訊 呼叫工具
                boolean b = SPTool_qqAcitivity.saveUser(QQ_Activity.this, user, pwd);
                if (b) {
                    Toast.makeText(QQ_Activity.this, "儲存成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(QQ_Activity.this, "儲存失敗", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

}

歐克了 那個SQLite資料庫儲存33中已經很清楚的介紹
那三個儲存方法算over了 剩下的就是內容提供者和網路儲存了

相關文章