কম্পিউটার টিউটোরিয়াল

Android-এ HashMap কে SharedPreferences-এ সংরক্ষণ করা

HashMap কে JSON হিসেবে SharedPreferences-এ সংরক্ষণ

SharedPreferences সরাসরি HashMap সাপোর্ট করে না। এই টিউটোরিয়ালে JSON-এ কনভার্ট করে সংরক্ষণ ও পুনরুদ্ধারের পদ্ধতি দেখানো হয়েছে।

ধাপ ১: প্রজেক্ট তৈরি

Android Studio-তে নতুন প্রজেক্ট তৈরি করুন।

ধাপ ২: লেআউট (activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/rlMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp"
    android:orientation="vertical">
    <EditText
        android:id="@+id/etName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Name"
        android:inputType="text" />
    <EditText
        android:id="@+id/etAge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Age"
        android:inputType="number" />
    <EditText
        android:id="@+id/etGame"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Favourite Game"
        android:inputType="text" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:onClick="saveLocal"
        android:text="Save Locally" />
</LinearLayout>

ধাপ ৩: MainActivity.java

package com.example.hashmapsharedprefs;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;

public class MainActivity extends AppCompatActivity {
    private static final String PREFS_NAME = "MyVariables";
    private static final String MAP_KEY = "map";
    
    EditText etName, etAge, etGame;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        etName = findViewById(R.id.etName);
        etAge = findViewById(R.id.etAge);
        etGame = findViewById(R.id.etGame);
        
        // সেভড ডেটা লোড করুন
        Map savedMap = loadMap();
        if (savedMap.containsKey("name")) 
            etName.setText(Objects.toString(savedMap.get("name"), ""));
        if (savedMap.containsKey("age")) 
            etAge.setText(Objects.toString(savedMap.get("age"), ""));
        if (savedMap.containsKey("game")) 
            etGame.setText(Objects.toString(savedMap.get("game"), ""));
    }

    public void saveLocal(View view) {
        String name = etName.getText().toString().trim();
        String age = etAge.getText().toString().trim();
        String game = etGame.getText().toString().trim();
        
        if (name.isEmpty()) {
            etName.setError("Required"); etName.requestFocus();
        } else if (age.isEmpty()) {
            etAge.setError("Required"); etAge.requestFocus();
        } else if (game.isEmpty()) {
            etGame.setError("Required"); etGame.requestFocus();
        } else {
            Map inputMap = new HashMap<>();
            inputMap.put("name", name);
            inputMap.put("age", age);
            inputMap.put("game", game);
            saveMap(inputMap);
            Toast.makeText(this, "Saved Locally!", Toast.LENGTH_SHORT).show();
        }
    }

    private void saveMap(Map inputMap) {
        SharedPreferences prefs = getApplicationContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        if (prefs != null) {
            JSONObject jsonObject = new JSONObject(inputMap);
            String jsonString = jsonObject.toString();
            
            SharedPreferences.Editor editor = prefs.edit();
            editor.remove(MAP_KEY).apply();
            editor.putString(MAP_KEY, jsonString);
            editor.apply(); // apply() অ্যাসিঙ্ক্রোনাস, commit() সিনক্রোনাস
        }
    }

    private Map loadMap() {
        Map outputMap = new HashMap<>();
        SharedPreferences prefs = getApplicationContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        
        try {
            if (prefs != null) {
                String jsonString = prefs.getString(MAP_KEY, new JSONObject().toString());
                JSONObject jsonObject = new JSONObject(jsonString);
                Iterator keysItr = jsonObject.keys();
                while (keysItr.hasNext()) {
                    String key = keysItr.next();
                    outputMap.put(key, jsonObject.get(key));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return outputMap;
    }
}

ধাপ ৪: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.hashmapsharedprefs">
    <application ...>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

আধুনিক বিকল্প: DataStore (Preferences DataStore)

Jetpack DataStore হলো SharedPreferences-এর আধুনিক প্রতিস্থাপন:

// build.gradle
implementation "androidx.datastore:datastore-preferences:1.0.0"

// ব্যবহার
val Context.dataStore: DataStore by preferencesDataStore(name = "settings")
val EXAMPLE_COUNTER = intPreferencesKey("example_counter")

// লিখুন
suspend fun incrementCounter() {
    dataStore.edit { settings ->
        val current = settings[EXAMPLE_COUNTER] ?: 0
        settings[EXAMPLE_COUNTER] = current + 1
    }
}

// পড়ুন
val counterFlow: Flow = dataStore.data.map { it[EXAMPLE_COUNTER] ?: 0 }

তুলনা

ফিচারSharedPreferencesDataStore
APIসিনক্রোনাস/অ্যাসিঙ্ক্রোনাসFlow/Coroutines ( Reactive)
থ্রেড সেফটিলিমিটেডহ্যাঁ
টাইপ সেফটিনাহ্যাঁ (Preferences Proto DataStore-এ)
মাইগ্রেশনম্যানুয়ালবিল্ট-ইন

নোট: জটিল ডেটা স্ট্রাকচার (নেস্টেড অবজেক্ট, লিস্ট) এর জন্য Room Database বা DataStore Protobuf ভালো। সাধারণ কি-ভ্যালু জন্য DataStore Preferences পর্যাপ্ত।

  1. অ্যান্ড্রয়েডে লাইন আঁকা (Canvas এবং Paint ব্যবহার করে)

  2. অ্যান্ড্রয়েডে প্রোগ্রামেটিক্যালি GPS সক্ষম/অক্ষম করা

  3. অ্যান্ড্রয়েডে URL থেকে ইমেজ ডাউনলোড ও সংরক্ষণ করা

  4. অ্যান্ড্রয়েডে অন্য অ্যাপ্লিকেশনের SharedPreferences পড়ার পদ্ধতি