CyStack logo
  • Sản phẩm & Dịch vụ
  • Giải pháp
  • Bảng giá
  • Công ty
  • Tài liệu
Vi

vi

Mục lục

Trang chủBlogLưu trữ dữ liệu trong And...
Android

Lưu trữ dữ liệu trong Android: Cách sử dụng SharedPreferences

4 phút đọc17/08/2025
CyStack Author
Chris Pham

Technical Writer

0 lượt xem
Reading Time: 4 minutes

Trong bài hướng dẫn này, chúng ta sẽ khám phác cách lưu trữ dữ liệu trong Android bằng SharedPreferences.

Lưu trữ dữ liệu trong Android

Tổng quan về Android Shared Preferences

Shared Preferences cho phép các activity và ứng dụng lưu lại preferences dưới dạng các cặp key-value (tương tự như Map), và dữ liệu này sẽ được duy trì ngay cả khi người dùng đóng ứng dụng. Android lưu các cài đặt của Shared Preferences dưới dạng file XML trong thư mục shared_prefs tại đường dẫn DATA/data/{application package}. Có thể lấy đường dẫn đến thư mục DATA bằng cách gọi Environment.getDataDirectory().

SharedPreferences chỉ dành riêng cho ứng dụng, tức là dữ liệu sẽ bị mất khi:

  • Gỡ cài đặt ứng dụng
  • Xóa dữ liệu ứng dụng (thông qua mục Settings)

Đúng như tên gọi, mục đích chính của Shared Preferences là để lưu trữ các cấu hình của người dùng, ví dụ như các cài đặt riêng hoặc duy trì trạng thái đăng nhập cho ứng dụng.

Để truy cập vào các preferences, chúng ta có ba API để lựa chọn:

  • getPreferences(): sử dụng bên trong Activity để truy cập các preferences của riêng Activity đó.
  • getSharedPreferences(): sử dụng bên trong Activity (hoặc Context khác của ứng dụng) để truy cập các preferences ở cấp độ ứng dụng.
  • getDefaultSharedPreferences(): sử dụng trên PreferenceManager để lấy đối tượng SharedPreferences, hoạt động phối hợp với framework quản lý preference chung của Android.

Trong bài hướng dẫn này, chúng ta sẽ sử dụng getSharedPreferences(). Phương thức này được định nghĩa như sau: getSharedPreferences(String PREFS_NAME, int mode). Trong đó, PREFS_NAME là tên của file. mode là chế độ hoạt động.

Các chế độ hoạt động có thể áp dụng bao gồm:

  • MODE_PRIVATE: chế độ mặc định, file được tạo chỉ có thể được truy cập bởi ứng dụng đã gọi.
  • MODE_WORLD_READABLE: Tạo file mà các ứng dụng khác có thể đọc là rất nguy hiểm và có khả năng gây ra lỗ hổng bảo mật.
  • MODE_WORLD_WRITEABLE: Tạo file mà các ứng dụng khác có thể ghi là rất nguy hiểm và có khả năng gây ra lỗ hổng bảo mật.
  • MODE_MULTI_PROCESS: Phương thức này sẽ kiểm tra các sửa đổi của preferences ngay cả khi instance của Shared Preference đã được tải.
  • MODE_APPEND: Chế độ này sẽ nối các preference mới vào các preference đã tồn tại.
  • MODE_ENABLE_WRITE_AHEAD_LOGGING: Cờ mở database. Khi được thiết lập, nó sẽ bật tính năng ghi log trước khi ghi (write-ahead logging) theo mặc định.

Khởi tạo

Chúng ta cần một Editor để chỉnh sửa và lưu các thay đổi trong SharedPreferences. Có thể sử dụng đoạn code sau để lấy đối tượng SharedPreferences.

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();

Lưu trữ dữ liệu

editor.commit() được dùng để lưu các thay đổi vào SharedPreferences.

editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long
 
editor.commit(); // commit changes

Truy xuất dữ liệu

Dữ liệu có thể được truy xuất từ SharedPreferences đã lưu bằng cách gọi các phương thức get như sau:

pref.getString("key_name", null); // getting String
pref.getInt("key_name", -1); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean

Xóa dữ liệu

remove(“key_name”) được dùng để xóa một giá trị cụ thể. clear() được dùng để xóa toàn bộ dữ liệu.

editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
 
editor.commit(); // commit changes
editor.clear();
editor.commit(); // commit changes

Cấu trúc Project

android-shared-preferences-project-view

Code cho Project Android Shared Preferences

Layout activity_main.xml bao gồm hai EditText để lưu và hiển thị tên và email. Ba Button sẽ triển khai các sự kiện onClick tương ứng trong MainActivity.



    

File MainActivity.java được dùng để lưu và truy xuất dữ liệu thông qua các key.

package com.journaldev.sharedpreferences;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {
    SharedPreferences sharedpreferences;
    TextView name;
    TextView email;
    public static final String mypreference = "mypref";
    public static final String Name = "nameKey";
    public static final String Email = "emailKey";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name = (TextView) findViewById(R.id.etName);
        email = (TextView) findViewById(R.id.etEmail);
        sharedpreferences = getSharedPreferences(mypreference,
                Context.MODE_PRIVATE);
        if (sharedpreferences.contains(Name)) {
            name.setText(sharedpreferences.getString(Name, ""));
        }
        if (sharedpreferences.contains(Email)) {
            email.setText(sharedpreferences.getString(Email, ""));

        }

    }

    public void Save(View view) {
        String n = name.getText().toString();
        String e = email.getText().toString();
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.putString(Name, n);
        editor.putString(Email, e);
        editor.commit();
    }

    public void clear(View view) {
        name = (TextView) findViewById(R.id.etName);
        email = (TextView) findViewById(R.id.etEmail);
        name.setText("");
        email.setText("");

    }

    public void Get(View view) {
        name = (TextView) findViewById(R.id.etName);
        email = (TextView) findViewById(R.id.etEmail);
        sharedpreferences = getSharedPreferences(mypreference,
                Context.MODE_PRIVATE);

        if (sharedpreferences.contains(Name)) {
            name.setText(sharedpreferences.getString(Name, ""));
        }
        if (sharedpreferences.contains(Email)) {
            email.setText(sharedpreferences.getString(Email, ""));

        }
    }

    @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;
    }

}

mypreference là tên của file nơi lưu trữ các cặp key-value của Shared Preferences. Hình ảnh bên dưới cho thấy kết quả cuối cùng của project.

android-shared-preferences-project-view

Bài hướng dẫn đến đây là kết thúc. Bạn có thể tải project Android Shared Preferences về từ liên kết bên dưới.

[Tải xuống Dự án Mẫu Android Shared Preferences]

Về tác giả

Chris Pham
Chris PhamTechnical Writer

I have over 5 years of experience writing technical documentation for tech products, making them accessible and user-friendly. My focus is always on providing clear and precise information. @#@ Tôi đã có hơn 5 năm kinh nghiệm viết tài liệu kỹ thuật cho các sản phẩm công nghệ, giúp người dùng dễ dàng tiếp cận và sử dụng. Tôi luôn tập trung vào việc cung cấp thông tin chính xác và dễ hiểu.

Cập nhật thông tin mới nhấtNhận các thông tin mới nhất về mối đe dọa, báo cáo an ninh mạng từ CyStack về hòm thư điện tử của bạn

Thảo luận (0)

Đăng nhập để thảo luận

Bài viết liên quan