Share Preferances right way
Tags: android
Published: 2023-06-22 08:03:51

Let's keep it easy and simple

Shared preferences
Shared preferences allow you to store small amounts of primitive data as key/value pairs in a file on the device

keep track of small bits of important
Store information without needing a storage permission



```
public class MainActivity extends AppCompatActivity {
    TextView sharedPref;
    Button buttonAdd;
    int count=0;

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

        SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
        count = sp.getInt("your_int_key", -1);


        sharedPref=findViewById(R.id.sharedPref);
        buttonAdd=findViewById(R.id.buttonAdd);
        sharedPref.setText(""+count);

        buttonAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                count++;
                sharedPref.setText(""+count);

                SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();
                editor.putInt("your_int_key", count);
                editor.commit();
            }
        });

    }
}
```

Lets Upgrade to PreferenceUtil
you must be thinking why PreferenceUtil 🤔 , let's see why should we use this.
1) Much cleaner and readable code.
2) Can access any variable from any class.

--> To get the value
PreferenceUtil.getInstance(MainActivity.this).getCountNum();
--> To set the value

PreferenceUtil.getInstance(MainActivity.this).SetCountNum(count);
3) Code is reduced.
4) Variables using shared preferences are in one place.
5) Fewer errors due to key naming.
6) Easy to use with ViewModel.
7) Very good for you to handle large projects.

I hope these advantages are good enough for you to migrate😎.

MainActivity Code

```
package com.androxus.prefranceutil;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;


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

public class MainActivity extends AppCompatActivity {
    TextView sharedPref;
    Button buttonAdd;
    int count=0;


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


        sharedPref=findViewById(R.id.sharedPref);
        buttonAdd=findViewById(R.id.buttonAdd);


//        SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
//        count = sp.getInt("your_int_key", -1);
        count=PreferenceUtil.getInstance(MainActivity.this).getCountNum();


        sharedPref.setText(""+count);
        buttonAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                count++;
                sharedPref.setText(""+count);
                PreferenceUtil.getInstance(MainActivity.this).SetCountNum(count);


//                SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
//                SharedPreferences.Editor editor = sp.edit();
//                editor.putInt("your_int_key", count);
//                editor.commit();
            }
        });

    }
}
```
PreferenceUtil class code

```
package com.androxus.prefranceutil;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class PreferenceUtil {


    public static final String COUNT_VALUE = "count_value";
    public static final String COUNT_NUM = "count";
    private static com.androxus.prefranceutil.PreferenceUtil sInstance;
    private SharedPreferences mPref;
    private SharedPreferences.Editor mEditor;

    private PreferenceUtil(final Context context) {
        mPref = PreferenceManager.getDefaultSharedPreferences(context);
    }
    public static com.androxus.prefranceutil.PreferenceUtil getInstance(final Context context) {
        if (sInstance == null)
            sInstance = new com.androxus.prefranceutil.PreferenceUtil(context.getApplicationContext());
        return sInstance;
    }

    public final int getCountNum() {
        return mPref.getInt(COUNT_NUM,0);
    }

    public final int getCount() {
        return mPref.getInt(COUNT_VALUE,0);
    }

    public void setCount(int count) {
        final SharedPreferences.Editor editor = mPref.edit();
        editor.putInt(COUNT_VALUE, count);
        editor.apply();
    }

    public void SetCountNum(int count) {
        final SharedPreferences.Editor editor = mPref.edit();
        editor.putInt(COUNT_NUM, count);
        editor.apply();
    }
}
```
ENJOY HOPE YOU LIKE