Hướng dẫn cách lập trình android với bộ nhớ ngoài (External Storage)

Chúng ta sẽ tạo giao diện cho MainActivity tại file activity_main.xml bao gồm một TextView để hiển thị thông báo lưu hoặc đọc dữ liệu, một EditText để nhập chuỗi ký tự lưu vào, 2 Button để nhấn sự kiện lưu dữ liệu và đọc dữ liệu lên.

Tại bài học trước mình đã giới thiệu cho các bạn về cách lưu trữ và đọc dữ liệu vào bộ nhớ trong của thiết bị , các bạn có thể xem lại tại đây. Trong bài này chúng ta sẽ tìm hiểu cách lưu trữ ra đọc file với (External Storage).

External Storage là nơi lưu trữ dữ liệu ngoài của Android, các file dữ liệu lưu trữ mà bạn lưu trữ tại đây không được hệ thống áp dụng bảo mật.

Thông thường có 2 loại lưu trữ ngoài (External Storage) là lưu trữ ngoài tại ổ cứng điện thoại và lưu trữ tại ổ cứng lưu động như thẻ nhớ (SD card). Dữ liệu được tạo ra sẽ không bị rang buộc bởi ứng dụng, khi ta xóa ứng dụng tạo ra dữ liệu tại bộ nhớ ngoài thì dữ liệu đó không bị mất đi.

Trong bài học này chúng ta sẽ làm một ví dụ cơ bản để lưu trữ một chuỗi văn bản vào bộ nhớ ngoài tại SDcard và đọc dữ liệu đó rồi hiện lên màn hình.

Đầu tiên chúng ta sẽ tạo một project mới với MainActivity ở dạng Empty Activity. Ở bài này mình tạo project có tên Devpro_Extarnal_Storage.

Chúng ta sẽ tạo giao diện cho MainActivity tại file activity_main.xml bao gồm một TextView để hiển thị thông báo lưu hoặc đọc dữ liệu, một EditText để nhập chuỗi ký tự lưu vào, 2 Button để nhấn sự kiện lưu dữ liệu và đọc dữ liệu lên.

Activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
    android:layout_width=”fill_parent”
    android:layout_height=”fill_parent”
    android:orientation=”vertical”
    android:gravity=”center”>
    <TextView
        android:gravity=”center”
        android:layout_width=”fill_parent”
        android:layout_height=”wrap_content”
        android:text=”Lưu trữ file vào bộ nhớ” />
    <EditText
        android:id=”@+id/myInputText”
        android:layout_width=”match_parent”
        android:layout_height=”wrap_content”
        android:ems=”10″
        android:gravity=”top|left”
        android:inputType=”textMultiLine”
        android:lines=”5″
        android:minLines=”3″>
        <requestFocus />
    </EditText>
    <Button
        android:id=”@+id/btnSave”
        android:layout_width=”match_parent”
        android:layout_height=”wrap_content”
        android:text=”Lưu vào bộ nhớ ngoài” />
    <Button
        android:id=”@+id/btnDisplay”
        android:layout_width=”match_parent”
        android:layout_height=”wrap_content”
        android:text=”Lấy dữ liệu từ bộ nhớ ngoài” />
    <TextView
        android:id=”@+id/responseText”
        android:layout_width=”wrap_content”
        android:layout_height=”wrap_content”
        android:padding=”5dp”
        android:text=””
        android:textAppearance=”?android:attr/textAppearanceMedium” />
</LinearLayout>

Tiếp theo tại MainActivity.java ta sẽ viết code để kiểm tra bộ nhớ và tạo dữ liệu, đọc dữ liệu trên thiết bị android.

Đầu tiên ta ánh xạ các EditText, TextView và Button cho các đối tượng tại giao diện sau đó tạo các sự kiện cho 2 nút Button tại hàm initView và gọi hàm này tại hàm onCreate trong class MainActivity:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Button btnSave, readFromExternalStorage;
private String filename = “MySampleFile.txt”;
private String filepath = “MyFileStorage”;
TextView responseText;
EditText myInputText;
File myExternalFile;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initView();
}
private void initView() {
    myInputText = (EditText) findViewById(R.id.myInputText);
    responseText = (TextView) findViewById(R.id.responseText);
    btnSave = (Button) findViewById(R.id.btnSave);
    btnSave.setOnClickListener(this);
    readFromExternalStorage = (Button) findViewById(R.id.btnDisplay);
    readFromExternalStorage.setOnClickListener(this);
}

