Lưu trữ dữ liệu trong android (Bài 5)

Lưu trữ dữ liệu trong android (Bài 5)

luu-tru-du-lieu-trong-android-7
Lập trình Android cơ bản

Lưu trữ dữ liệu trong android (Bài 5)

Lưu trữ dữ liệu trong android cung cấp nhiều lựa chọn trong việc lưu trữ dữ liệu như lưu trữ dữ liệu vào bộ nhớ trong (internal storage), lưu trữ dữ liệu vào bộ nhớ ngoài (external storage), lưu trữ dữ liệu với shared preferences, lưu trữ dữ liệu sử dụng SQLite hoặc lưu trữ dữ liệu thông qua mạng (storage via network connection).

Lưu trữ dữ liệu trong android – Bộ nhớ trong (Internal Storage)

Internal storage là việc lưu trữ dữ liệu cục bộ theo từng ứng dụng trên bộ nhớ thiết bị. Dữ liệu sẽ bị mất khi người dùng xoá ứng dụng.

Xử lý ghi dữ liệu vào bộ nhớ trong (Lưu ý, FileName là tên file mà bạn muốn tạo, str là dữ liệu bạn cần ghi vào bộ nhớ. Dữ liệu này chúng ta có thể lấy từ giao diện của ứng dụng)

OutputStream os = openFileOutput("FileName", MODE_APPEND/MODE_PRIVATE);
String str = "Dữ liệu cần ghi";
os.write(str.getBytes());
os.close();

Xử lý đọc dữ liệu từ bộ nhớ trong (Lưu ý, FileName là tên tập tin mà chúng ta cần đọc dữ liệu)

FileInputStream fis = openFileInput("fileName");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
StringBuffer data = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
 data. append(line).append("\n");
}

Lưu trữ dữ liệu trong android – Bộ nhớ ngoài (External Storage)

Cũng giống như internal storage, chúng ta có thể lưu và đọc dữ liệu từ external storage của thiết bị như sdcard.

Xử lý ghi dữ liệu vào bộ nhớ ngoài (Lưu ý phần in đậm, các bạn phải thay đổi cho phù hợp)

File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"FileName");
OutputStream os = new FileOutputStream(file);
String str = "Dữ liệu muốn ghi";
os.write(str.getBytes());
os.close();

Xử lý đọc dữ liệu từ bộ nhớ ngoài

File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"FileName");
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
//Đọc dữ liệu từ file, nội dung sau khi đọc sẽ chứa trong biến content
StringBuilder content = new StringBuilder();
while ((line = br.readLine()) != null) {
 content.append(line);
 content.append('\n');
}
br.close();

Lưu trữ dữ liệu trong android – Ví dụ

Giao diện màn hình thứ nhất

lưu trữ dữ liệu trong android

Giao diện màn hình thứ hai được gọi khi người dùng click vào nút “WRITE”

luu tru du lieu trong android 5

Giao diện màn hình thứ ba được gọi khi người dùng click vào nút “READ”

luu tru du lieu trong android 6

Các bước thực hiện

Bước 1: Tạo 3 activity đặt tên lần lượt là DataStorageDemoActivity, WrittingFileActivity và ReadingFileActivity

Bước 2: Thiết kế giao diện

Giao diện DataStorageDemoActivity

luu tru du lieu trong android 1

Giao diện WrittingFileActivity

luu tru du lieu trong android 2

Giao diện ReadingFileActivity

luu tru du lieu trong android 3

Bước 3: Viết xử lý (Lưu ý chỉnh định tên phương thức tại thuộc tính onClick của các button trong layout)

Code của DataStorageDemoActivity

public class DataStorageDemoActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_storage_demo);
    }
    public void runWriteActivity(View view){
        Intent intent = new Intent(this, WrittingFileActivity.class);
        startActivity(intent);
    }
    public void runReadActivity(View view){
        Intent intent = new Intent(this, ReadingFileActivity.class);
        startActivity(intent);
    }
}

Code của WrittingFileActivity

public class WrittingFileActivity extends AppCompatActivity {
    EditText etChuThich;
    RadioButton rbInternal, rbExternal;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_writting_file);
        etChuThich = (EditText) findViewById(R.id.etChuThich);
        rbInternal = (RadioButton) findViewById(R.id.rbInternal);
        rbExternal = (RadioButton) findViewById(R.id.rbExternal);
    }
    public void writeExternal(View view) {
        try {
            if (rbInternal.isChecked()) {
                writeInternal();
            } else if (rbExternal.isChecked()) {
                writeExternal();
            } else {
                writeInternal();
                writeExternal();
            }
            Toast.makeText(this, "Ghi dữ liệu thành công!", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
        }
    }
    public void writeInternal() {
        try {
            OutputStream os = openFileOutput("chuthich_in.txt", MODE_PRIVATE);
            String string = etChuThich.getText().toString();
            os.write(string.getBytes());
            os.close();
        } catch (Exception e) {
        }
    }
    public void writeExternal() {
        try {
            File sdcard = Environment.getExternalStorageDirectory();
            File f = new File(sdcard,"chuthich_ex.txt");
            OutputStream os = new FileOutputStream(f);
            String string = etChuThich.getText().toString();
            os.write(string.getBytes());
            os.close();
        } catch (Exception e) {
        }
    }
}

