SharedPreferences

Showing posts with label SharedPreferences. Show all posts
Showing posts with label SharedPreferences. Show all posts

Wednesday, December 17, 2014

Creating Shared Preferences in android.....


This article shows how to create SharedPreferences in android.


import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;

public class MyPreferences {
    public static boolean putInt(Context activity,String key,int value){
        SharedPreferences sharedPreferences = activity.getSharedPreferences("pref", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt(key, value);
        editor.commit();                      
        return true;      
    }
 
    public static int getInt(Context activity,String key,int defaultValue){
        SharedPreferences sharedPreferences = activity.getSharedPreferences("pref", Activity.MODE_PRIVATE);
        int temp = sharedPreferences.getInt(key, defaultValue);
        return temp;      
    }
 
    public static boolean putString(Context activity, String key, String value)
    {
    SharedPreferences sharedPreferences = activity.getSharedPreferences("pref", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, value);
        editor.commit();                      
        return true;         }
 
    public static String getString(Context activity,String key,String defaultValue){
        SharedPreferences sharedPreferences = activity.getSharedPreferences("pref", Activity.MODE_PRIVATE);
        String temp = sharedPreferences.getString(key, defaultValue);
        return temp;      
    }
 
    public static boolean putLong(Context activity, String key, long value)
    {
    SharedPreferences sharedPreferences = activity.getSharedPreferences("pref", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putLong(key, value);
        editor.commit();
return true;         }
 
    public static long getLong(Context activity,String key,long defaultValue){
        SharedPreferences sharedPreferences = activity.getSharedPreferences("pref", Activity.MODE_PRIVATE);
        long temp = sharedPreferences.getLong(key, defaultValue);
        return temp;      
    }
 
}

By implementing above code you can easily Create SharedPreferences.