Tiếp theo trong class MainActivity ta viết hàm kiểm tra xem thiết bị có bộ nhớ ngoài hay không và kiểm tra bộ nhớ ngoài đó có read only (Không cho phép ghi dữ liệu) Hai trường hợp này đều dẫn tới việc không thể ghi dữ liệu lên đó được. Sau đó xét trường hợp thỏa mãn ghi được dữ liệu ta sẽ tạo một file có tên là MySampleFile.txt và một thư mục MyFileStorage.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
* Kiểm tra xe bộ nhớ ngoài SDCard có readonly không vì nếu là readonly thì
* không thể tạo file trên đó được
*/
private static boolean isExternalStorageReadOnly() {
    String extStorageState = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
        return true;
    }
    return false;
}
/*
* Kiểmtra xem device có bộ nhớ ngoài không
*/
private static boolean isExternalStorageAvailable() {
    String extStorageState = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
        return true;
    }
    return false;
}

Trong hàm onCreate() ta thêm dòng lệnh kiểm tra bộ nhớ và tạo file:

onCreate() được sửa lại như sau:

1
2
3
4
5
6
7
8
9
10
11
12
13
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initView();
    // check if external storage is available and not read only
    if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
        btnSave.setEnabled(false);
    } else {
        myExternalFile = new File(getExternalFilesDir(filepath), filename);
    }
}

Khi đã tạo được file ta bắt sự kiện cho 2 nút lưu và đọc file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public void onClick(View v) {
    String myData = “”;
    switch (v.getId()) {
        case R.id.btnSave:
            try {
                FileOutputStream fos = new FileOutputStream(myExternalFile);
                fos.write(myInputText.getText().toString().getBytes());
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            myInputText.setText(“”);
            responseText.setText(“Dữ liệu đã được lưu vào bộ nhớ ngoài”);
            break;
        case R.id.btnDisplay:
            try {
                FileInputStream fis = new FileInputStream(myExternalFile);
                DataInputStream in = new DataInputStream(fis);
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(in));
                String strLine;
                while ((strLine = br.readLine()) != null) {
                    myData = myData + strLine;
                }
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            myInputText.setText(myData);
            responseText.setText(“Được lấy ra từ bộ nhớ ngoài”);
            break;
    }
}

Vậy là xong, toàn bộ code tại MainActivity như sau:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package com.example.dong.devpro_external_storage;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
    Button btnSave, readFromExternalStorage;
    private String filename = “MySampleFile.txt”;
    private String filepath = “MyFileStorage”;
    TextView responseText;
    EditText myInputText;
    File myExternalFile;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        // check if external storage is available and not read only
        if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
            btnSave.setEnabled(false);
        } else {
            myExternalFile = new File(getExternalFilesDir(filepath), filename);
        }
    }
    private void initView() {
        myInputText = (EditText) findViewById(R.id.myInputText);
        responseText = (TextView) findViewById(R.id.responseText);
        btnSave = (Button) findViewById(R.id.btnSave);
        btnSave.setOnClickListener(this);
        readFromExternalStorage = (Button) findViewById(R.id.btnDisplay);
        readFromExternalStorage.setOnClickListener(this);
    }
    public void onClick(View v) {
        String myData = “”;
        switch (v.getId()) {
            case R.id.btnSave:
                try {
                    FileOutputStream fos = new FileOutputStream(myExternalFile);
                    fos.write(myInputText.getText().toString().getBytes());
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                myInputText.setText(“”);
                responseText.setText(“Dữ liệu đã được lưu vào bộ nhớ ngoài”);
                break;
            case R.id.btnDisplay:
                try {
                    FileInputStream fis = new FileInputStream(myExternalFile);
                    DataInputStream in = new DataInputStream(fis);
                    BufferedReader br = new BufferedReader(
                            new InputStreamReader(in));
                    String strLine;
                    while ((strLine = br.readLine()) != null) {
                        myData = myData + strLine;
                    }
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                myInputText.setText(myData);
                responseText.setText(“Được lấy ra từ bộ nhớ ngoài”);
                break;
        }
    }
    /*
     * Kiểm tra xe bộ nhớ ngoài SDCard có readonly không vì nếu là readonly thì
     * không thể tạo file trên đó được
     */
    private static boolean isExternalStorageReadOnly() {
        String extStorageState = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
            return true;
        }
        return false;
    }
     /*
     * Kiểmtra xem device có bộ nhớ ngoài không
     */
    private static boolean isExternalStorageAvailable() {
        String extStorageState = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
            return true;
        }
        return false;
    }
}

Ta chạy chương trình và xem kết quả:

1

 

Chúng ta có thể kiểm tra đường dẫn file trong thiết bị:

2

 

Nếu các bạn muốn biết thêm các kỹ thuật khác về android, các bạn có thể tham khảo thêm các khóa học android tại đây.
Các bạn có thể tải source code tại đây

Cùng Danh Mục:

Liên Quan Khác

Leave a Reply

Your email address will not be published. Required fields are marked *