Shared Preferences in Android

What is Shared Prefrences in Android? Need of it in Application.

If you want to store data you can use Share preferences. In the share preferences ,data store in Key-Value pairs. Generally,  In Shared preferences  use  for Primitive data storage. If you want to store data in Relational or Tabular format refer SQLite Database


Android stores the shared preferences data in XML file in shared_prefs folder under  DATA/data/[application package] directory.

Share preference contains different types of MODES. It provide the accessibility of data.

1.) MODE_PRIVATE
 
   It is file creation Mode. It is default mode, where the created file can only be accessed by the calling application. Its constant value is 0.


2.)  MODE_WORLD_READABLE 

  This mode allows other application to read preferences. The constant value is 1.

3.) MODE_WORLD_WRITABLE

  This mode allows the other application to write the preferences. The constant value is 2.

4.) MODE_MULTI_PROCESS

  This method will check for modification of preferences even if the shared preferences instance
  has already been Loaded. The constant value is 4.

5.) MODE_APPEND

It will be append the new preference with existing preferences. The constant value is 32768.

6.) MODE_ENABLE_WRITE_AHEAD_LOGGING

Database open flag. When it is set ,it would be enable write ahead logging by default. The constant value is 8.



Some important method of Share preferences

contains(String key) - It checks the preferences check any preference.

edit()  - It create a new Editor Through which you can modify the data in existing preferences.

getAll() - It retrieve all the value from the preferences.

getString(String key,String defaultValue) - It retrieve a String value from the preferences. If                                                                                         prefrence value null the return defaultValue.



Initialize the shared preference  in Activity

SharedPreferences mSharedPreferences;
mSharedPreferences= getApplicationContext().getSharedPreferences("mypreference", Context.MODE_PRIVATE);

Initialize the shared preference  in Fragment

SharedPreferences mSharedPreferences;
mSharedPreferences= getActivity().getSharedPreferences("mypreference", Context.MODE_PRIVATE);

If you want to save the data in shared preference,  you have to use  SharedPreferences.Editor class.


SharedPreferences.Editor mEditor;
mEditor= mSharedPreferences.edit();
mEditor.putString("name", name);
mEditor.putString("email",email);

To save the value in preference

mEditor.commit();
To get the data from share prefrences
SharedPreferences mSharedPreferences;
mSharedPreferences= getApplicationContext().getSharedPreferences("myprefence", Context.MODE_PRIVATE);
String name = mSharedPreferences.getString("name", "");
String email = mSharedPreferences.getString("email", "");
Example

activity_main.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:layout_scrollFlags="scroll|enterAlways" />
</android.support.design.widget.AppBarLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="@+id/etName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:background="@android:color/white"
android:hint="Enter Name"
android:layout_margin="5dp"
android:inputType="text"/>
<EditText
android:id="@+id/etemail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:background="@android:color/white"
android:hint="Enter Email"
android:layout_margin="5dp"
android:inputType="textEmailAddress"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/btnSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/white"
android:text="Submit"
android:layout_margin="2dp"
android:layout_weight="1"
android:background="@color/colorPrimary"/>
<Button
android:id="@+id/btnLink"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/white"
android:text="Click to see value"
android:layout_weight="1"
android:layout_margin="2dp"
android:background="@color/colorPrimary"/>
</LinearLayout>
</LinearLayout>

MainActivity.java



package demo.ecom.adnig.sharepreference_demo; import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
SharedPreferences mSharedPreferences;
SharedPreferences.Editor mEditor;
EditText etName,etEmail;
Button btnSubmit,btnNextActivity;
String name,email;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
etName = (EditText) findViewById(R.id.etName);
etEmail = (EditText)findViewById(R.id.etemail);
btnSubmit = (Button)findViewById(R.id.btnSubmit);
btnNextActivity = (Button)findViewById(R.id.btnLink);
// initilze sharedPreferences
mSharedPreferences= getApplicationContext().getSharedPreferences("myprefence", Context.MODE_PRIVATE);
mEditor= mSharedPreferences.edit();
btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
name = etName.getText().toString();
email = etEmail.getText().toString();
if(!(name.equals("")) && !(email.equals(""))) {
mEditor.putString("name", name);
mEditor.putString("email", email);
mEditor.commit();
Toast.makeText(MainActivity.this,"Your data save in Share Preferences",Toast.LENGTH_LONG).show();
}
}
});
btnNextActivity.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,SecondActivity.class));
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}

activity_second.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:layout_scrollFlags="scroll|enterAlways" />
</android.support.design.widget.AppBarLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_weight="1"
android:background="@android:color/white"
android:text="Name"
android:layout_margin="5dp"
/>
<TextView
android:id="@+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_weight="1"
android:background="@android:color/white"
android:layout_margin="5dp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_weight="1"
android:background="@android:color/white"
android:text="Email"
android:layout_margin="5dp"
/>
<TextView
android:id="@+id/tvEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_weight="1"
android:background="@android:color/white"
android:layout_margin="5dp"
/>
</LinearLayout>
</LinearLayout>

SecondActivity.java

package demo.ecom.adnig.sharepreference_demo;
import
android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class SecondActivity extends AppCompatActivity {
TextView tvName,tvEmail;
SharedPreferences mSharedPreferences;
String name,email;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
tvName = (TextView)findViewById(R.id.tvName);
tvEmail = (TextView)findViewById(R.id.tvEmail);
mSharedPreferences= getApplicationContext().getSharedPreferences("myprefence", Context.MODE_PRIVATE);
name = mSharedPreferences.getString("name", "");
email = mSharedPreferences.getString("email", "");
tvName.setText(name);
tvEmail.setText(email);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_second, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

Output





you can download from Githib
SHARE

About prabhakar jha

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment