Ví dụ sử dụng SharedPreferences trong Android

SharedPreferences là gì? Nội dung bài trước chúng ta đã tìm hiểu SharedPreferences trong Android thì toàn bộ bài viết này sẽ hướng dẫn ví dụ sử dụng SharedPreferences trong Android.

Ngoài SQLite hoặc Realm thì SharedPreferences trong Android cũng là một giải pháp giúp thực hiện lưu trữ và truy xuất dữ liệu dưới dạng cặp giá trị key – value.

Nếu bạn chưa xem nội dung phần tìm hiểu SharedPreferences trong Android thì có thể theo dõi lại để hiểu rõ hơn trước khi thực hiện ví dụ sử dụng SharedPreferences trong Android.

Bước 1: Bạn mở Android Studio lên sau đó chọn mục File -> New -> New Project và điền các thông tin về dự án bao gồm tên dự án, nơi lưu trữ… sau đó nhấn Next để qua bước kế tiếp.

Trong màn hình tiếp theo thì bạn có thể lựa chọn theo như mình là chọn mục Empty Activity như sau:

Bước 2: Thiết kế giao diện hiển thị ứng dụng, mở tập tin activity_main.xml sau đó chúng ta thiết kế giao diện gồm 2 EditText để nhập họ tên và email cùng với 1 Button thực hiện lưu dữ liệu sau khi người dùng nhập.

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:layout_margin="20dp"
    android:layout_gravity="center"
    android:gravity="center">

    <EditText
        android:id="@+id/edtTen"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:hint="Họ và tên..."/>

    <EditText
        android:id="@+id/edtEmail"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:hint="Địa chỉ Email..."/>

    <Button
        android:id="@+id/btnLuu"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="Lưu dữ liệu"/>


</LinearLayout>

Giao diện chương trình sẽ như sau:

Bước 3: Tại MainActivity.java chúng ta sẽ thực hiện truy xuất và lưu dữ liệu vào SharedPreferences trong Android.

Đọc dữ liệu từ SharedPreferences thì gọi phương thức theo cú pháp như sau:

get<TypeData>("key_name", "value_default");

Bạn có thể gán dữ liệu mặc định trong “value_default” nếu dữ liệu trả về trong “key_name” không lấy được hoặc rỗng.

SharedPreferences sharedPref = getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
String name = sharedPref.getString("name", "");
String email = sharedPref.getString("email", "");

Để ghi dữ liệu vào một tập tin SharedPreferences trong Android bạn hãy tạo đối tượng SharedPreferences.Editor bằng cách gọi phương thức edit().

SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("name", edtTen.getText().toString());
editor.putString("email", edtEmail.getText().toString());
editor.commit();

Mã nguồn toàn bộ tập tin MainActivity.java như sau:

package com.teamvietdev.android.sharedpreferences;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    EditText edtTen;
    EditText edtEmail;
    Button btnLuu;

    SharedPreferences sharedPref;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sharedPref = getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);

        edtTen = findViewById(R.id.edtTen);
        edtEmail = findViewById(R.id.edtEmail);
        btnLuu = findViewById(R.id.btnLuu);

        String name = sharedPref.getString("name", "");
        String email = sharedPref.getString("email", "");
        edtTen.setText(name);
        edtEmail.setText(email);

        btnLuu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.putString("name", edtTen.getText().toString());
                editor.putString("email", edtEmail.getText().toString());
                editor.commit();
                Toast.makeText(getApplicationContext(), "Lưu dữ liệu thành công!", Toast.LENGTH_SHORT).show();
            }
        });

    }

}

Lời kết: Như vậy có nhiều cách để thực hiện lưu trữ và truy xuất dữ liệu như sử dụng SQLite, Realm hoặc có thể là sử dụng SharedPreferences trong Android tùy theo mục đích sử dụng mà bạn chọn thư viện phù hợp. Hẹn gặp lại các bạn trong các bài viết tiếp theo trong chuyên mục lập trình Android với nhiều bài viết hướng dẫn, tài liệu, lập trình Android.

(Tác giả: Team Việt Dev)

Bình luận