Android數據存儲全解析(一)

一、文件存儲

文件存儲是 Android 中最基本的一種數據存儲方式,它不對存儲的內容進行任何的格式化處理,所有數據都是原封不動地保存到文件當中的,因而它比較適合用於存儲一些簡單的文本數據或二進制數據。


Context 類中提供了一個 openFileOutput ()方法,可以用於將數據存儲到指定的文件中。

參數:文件名,操作模式

操作模式主要有兩類:
MODE_PRIVATE 是默認的操作模式,表示當指定同樣文件名的時候,所寫入的內容將會覆蓋原文件中的內容MODE_APPEND 則表示如果該文件已存在就往文件裏面追加內容,不存在就創建新文件。


核心代碼:

FileOutputStream out = null;
out = context.openFileOutput(filename, Context.MODE_***);
out.write(filecontent.getBytes("UTF-8"));
out.close();

示例(獲取輸入到editText中的內容並輸入到textView中):

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.liming.myapplication.MainActivity">

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText"
        android:layout_marginTop="35dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:id="@+id/textView"
        android:layout_marginTop="63dp"
        android:layout_below="@+id/editText"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="SaveData"
        android:id="@+id/button"
        android:layout_marginTop="64dp"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="GetData"
        android:id="@+id/button2"
        android:layout_below="@+id/button"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

Activity:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private EditText editText;
    private TextView textView;
    private Button saveData;
    private Button getData;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        saveData = (Button)findViewById(R.id.button);
        saveData.setOnClickListener(this);
        getData = (Button)findViewById(R.id.button2);
        getData.setOnClickListener(this);
        editText = (EditText)findViewById(R.id.editText);
        textView = (TextView)findViewById(R.id.textView);
    }

    public void save() {
        String data = editText.getText().toString();
        FileOutputStream out = null;
        BufferedWriter writer = null;
        try {
            out = openFileOutput("horizon", Context.MODE_PRIVATE);
            writer = new BufferedWriter(new OutputStreamWriter(out));
            writer.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void get(){
        String data = null;
        FileInputStream in = null;
        BufferedReader reader = null;
        StringBuilder content = new StringBuilder();
        try {
            in = openFileInput("horizon");
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    textView.setText(content.toString());
    }


    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.button){
            save();
        }else{
            get();
        }
    }
}

截圖:


注意利用openFileOutput獲取的路徑,默認是/data/data/<packagename>/files/ 目 錄  。

此外,Activity還提供了getCacheDir()和getFilesDir()方法:
getCacheDir()方法用於獲取/data/data/<package name>/cache目錄
getFilesDir()方法用於獲取/data/data/<package name>/files目錄


二、外部存儲

在使用SDCard存儲前,必須確認外部存儲媒體已掛載且可讀/寫

Android提供了對應的比對接口

MEDIA_MOUNTED 存儲媒體已經掛載,並且掛載點可讀/寫。

Environment.getExternalStorageState()用以獲取存儲媒體狀態

這裏我給出存儲的示例:

public void SDSave() {
        FileOutputStream out = null;
        BufferedWriter writer = null;
        String data = "墓王之王會是什麼鬼?";
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File file = new File(Environment.getExternalStorageDirectory(), "data.txt");
            try {
                out = new FileOutputStream(file);
                writer = new BufferedWriter(new OutputStreamWriter(out));
                writer.write(data);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }



三、SharedPreferences存儲

不同於文件的存儲方式,SharedPreferences是使用鍵值對的方式來存儲數據的。

要想使用SharedPreferences來存儲數據, 首先需要獲取到SharedPreferences對象。Android中主要提供了三種方法用於得到 SharedPreferences 對象。
1. Context 類中的 getSharedPreferences()方法
此方法接收兩個參數,第一個參數用於指定 SharedPreferences 文件的名稱,如果指定的文件不存在則會創建一個,SharedPreferences 文件都是存放在/data/data/<packagename>/shared_prefs/目錄下的。第二個參數用於指定操作模式,主要有兩種模式可以選擇,MODE_PRIVATE 和 MODE_MULTI_PROCESS。
2. Activity 類中的 getPreferences()方法
這個方法和 Context 中的 getSharedPreferences()方法很相似,不過它只接收一個操作模式參數,因爲使用這個方法時會自動將當前活動的類名作爲 SharedPreferences 的文件名。
3. PreferenceManager 類中的 getDefaultSharedPreferences()方法
這是一個靜態方法,它接收一個 Context 參數,並自動使用當前應用程序的包名作
爲前綴來命名 SharedPreferences 文件。
得到了 SharedPreferences 對象之後, 就可以開始向 SharedPreferences 文件中存儲數據了.


大體上都是分爲三步實現。
1. 調用 SharedPreferences 對象的 edit()方法來獲取一個 SharedPreferences.Editor 對象。
2. 向 SharedPreferences.Editor 對象中添加數據,比如添加一個布爾型數據就使用
putBoolean 方法,添加一個字符串則使用 putString()方法,以此類推。
3. 調用 commit()方法將添加的數據提交,從而完成數據存儲操作。

這裏給出第一種方式的示例:

layout部分:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center">
    <Button
        android:id="@+id/save_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Save_data"
        />
    <Button
        android:id="@+id/get_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="get_data"
        />
</LinearLayout>
實現代碼:
public class MainActivity extends AppCompatActivity {

    private Button saveData;
    private Button getData;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        saveData = (Button) findViewById(R.id.save_data);
        saveData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //創建文件並存入數據
                SharedPreferences.Editor editor = getSharedPreferences("data",
                        MODE_PRIVATE).edit();
                editor.putString("name", "horizon");
                editor.putInt("age", 20);
                editor.putBoolean("married", false);
                editor.commit();
            }
        });
        getData = (Button)findViewById(R.id.get_data);
        getData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //獲取對應文件
                SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE);
                String name = pref.getString("name", "");
                int age = pref.getInt("age", 0);
                boolean married = pref.getBoolean("married",false);
                Log.d("MainActivity", "name is " + name);
                Log.d("MainActivity", "age is " + age);
                Log.d("MainActivity", "married is " + married);
            }
        });
    }
}

截圖

save(ddms)



get



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