Android數據存儲方案

文件存儲

Context類中提供了一個openFileOutput()方法,能夠用於將數據存儲到指定文件中。
第一個參數是文件名
第二個參數是文件的操做模式javascript

文件默認會存儲到/data/data/package name/files/目錄下java

MainActivity.javaandroid

package com.zhoujian.persistentdata;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class MainActivity extends AppCompatActivity {

    private EditText edit;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        edit = (EditText) findViewById(R.id.edit);
        String inputText = loadData();
        if (!TextUtils.isEmpty(inputText))
        {
            edit.setText(inputText);
            edit.setSelection(inputText.length());
            Toast.makeText(this, "恢復數據成功", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        String inputText = edit.getText().toString();
        saveData(inputText);
    }

    public void saveData(String inputText)
    {
        FileOutputStream out = null;
        BufferedWriter writer = null;
        try
        {
            //MODE_PRIVATE:默認模式,表示當指定一樣文件名的時候,所寫的內容將會覆蓋原文件中的內容
            //MODE_APPEND:表示若是文件存在,就往文件裏追加內容,不存在就建立
            out = openFileOutput("file", Context.MODE_PRIVATE);
            writer = new BufferedWriter(new OutputStreamWriter(out));
            writer.write(inputText);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public String loadData()
    {
        FileInputStream in = null;
        BufferedReader reader = null;
        StringBuilder sb = new StringBuilder();
        try
        {
            in = openFileInput("file");
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null)
            {
                sb.append(line);
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (reader != null)
            {
                try
                {
                    reader.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }
}複製代碼

Demo下載:https://github.com/zeke123/PersistentDatagit

SharedPreferences 存儲

SharedPreferences是採用鍵值對的方式存儲數據的github

點擊CheckBox,用SharedPreferences存儲數據,記住用戶名和密碼sql

LoginActivity.java數據庫

package com.zhoujian.sharedPreferences;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends BaseActivity {

    private SharedPreferences pref;

    private SharedPreferences.Editor editor;

    private EditText mAccount;

    private EditText mPassword;

    private Button login;

    private CheckBox mCheckBox;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        pref = PreferenceManager.getDefaultSharedPreferences(this);
        mAccount = (EditText) findViewById(R.id.account);
        mPassword = (EditText) findViewById(R.id.password);
        mCheckBox = (CheckBox) findViewById(R.id.remember_pass);
        login = (Button) findViewById(R.id.login);
        boolean isRemember = pref.getBoolean("remember_password", false);
        if (isRemember) {
            // 將帳號和密碼都設置到文本框中
            String account = pref.getString("account", "");
            String password = pref.getString("password", "");
            mAccount.setText(account);
            mPassword.setText(password);
            mCheckBox.setChecked(true);
        }
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String account = mAccount.getText().toString();
                String password = mPassword.getText().toString();
                // 若是帳號是123456且密碼是123456,就認爲登陸成功
                if (account.equals("123456") && password.equals("123456")) {
                    editor = pref.edit();
                    if (mCheckBox.isChecked()) {
                        // 檢查複選框是否被選中
                        editor.putBoolean("remember_password", true);
                        editor.putString("account", account);
                        editor.putString("password", password);
                    } else {
                        editor.clear();
                    }
                    editor.apply();
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(LoginActivity.this, "帳號或者密碼錯誤", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}複製代碼

Demo下載:https://github.com/zeke123/SharedPreferencesapp

SQLite數據庫存儲

建立數據庫

在mac上查看數據庫的工具:SQLPro for SQLiteide

數據庫文件位於:/data/data/package name/databases/目錄下工具

MyDatabaseHelper.java

package com.zhoujian.sqlitedemo;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

public class MyDatabaseHelper extends SQLiteOpenHelper {


    private Context mContext;

    //integer:表示整型
    //text:表示文本型
    //real:表示浮點型
    //blob:表示二進制類型

    public static final String CREATE_BOOK = "create table Book ("
            + "id integer primary key autoincrement, "
            + "author text, "
            + "price real, "
            + "pages integer, "
            + "name text)";

    public static final String CREATE_CATEGORY = "create table Category ("
            + "id integer primary key autoincrement, "
            + "category_name text, "
            + "category_code integer)";



    public MyDatabaseHelper(Context context, String name,
                            SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        mContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_BOOK);
        db.execSQL(CREATE_CATEGORY);
        Toast.makeText(mContext, "建立數據庫成功", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        //當數據庫升級的時候,若是表存在,會先刪除表,而後從新建立
        db.execSQL("drop table if exists Book");
        db.execSQL("drop table if exists Category");
        onCreate(db);
    }

}複製代碼

增刪改查

MainActivity.java

package com.zhoujian.sqlitedemo;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private MyDatabaseHelper dbHelper;
    private SQLiteDatabase mDb;
    private Button mCreateDatabase;
    private Button mAddData;
    private Button mQueryButton;
    private Button mDeleteButton;
    private Button mUpdateData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dbHelper = new MyDatabaseHelper(this, "Book.db", null, 1);
        initViews();
        clickEvents();
    }

    private void initViews()
    {
        mCreateDatabase = (Button) findViewById(R.id.create_database);
        mAddData = (Button) findViewById(R.id.add_data);
        mQueryButton = (Button) findViewById(R.id.query_data);
        mDeleteButton = (Button) findViewById(R.id.delete_data);
        mUpdateData = (Button) findViewById(R.id.update_data);
    }
    private void clickEvents()
    {
        mCreateDatabase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //getReadableDatabase():若是磁盤已滿,將以只讀的方式打開數據庫
                //getWritableDatabase():若是磁盤已滿,將出現異常

                mDb = dbHelper.getWritableDatabase();
            }
        });

        mAddData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mDb!=null){
                    ContentValues values = new ContentValues();
                    // 插入第一條數據
                    values.put("name", "Android開發藝術探索");
                    values.put("author", "任玉剛");
                    values.put("pages", 494);
                    values.put("price", 65.5);
                    mDb.insert("Book", null, values);
                    values.clear();
                    // 插入第二條數據
                    values.put("name", "第一行代碼");
                    values.put("author", "郭霖");
                    values.put("pages", 510);
                    values.put("price", 75);
                    mDb.insert("Book", null, values);
                    values.clear();
                    // 插入第三條數據
                    values.put("name", "瘋狂Android講義");
                    values.put("author", "李剛");
                    values.put("pages", 580);
                    values.put("price", 85);
                    mDb.insert("Book", null, values);


                    Toast.makeText(MainActivity.this, "添加數據成功", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(MainActivity.this, "請先建立數據庫", Toast.LENGTH_SHORT).show();
                }
            }
        });

        mUpdateData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mDb!=null){

                    //把Android開發藝術探索這本書的價格改成70
                    ContentValues values = new ContentValues();
                    values.put("price", 70);
                    mDb.update("Book", values, "name = ?", new String[] { "Android開發藝術探索" });
                    Toast.makeText(MainActivity.this, "更新數據成功", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(MainActivity.this, "請先建立數據庫", Toast.LENGTH_SHORT).show();
                }
            }
        });

        mDeleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mDb!=null){
                    //刪除頁數大於500的書籍
                    mDb.delete("Book", "pages > ?", new String[] { "500" });
                    Toast.makeText(MainActivity.this, "刪除數據成功", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(MainActivity.this, "請先建立數據庫", Toast.LENGTH_SHORT).show();
                }
            }
        });

        mQueryButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(mDb!=null){

                    // 查詢Book表中全部的數據
                    Cursor cursor = mDb.query("Book", null, null, null, null, null, null);
                    if (cursor.moveToFirst()) {
                        do {
                            // 遍歷Cursor對象,取出數據並打印
                            String name = cursor.getString(cursor.getColumnIndex("name"));
                            String author = cursor.getString(cursor.getColumnIndex("author"));
                            int pages = cursor.getInt(cursor.getColumnIndex("pages"));
                            double price = cursor.getDouble(cursor.getColumnIndex("price"));
                            Log.d("MainActivity", "書籍的名字: " + name);
                            Log.d("MainActivity", "書籍的做者: " + author);
                            Log.d("MainActivity", "書籍的頁數: " + pages);
                            Log.d("MainActivity", "書籍的價格:" + price);
                        } while (cursor.moveToNext());
                    }
                    cursor.close();
                    Toast.makeText(MainActivity.this, "查詢數據成功", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(MainActivity.this, "請先建立數據庫", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}複製代碼

Demo下載:https://github.com/zeke123/SqliteDemo

相關文章
相關標籤/搜索