Shared Preferences are XML files to store private primitive data in key-value pairs. Data Types include Booleans, floats, ints, longs, and strings.
When we want to save some data which is accessible throughout the application, one way to do is to save it in global variable. But it will vanish once the application is closed. Another and recommended way is to save in SharedPreference
SharedPreferences saves the data in key-value pair and can be accessed in same.
we can create Object of SharedPreferences using two methods,
1).getSharedPreferences() : Using this methods you can create Multiple SharedPreferences.and its first parameters in name of SharedPreferences.
2).getPreferences() : Using this method you can create Single SharedPreferences.
MainActivity[MainActivity.class]
package com.androidfeeders.sharedpreferencesexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText editText;
EditText editText1;
Button button;
String string,string1;
TextView textView;
SqliteDBHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText=(EditText)findViewById(R.id.input);
editText1=(EditText)findViewById(R.id.input1);
textView=(TextView) findViewById(R.id.getString);
button=(Button) findViewById(R.id.buttonClick);
button.setOnClickListener(this);
//Sqlite database
dbHelper= new SqliteDBHelper(getApplicationContext());
}
@Override
public void onClick(View view) {
string= editText.getText().toString();
string1= editText1.getText().toString();
//Sqlite database
dbHelper.insertData(string,string1);
//Shared Preferences
SharedPreferenceHelper.getInstance(this).saveStringData("keystring",string); //get data
textView.setText(SharedPreferenceHelper.getInstance(this).getStringData("keystring")); //set data
}
}
SharedPreferenceHelper[SharedPreferenceHelper.class]
package com.androidfeeders.sharedpreferencesexample;
import android.content.Context;
import android.content.SharedPreferences;
public class SharedPreferenceHelper {
private static SharedPreferenceHelper sharedPreferenceHelper;
private SharedPreferences sharedPreferences;
//Singleton method for create single instance in application
public static SharedPreferenceHelper getInstance(Context context) {
if (sharedPreferenceHelper == null) {
sharedPreferenceHelper = new SharedPreferenceHelper(context);
}
return sharedPreferenceHelper;
}
// SharedPreferenceHelper class Constuctor
// @param context
private SharedPreferenceHelper(Context context) {
//context mode private only access in applicaion itself
sharedPreferences = context.getSharedPreferences("pref", Context.MODE_PRIVATE);
}
/**
* Get String value for a particular key.
*
* @param key The string resource Id of the key
* @param value The default value to return
*/
public void saveStringData(String key, String value) {
SharedPreferences.Editor prefsEditor = sharedPreferences.edit();
prefsEditor.putString(key, value);
prefsEditor.commit();
}
/**
* Set String value for a particular key.
*
* @param key The string resource Id of the key
*/
public String getStringData(String key) {
if (sharedPreferences != null) {
return sharedPreferences.getString(key, "");
}
return "";
}
}
SqliteDBHelper[SqliteDBHelper.class]
package com.androidfeeders.sharedpreferencesexample;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class SqliteDBHelper extends SQLiteOpenHelper {
public static final String TABLENAME = "";
public static final String COL1 = "ID";
public static final String COL2 = "NAME";
public static final String COL3 = "PLACE";
public SqliteDBHelper(Context context) {
super(context, "Student.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("CREATE TABLE" + TABLENAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT ,NAME TEXT, PLACE TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS" + TABLENAME);
}
public boolean insertData(String name,String place)
{
SQLiteDatabase sqLiteDatabase= this.getWritableDatabase();
ContentValues contentValues= new ContentValues();
contentValues.put(COL2,name);
contentValues.put(COL3,place);
sqLiteDatabase.insert(TABLENAME,null,contentValues);
return true;
}
}
Layout Resource[activity_main.xml]
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:layout_width="160dp"
android:id="@+id/input"
android:layout_height="wrap_content"
android:hint="name"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.318"
app:layout_constraintHorizontal_bias="0.446" />
<EditText
android:layout_width="160dp"
android:id="@+id/input1"
android:layout_height="wrap_content"
android:hint="place"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.44"
app:layout_constraintHorizontal_bias="0.446" />
<Button
android:layout_width="160dp"
android:id="@+id/buttonClick"
android:layout_height="wrap_content"
android:text="save"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.65" />
<TextView
android:layout_width="160dp"
android:id="@+id/getString"
android:layout_height="wrap_content"
android:text="Type something"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.805"
app:layout_constraintHorizontal_bias="0.566" />
</android.support.constraint.ConstraintLayout>
Gradle Scripts~build.gradle[Module:app]
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.androidfeeders.sharedpreferencesexample"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
Gradle Scripts~build.gradle[Project:BaseAdapterSample]
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Resource[strings.xml]
<resources>
<string name="app_name">SharedPreferencesExample</string>
</resources>
manifests
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidfeeders.sharedpreferencesexample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".sharedpreferencesexample">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I started to learn android and Kotlin and iOS and Hybrid application and i cant code IOS very well. But i love more interesting to code and finding new developer minds who are join to me You're welcome to keep on using my website.Instead, you can join our FB page for developer comments and post there: https://www.facebook.com/ramasamy.m.779 Best wishes :) Ramasamy(Software Developer)
See what's new in Android & IOS & Hybrid development … explore and learn in site
Ramasamy
5 min agoKotlin and React native example too
ReplyRamasamy
5 min agoKotlin and React native example too
ReplyRamasamy
5 min agoKotlin and React native example too
Reply