Friday, 10 April 2015

How to save String,integer etc preferences in android

Android provides below storage options to store our data.We just have to choose depending on our requrirement.

1. Shared Preferences : to store data corresponding to particular keys. Data can be int,string,boolen etc.

2. Internal Storage : to store data in internal storage can be images,videos,text files etc.

3. External Storage : same as internal can be use to stored above data.

4. SQLite Databases : Sqlite is a mobile database in android which allows us to store data as we do in web but on small scale.

5. Network Connection : we can use web services to store data on web servers.

Here i will providing code for storing our small scale data in preferences via methods.We just have to pass the keys and values to store and keys to fetch those stored values.


1. For Storing Integer values : 

public static void saveIntSharePrefs(Context mContext,int Position,String key)
  {
SharedPreferences pref = mContext.getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
editor.putInt(key,Position);
editor.commit();
}

2. For Fetching Integer values :

public static int getSaveIntSharePrefs(Context mContext,String key)
{
SharedPreferences pref = mContext.getSharedPreferences("MyPref", 0); // 0 - for private mode
return pref.getInt(key, 0);
}

3. For Storing String values : 

public static void saveStringSharePrefs(Context mContext,String value,String key)
{
SharedPreferences pref = mContext.getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
editor.putString(key,value);
editor.commit();
}

4. For Fetching String values :

public static String getSaveStringSharePrefs(Context mContext,String key)
{
SharedPreferences pref = mContext.getSharedPreferences("MyPref", 0); // 0 - for private mode
return pref.getString(key, "");
}


5.For Storing Boolean values : 

public static void saveBooleanSharePrefs(Context mContext,Boolean value,String key)
{
SharedPreferences pref = mContext.getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
editor.putBoolean(key,value);
editor.commit();
}

6. For Fetching Boolean values :

public static Boolean getSaveBooleanSharePrefs(Context mContext,String key)
{
SharedPreferences pref = mContext.getSharedPreferences("MyPref", 0); // 0 - for private mode
return pref.getBoolean(key, false);
}



Cheers!!
happy Coding!!

No comments:

Post a Comment