Code của ReadingFileActivity

public class ReadingFileActivity extends AppCompatActivity {
    TextView tvInternal, tvExternal;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reading_file);
        tvInternal = (TextView)findViewById(R.id.tvInternal);
        tvExternal = (TextView)findViewById(R.id.tvExternal);
    }
    public void load(View view){
        readFromInternal();
        readFromExternal();
    }
    private void readFromInternal(){
        try {
            InputStream is = openFileInput("chuthich_in.txt");
            int size = is.available();
            byte data[] = new byte[size];
            is.read(data);
            is.close();
            String s = new String(data); //s chứa dữ liệu đọc từ file
            tvInternal.setText(s);
        }catch (Exception ex){
        }
    }
    private void readFromExternal(){
        try {
            File sdcard = Environment.getExternalStorageDirectory();
            File f = new File(sdcard,"chuthich_ex.txt");
            BufferedReader br = new BufferedReader(new FileReader(f));
            String line;
            //Read text from file
            StringBuilder content = new StringBuilder();
            while ((line = br.readLine()) != null) {
                content.append(line);
                content.append('\n');
            }
            br.close();
            tvExternal.setText(content);
        }catch (Exception ex){
        }
    }
}

Lưu trữ dữ liệu trong android – Bài thực hành

Bài thực hành số 1:

Thiết kế giao diện ứng dụng

luu tru du lieu trong android 7

Viết xử lý cho nút “Gửi thông tin”

Kiểm tra thông tin

  • Họ tên không được để trống và phải có ít nhất 3 ký tự
  • Chứng minh nhân dân chỉ được nhập kiểu số và phải có đúng 9 chữ số
  • Bằng cấp mặc định sẽ chọn là Đại học
  • Sở thích phải chọn ít nhất 1
  • Nếu thông tin hợp lệ, ứng dụng sẽ lưu thông tin vào bộ nhớ (trong hoặc ngoài)

Lưu trữ dữ liệu trong android – Shared Preferences

Shared Preferences cho phép chúng ta lưu và đọc dữ liệu sử dụng cặp key/value. Để sử dụng shared preferences , chúng ta gọi phương thức getSharedPreferences() với cú pháp như sau:

SharedPreferences sp = getSharedPreferences("FileName", Mode);

Bảng sau đây mô tả về Mode

STTMiêu tả
1MODE_APPEND Nối preferences mới với preferences đã tồn tại
2MODE_PRIVATE Chỉ được truy cập cục bộ
3MODE_WORLD_READABLE Chế độ này cho phép ứng dụng khác đọc preferences
4MODE_WORLD_WRITEABLE Chế độ này cho phép ứng dụng khác ghi preferences

Để lưu vào shared preferences, chúng ta sử dụng lớp SharedPreferences.Editor. Lớp này cho thao tác dữ liệu bên trong shared preferences. Bảng sau sẽ trình bày các phương thức của lớp SharedPreferences.Editor.

STTMiêu tả
1commit() Lưu những thay đổi từ editor đến sharedPreference
2clear() Xoá tất cả dữ liệu từ editor
3remove(String key) Xoá dữ liệu dựa vào key
4putLong(String key, long value) Lưu dữ liệu kiểu long
5putInt(String key, int value) Lưu dữ liệu kiểu int
6putFloat(String key, float value) Lưu dữ liệu kiểu float

Xử lý ghi dữ liệu 

//Tạo đối tượng SharedPreferences
SharedPreferences sp = getSharedPreferences("FileName", Mode);
SharedPreferences.Editor editor = sp.edit();
//Lưu dữ liệu
editor.putX(key, value); //X là kiểu dữ liệu
//Hoàn thành
editor.commit();

Xử lý đọc dữ liệu 

//Tạo đối tượng SharedPreferences
SharedPreferences sp = getSharedPreferences("FileName", Mode);
//Đọc dữ liệu
sp.getX(key, default); //X là kiểu dữ liệu

Bài thực hành số 2

Thiết kế và viết xử lý cho màn hình đăng nhập (LoginActivity). Khi người dùng chọn “Remember”, thông tin đăng nhập sẽ được ghi lại cho lần đăng nhập kế tiếp.

Giao diện ứng dụng

luu tru du lieu trong android 8

Khi người dùng click nút “LOGIN”, nếu Remember được chọn, thông tin đăng nhập sẽ được lưu vào shared preferences.

Alert: You are not allowed to copy content or view source !!