Singleton để lưu trữ dữ liệu chia sẻ
Singleton thường được dùng làm kho dữ liệu trung tâm (central data store) cho phép các thành phần khác nhau trong ứng dụng truy cập và chia sẻ dữ liệu mà không cần truyền qua Intent hay Bundle.
Bước 1: Tạo dự án mới
Android Studio → File → New Project → chọn Empty Activity.
Bước 2: Giao diện (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Nhập văn bản" />
<Button
android:id="@+id/save"
android:text="Lưu vào Singleton"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Bước 3: MainActivity.java
package com.example.singletonclass;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText editText;
Button btnSave;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
btnSave = findViewById(R.id.save);
btnSave.setOnClickListener(v -> {
String input = editText.getText().toString().trim();
if (input.isEmpty()) {
editText.setError("Vui lòng nhập văn bản");
return;
}
SingleTonExample singleton = SingleTonExample.getInstance();
singleton.setText(input);
Toast.makeText(MainActivity.this,
"Đã lưu: " + singleton.getText(),
Toast.LENGTH_LONG).show();
});
}
}
Bước 4: SingleTonExample.java
package com.example.singletonclass;
public class SingleTonExample {
private String storedText;
private static final SingleTonExample ourInstance = new SingleTonExample();
public static SingleTonExample getInstance() {
return ourInstance;
}
private SingleTonExample() { }
public void setText(String text) {
this.storedText = text;
}
public String getText() {
return storedText;
}
}
Chạy và kiểm tra
- Nhập văn bản vào EditText (ví dụ: "Hello Singleton")
- Nhấn nút "Lưu vào Singleton"
- Toast hiển thị nội dung vừa lưu từ Singleton
- Thử rotate màn hình hoặc đóng/mở app → dữ liệu vẫn còn (trong cùng process)
Ứng dụng thực tế
- Lưu trữ cấu hình người dùng (User preferences)
- Cache dữ liệu API response
- Quản lý trạng thái đăng nhập (User session)
- Chia sẻ dữ liệu giữa các Fragment/Activity
⚠️ Lưu ý quan trọng
Singleton trong Android không bền vững (non-persistent). Dữ liệu sẽ mất khi:
- Process bị kill bởi hệ thống (low memory)
- User force-stop app
- Reboot thiết bị
→ Cần kết hợp với SharedPreferences, Room Database, hoặc DataStore để lưu trữ bền vững.