Shared prefrence

By
SharedPrefrence

Android provide many ways to storing data of an our Application. Like Shared prefrence, Database and cloud.

along this we discuss on Shared prefrence with code.

Where is used Shared prefrenced?

Suppose we don’t have knowledge about database and all, and we store some small amount of data in our application that time we used prefrenced.
Using Shared prefrence we store many amount of data like String, Int or float.

example:

Suppose we login in the application, that time we store user loged in or not, that flag will be stored using prefrence.

Whenever we start our application that time we get data from the prefrence in checked user login flag true or false, further according this we display our next screen.

Advantage Of Shared prefrence

  • No need to required extra knowledge about sql and sql query.
  • Fast to store and retrive data compare database.
  • Stored data securly we access using shared prefrence.

Disadvantage

  • We not store large amount of data
  • Data will erase when application cache clear or uninstall our application
  • Change data not access in other device with same login or same user.

Method used to Shared Prefrence

  1. putLong(String key, long value) : Store long value in our device
  2. putInt(String key, int value) : Store Integer data in device
  3. putFloat(String key, int value) : Store float data
  4. putString(String key, int value) : Storing strimg data in Shared prefrence
  5. apply() : Storing data save in prefrence when we do the apply methode
  6. commit() : Storing data save in prefrence when we do the commmit methode
  7. remove() : remove particulare shared prefrence data

Use in Programming

Storing Data in SharedPrefrence

=> Storing String data



 public static void storeString(SharedPreferences sharedPreferences, String key, String value) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, value);
        editor.apply();
    }

Here, storeString method is used to storing string data, when we used this pass the SharedPrefrence onject, key of data and data value.
editor.putstring(key, value) method pass our key and value, when we apply() call that time it’s store data in our prefrence.
apply() methode work in background and it’s return type is void.

Note: You can also use commit() instead of apply(). but apply() is better, because it’s return type void and it’s process is asynchronously that’s while not taking more time to store data. it’s working background.
While commit() return boolean value, and working synchronously that’s while taking more time to compare apply().

=> Storing Array List



  public static void storeSerializeArraylist(SharedPreferences sharedPreferences, String key, ArrayList tempAppArraylist){
        SharedPreferences.Editor editor = sharedPreferences.edit();
        try {
            editor.putString(key, ObjectSerializer.serialize(tempAppArraylist));
            editor.apply();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

This function is used to storing array list in prefrence. storeSerializeArraylist method is very usefull for programming.
some time we need to store full array list data that time we implement this custom method.

=> Storing Int data



  public static void storeInt(SharedPreferences sharedPreferences, String key, int value) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt(key, value);
        editor.apply();
    }

Here, storeInt method is used to storing integer data, when we used this pass the SharedPrefrence onject, key of data and data value.

=> Storing Float data



  public static void storeFloat(SharedPreferences sharedPreferences, String key, float value) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putFloat(key, value);
        editor.apply();
    }

Retriving Data from SharedPrefrence

Now, we thing how to retrive those data from ShredPrefrence according to our requirement.
let’s see this,

=>Retrive String data From Prefrence



  public static String getPrefrenceStringData(SharedPreferences mPreferences, String Key){
        String prefdata ="";
        prefdata = mPreferences.getString(Key,"");
        return prefdata;
    }

=>Retrive Array List data From Prefrence



  public static ArrayList getSerializeArraylist(SharedPreferences sharedPreferences, String key){
        ArrayList tempArrayList = new ArrayList();
        try {
            tempArrayList = (ArrayList) ObjectSerializer.deserialize(sharedPreferences.getString(key, ObjectSerializer.serialize(new ArrayList())));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return tempArrayList;
    }

this methode returns array list data from the shared prefrence.

Before add above function create below 2 class in our project.

first is ObjectSerializer.java and WrappedIOException.java , both file look like this,

1.  WrappedIOException.java



package in.co.lifs.sharedprefdemo;

import java.io.IOException;

public class WrappedIOException {
    public static IOException wrap(final Throwable e) {
        return wrap(e.getMessage(), e);
    }

    public static IOException wrap(final String message, final Throwable e) {
        final IOException wrappedException = new IOException(message + " [" +
                e.getMessage() + "]");
        wrappedException.setStackTrace(e.getStackTrace());
        wrappedException.initCause(e);
        return wrappedException;
    }
}

1.  ObjectSerializer.java



package in.co.lifs.sharedprefdemo;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ObjectSerializer {

    public static String serialize(Serializable obj) throws IOException {
        if (obj == null) return "";
        try {
            ByteArrayOutputStream serialObj = new ByteArrayOutputStream();
            ObjectOutputStream objStream = new ObjectOutputStream(serialObj);
            objStream.writeObject(obj);
            objStream.close();
            return encodeBytes(serialObj.toByteArray());
        } catch (Exception e) {
            throw WrappedIOException.wrap("Serialization error: " + e.getMessage(), e);
        }
    }

    public static String encodeBytes(byte[] bytes) {
        StringBuffer strBuf = new StringBuffer();

        for (int i = 0; i < bytes.length; i++) { strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a')));
            strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a')));
        }

        return strBuf.toString();
    }

    public static Object deserialize(String str) throws IOException {
        if (str == null || str.length() == 0) return null;
        try {
            ByteArrayInputStream serialObj = new ByteArrayInputStream(decodeBytes(str));
            ObjectInputStream objStream = new ObjectInputStream(serialObj);
            return objStream.readObject();
        } catch (Exception e) {
            throw WrappedIOException.wrap("Deserialization error: " + e.getMessage(), e);
        }
    }

    public static byte[] decodeBytes(String str) {
        byte[] bytes = new byte[str.length() / 2];
        for (int i = 0; i < str.length(); i+=2) {
            char c = str.charAt(i);
            bytes[i/2] = (byte) ((c - 'a') << 4);
            c = str.charAt(i+1);
            bytes[i/2] += (c - 'a');
        }
        return bytes;
    }
}

Leave a Comment

Your email address will not be published.

Latest Blog