Android0907(文件存儲,SharePreferences,getCacheDir、Environment,SQLite數據庫存儲)

文件存儲

將數據寫入並存儲到文件中

文件存儲是將數據存儲到指定的文件中,用的是Context類中openFileOutput()方法,傳的兩個參數中第一個爲文件名稱,第二個爲文件的操作模式,默認的模式爲MODE_PRIVATE,還有一個是MODE_APPEND,前者是後來寫入的內容會將前面寫入的內容覆蓋掉,後者是將新寫入的內容追加到原來的文件內容中

  try {
                    FileOutputStream outputStream=openFileOutput("hellocache",MODE_PRIVATE);
                    PrintWriter fileWriter=new PrintWriter(new OutputStreamWriter(outputStream));
                    fileWriter.write("你好緩存");
                    fileWriter.flush();
                    fileWriter.close();
                    outputStream.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

如何查看模擬器裏的寫入的文件
找到工具欄的這個標誌
這裏寫圖片描述
找到File Explorer->data->data->文件所在的包名
這裏寫圖片描述
裏面的file文件,導出來用記事本打開
這裏寫圖片描述
這裏寫圖片描述
將文件中內容數據讀取出來

Context類中還提供一個openFileInput()方法,用於從文件中讀取數據,相比於openFileOutput只需傳一個參數,即讀取的文件名稱。

 try {
                    FileInputStream inputStream=openFileInput("hellocache");
                    BufferedReader br=new BufferedReader(new InputStreamReader(inputStream));
                    String text=br.readLine();
                    while(text!=null){
                        Log.d("緩存數據",""+text);
                        text=br.readLine();
                    }
                    inputStream.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

SharePreferences存儲

SharePreferences是通過鍵值對的方式來存放數據的。

1、SharePreferences對象是通過Context類中的getSharePreferences()方法,需要兩個參數,第一個參數用於指定SharePreferences的文件名稱,若不存在則新創建一個,第二個參數用於指定操作模式,主要的操作模式有MODE_PRIVATE和MODE_MULTI_PROCESS,前者是默認的,和直接傳入0的效果是相同的,後者是隻有當前的應用程序纔可以對這個SharePreferences文件進行讀寫。
2、Activity類中getPreferences()方法,這個方法和getSharePreferences()方法相似,不過它只接收一個操作模式參數
3、PreferenceManger類中getDefaultSharePrefernces()方法,只接收一個context參數

得到SharePreference對象後,對SharePreference文件進行存儲分爲三步:

1、調用SharePreferences對象的edit()方法來獲取一個SharePreferences.Edit對象。
2、向SharePreferences.Edit對象中添加數據,根據添加數據類型的不同可以調用putString(),putBoolean()等方法。
3、調用commit將獲得數據進行提交,完成操作。

 SharedPreferences preferences_write=getSharedPreferences("edit_date",MODE_PRIVATE);
                SharedPreferences.Editor edit=preferences_write.edit();
                edit.putString("edit_put",sEditText.getText().toString());
                edit.commit();

將數據從SharePreferences中讀取出來
將數據從SharePreferences讀取出來相對簡單,只需將根據數據類型的不同調用不同的餓get()方法,例如getString()、getBoolean()等。

SharedPreferences preferences_read=getSharedPreferences("edit_date",MODE_PRIVATE);
                String content=preferences_read.getString("edit_put","沒有輸入數據");
                sTextView.setText(content);

查看SharePreferences中存儲數據和文件存儲文件路經大致相同,只不過SharePreferences的數據存儲在shared_prefs目錄下,
這裏寫圖片描述
這裏寫圖片描述
簡單地實例

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" tools:context=".MainActivity"
    >
    <!--這是插拔式拓展卡讀寫權限-->
    <uses-permisson android:name="abdroid.permisson.MOUNT_UNMOUNT_FILESYSEMS"></uses-permisson>
    <!--這個是手機本身存儲的讀寫權限-->
    <uses-permisson android:name="abdroid.permisson.WRITE_EXTERNAL_STORAGE"></uses-permisson>
    <EditText
        android:id="@+id/edit_sql"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="2">
    <Button
        android:id="@+id/read_date"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="讀出數據"/>
    <Button
        android:id="@+id/write_date"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="寫入數據"/>


    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:id="@+id/cache_date"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="寫入緩存數據"/>
        <Button
            android:id="@+id/read_cache_date"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="讀出緩存數據"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
    <Button
        android:id="@+id/creat_cache_date"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="緩存數據"
        />
        <Button
            android:id="@+id/creat_sdcard_date"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="寫入sd卡數據"
            />
    </LinearLayout>
    <TextView
        android:id="@+id/text_sql"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />

</LinearLayout>
package com.example.administrator.sqlapp;

import android.content.SharedPreferences;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private TextView sTextView;
    private EditText sEditText;
    private Button sBtnRead;
    private Button sBtnWrite;
    private Button sCache;
    private Button sReadCache;
    private Button sCreateCache;
    private Button sSdCard;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sTextView= (TextView) findViewById(R.id.text_sql);
        sEditText= (EditText) findViewById(R.id.edit_sql);
        sBtnRead= (Button) findViewById(R.id.read_date);
        sBtnWrite= (Button) findViewById(R.id.write_date);
        sCache= (Button) findViewById(R.id.cache_date);
        sReadCache= (Button) findViewById(R.id.read_cache_date);
        sCreateCache= (Button) findViewById(R.id.creat_cache_date);
        sSdCard= (Button) findViewById(R.id.creat_sdcard_date);
        sBtnRead.setOnClickListener(this);
        sBtnWrite.setOnClickListener(this);
        sCache.setOnClickListener(this);
        sReadCache.setOnClickListener(this);
        sCreateCache.setOnClickListener(this);
        sSdCard.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.write_date:
                SharedPreferences preferences_write=getSharedPreferences("edit_date",MODE_PRIVATE);
                SharedPreferences.Editor edit=preferences_write.edit();
                edit.putString("edit_put",sEditText.getText().toString());
                edit.commit();
                break;
            case R.id.read_date:
                SharedPreferences preferences_read=getSharedPreferences("edit_date",MODE_PRIVATE);
                String content=preferences_read.getString("edit_put","沒有輸入數據");
                sTextView.setText(content);
                break;

            case R.id.cache_date:
                try {
                    FileOutputStream outputStream=openFileOutput("hellocache",MODE_PRIVATE);
                    PrintWriter fileWriter=new PrintWriter(new OutputStreamWriter(outputStream));
                    fileWriter.write("你好緩存");
                    fileWriter.flush();
                    fileWriter.close();
                    outputStream.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.read_cache_date:
                try {
                    FileInputStream inputStream=openFileInput("hellocache");
                    BufferedReader br=new BufferedReader(new InputStreamReader(inputStream));
                    String text=br.readLine();
                    while(text!=null){
                        Log.d("緩存數據",""+text);
                        text=br.readLine();
                    }
                    inputStream.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.creat_cache_date:
                File file=new File(getCacheDir(),"newCache.txt");
                if (!file.exists()){
                    try {
                        file.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    FileOutputStream outputStream=new FileOutputStream(file);
                    PrintWriter fileWriter=new PrintWriter(new OutputStreamWriter(outputStream));
                    fileWriter.write("你好緩存,這是一個新的緩存");
                    fileWriter.flush();
                    fileWriter.close();
                    outputStream.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.creat_sdcard_date:
                File sdfile=new File(Environment.getExternalStorageDirectory(),"newCache.txt");
                if (!sdfile.exists()){
                    try {
                        sdfile.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    FileOutputStream outputStream=new FileOutputStream(sdfile);
//                    PrintWriter fileWriter=new PrintWriter(new OutputStreamWriter(outputStream));
//                    fileWriter.write("你好緩存,這是sd卡內的緩存數據");
//                    fileWriter.flush();
//                    fileWriter.close();
                    outputStream.write("你好緩存,這是sd卡內的緩存數據".getBytes());
                    outputStream.flush();
                    outputStream.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
    }
}

這裏寫圖片描述
這裏寫圖片描述

SQLite數據庫存儲

SQLite專門提供了一個SQLiteOpenHelper類,是一個抽象類,要實現的它的兩個方法(onCreate(SQLiteDatabase db)、onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion))
和一個構造器TestSQliteOpeanHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version)構造器中四個參數:context對數據庫的操作,name是數據庫的名稱,創建數據庫時的指定名稱,factory允許我們在查詢數據時返回一個自定義的Cursor,一般傳入null,最後是數據庫的版本號

創建數據庫時在OnCreat()方法中調用SQLiteDataBase的execSQL()方法完成數據庫的創建

public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table if not exists user(id integer primary key  autoincrement,name varchar(20),password varchar(20))");
    }
 TestSQliteOpeanHelper helper=new TestSQliteOpeanHelper(getApplicationContext(),"MY_FIRST_DB.db");
        database=helper.getWritableDatabase();

查看創建的SQL數據庫同文件存儲的方法一樣,找到相對應包名,發現裏面有一個MY_FIRST_DB.db的文件,這就是我們創建的數據庫了。
這裏寫圖片描述

向數據庫插入數據insert()

SQliteDatabase提供一個insert(),用於添加數據,接收三個參數,第一個是表名,第二個是在未指定添加數據的情況下給某些可能爲空的值自動賦值null,一般直接傳入null,第三個參數是一個ContentValues對象,提供一些列的put()方法重載

 ContentValues values=new ContentValues();
                values.put("name","zhangsan");
                values.put("password","123456");
                database.insert("user",null,values);

從數據庫中刪除數據

SQliteDatabase提供一個delete(),用於刪除數據,接收三個參數,第一個是表名,第二個第三個參數是用於約束要刪除的數據的某一行或某一列

 database.delete("user", "name=?", new String[]{"zhangsan"});

更新數據庫中的數據

SQliteDatabase提供一個update(),接收四個參數,第一個是表名,第二個是ContentValues對象,第三、四個是約束要更新的數據的行列,還需要用put() 方法加入更新後的數據。

 ContentValues values_update=new ContentValues();
        values_update.put("password","abcd");
        database.update("user", values_update,"name=?",new String[]{"zhangsan"});

查找數據庫中的數據

SQliteDatabase提供了rawQuery(),但是需要用Cursor去使用,先用Cursor對象的moveToFirst()方法將光標移動到第一條數據,然後判斷是否爲空,使用cursor.getString得到數據信息,參數爲行數cursor.getColumnIndex(“name”),得到相對應的行數,最後將光標移動到下一行cursor.moveToNext()

 Cursor cursor=database.rawQuery("select * from user",null);
        cursor.moveToFirst();
        while(!cursor.isAfterLast()){
            String name=cursor.getString(cursor.getColumnIndex("name"));
            String passwords=cursor.getString(cursor.getColumnIndex("password"));
            Log.d("cursor","用戶名"+name+"密碼"+passwords);
            text_name.append("用戶名:"+name+"\n");
            text_passwords.append("密 碼:"+passwords+"\n");
            cursor.moveToNext();
        }

另一種查詢數據庫的方法是用query() 方法,需要傳八個參數,第一個依舊是表名,第二個是查詢哪幾列,第三個第四個是用於約束查詢數據的行數,第五個是用於指定group by的列,第六個是對group by後的數據進行過濾,第七個參數是用於指定查詢數據結果的排序方式,第八個返回的行數,設置爲null表示沒有限制條款.(2,3)。2表示偏移量,3表示查詢數據的量,表示跳過兩條數據後取3條數據。

Cursor cursor=database.query("user",null,null,null,null,null,"id DESC");

具體的例子activity_main.XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/creatBase"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="創建數據庫"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
    <Button
        android:id="@+id/insert"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="增"
        />
    <Button
        android:id="@+id/delete"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="刪"
        />
        <Button
            android:id="@+id/update"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="改"
            />
        <Button
            android:id="@+id/select"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="查"
            />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="用戶名:"/>
            <EditText
                android:id="@+id/edit_name"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="3"
                android:hint="請輸入用戶名"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="密 碼:"/>
            <EditText
                android:id="@+id/edit_passwords"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="3"
                android:hint="請輸入密碼"/>
        </LinearLayout>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/text_name"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="用戶名"/>
        <TextView
            android:id="@+id/text_passwords"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="密  碼"/>
    </LinearLayout>
</LinearLayout>

繼承與
SQLiteOpenHelper的TestSQliteOpeanHelper.java

package com.example.administrator.sqlite;

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

import com.example.administrator.sqlite.db.TestSQliteOpeanHelper;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private Button btn_creatBase;
    private Button btn_insert;
    private Button btn_update;
    private Button btn_select;
    private Button btn_delete;
    private EditText edit_name;
    private EditText edit_passwords;
    private TextView text_name;
    private TextView text_passwords;
    private SQLiteDatabase database;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TestSQliteOpeanHelper helper=new TestSQliteOpeanHelper(getApplicationContext(),"MY_FIRST_DB.db");
        database=helper.getWritableDatabase();
        btn_creatBase= (Button) findViewById(R.id.creatBase);
        btn_creatBase.setOnClickListener(this);
        btn_insert= (Button) findViewById(R.id.insert);
        btn_insert.setOnClickListener(this);
        btn_delete= (Button) findViewById(R.id.delete);
        btn_delete.setOnClickListener(this);
        btn_update= (Button) findViewById(R.id.update);
        btn_update.setOnClickListener(this);
        btn_select= (Button) findViewById(R.id.select);
        btn_select.setOnClickListener(this);
        edit_name= (EditText) findViewById(R.id.edit_name);
        edit_passwords= (EditText) findViewById(R.id.edit_passwords);
        text_name= (TextView) findViewById(R.id.text_name);
        text_passwords= (TextView) findViewById(R.id.text_passwords);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.creatBase:

                Toast.makeText(MainActivity.this,"創建了數據庫!",Toast.LENGTH_SHORT).show();
                break;
            case R.id.insert:
                insert();
                break;
            case R.id.update:
                update();
                break;
            case R.id.delete:
                delete();
                break;
            case R.id.select:
                select();
                break;
            default:
                break;
        }
    }

    private void select() {
        Cursor cursor=database.rawQuery("select * from user",null);
        cursor.moveToFirst();
        while(!cursor.isAfterLast()){
            String name=cursor.getString(cursor.getColumnIndex("name"));
            String passwords=cursor.getString(cursor.getColumnIndex("password"));
            Log.d("cursor","用戶名"+name+"密碼"+passwords);
            text_name.append("用戶名:"+name+"\n");
            text_passwords.append("密 碼:"+passwords+"\n");
            cursor.moveToNext();
        }
        Toast.makeText(MainActivity.this,"選擇了一個數據",Toast.LENGTH_SHORT).show();
    }

    private void delete() {
        database.delete("user", "name=?", new String[]{"zhangsan"});
        Toast.makeText(MainActivity.this,"刪除了一個數據",Toast.LENGTH_SHORT).show();
    }

    private void update() {
        ContentValues values_update=new ContentValues();
        values_update.put("password","abcd");
        database.update("user", values_update,"name=?",new String[]{"zhangsan"});
        Toast.makeText(MainActivity.this,"修改了一個數據",Toast.LENGTH_SHORT).show();
    }

    private void insert() {
        ContentValues values=new ContentValues();
        values.put("name",edit_name.getText().toString());
        values.put("password",edit_passwords.getText().toString());
        database.insert("user",null,values);
        edit_name.setText("");
        edit_passwords.setText("");
        Toast.makeText(MainActivity.this,"插入了一個數據",Toast.LENGTH_SHORT).show();
    }
}

這裏寫圖片描述
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章