Handling Data between Activities in Android using Shared Preferences

in #utopian-io6 years ago (edited)

Repository

https://github.com/Godwyyn/AndroidSharedPreference

What Will I Learn?

In this tutorial, you will learn the following:

  • How to store data in Shared Preferences
  • How to retrieve the data stored and show it in a view
  • XML layout design

Requirements

For this tutorial, you will need the following:

  • A laptop with any operating system such as Windows OS, Mac OSX and Linux
  • Android studio, you can get it here
  • Knowledge of Java, XML

Difficulty

  • Basic

Tutorial Contents

Shared Preferences is one of the many ways of storing data of an application. It can be used to store data, edit and also retrieve whenever needed. Shared Preferences allow user to save and retrieve data in the form of key,value pair.
This tutorial will cover how to store data in shared preferences and retrieve it or call the data in what ever activity that it is needed.

Step 1: Getting Started

To begin this tutorial, you need to setup up your Android studio by downloading from the link provided above and installing, or you can just run the IDE if you have it on your computer. After installation, create a new Android studio project. In this tutorial, we will be needing two Activities. One to input and save the data to shared preferences and the other to retrieve the data stored, so you can go ahead and create two activities.

Step 2: Layout Design

After setting up the project, we will have to set up views to be able to input data in the Main Activity, and also to receive data in the second activity. Below is the code and the screen shot of the activities used in the tutorial. Feel free to design something different.

Main Activity XML

Screenshot_20180603-162133.png

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
    android:fitsSystemWindows="true"
    tools:context="com.shareqube.goldwyn.sharedpreferences.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <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/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="60dp"
        android:orientation="vertical"
        android:padding="10dp">

        <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:text="@string/username" />

            <EditText
                android:id="@+id/save_username"
                android:layout_width="130dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp" />
        </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:text="@string/password" />

            <EditText
                android:id="@+id/save_password"
                android:layout_width="130dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:inputType="textPassword" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <Button
                android:id="@+id/save"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="save"
                android:text="@string/save" />

            <Button
                android:id="@+id/next"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="next"
                android:text="@string/next" />

        </LinearLayout>
    </LinearLayout>

</android.support.design.widget.CoordinatorLayout>  
LoadDataActivity XML

Screenshot_20180603-162146.png

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
    android:fitsSystemWindows="true"
    tools:context="com.shareqube.goldwyn.sharedpreferences.LoadData">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <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/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <LinearLayout
        android:padding="10dp"
        android:layout_marginTop="60dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">


            <Button
                android:layout_width="wrap_content"
                android:text="@string/load"
                android:onClick="load"
                android:layout_height="wrap_content" />

            <Button
                android:onClick="previous"
                android:text="@string/previous"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:text="@string/username"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <EditText
                android:id="@+id/load_username"
                android:layout_marginLeft="20dp"
                android:layout_width="130dp"
                android:layout_height="wrap_content" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:text="@string/password"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <EditText
                android:id="@+id/load_password"
                android:layout_marginLeft="20dp"
                android:layout_width="130dp"
                android:layout_height="wrap_content" />

        </LinearLayout>
    </LinearLayout>

</android.support.design.widget.CoordinatorLayout>

Step 4: To Store data

  • Get a reference to the SharedPreferences object
    • For a single file, call getPreferences(int mode)
    • For several files, call getSharedPreferences(String name, int mode)
  • Call the editor
  • Use the editor to add data with a key
  • Commit editor changes
``` 
        public class MainActivity extends AppCompatActivity {
EditText username,password;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    username = (EditText) findViewById(R.id.save_username);
    password = (EditText) findViewById(R.id.save_password);
}

public void save(View view){
    SharedPreferences sharedPref = getSharedPreferences("MyData",MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putString("name",username.getText().toString());
    editor.putString("password",password.getText().toString());
    editor.commit();

    Toast.makeText(this, "Your details has been save" , Toast.LENGTH_SHORT).show();
}

public void next(View view){
    Toast.makeText(this, "Next", Toast.LENGTH_SHORT).show();
    Intent intent = new Intent(this,LoadData.class);
    startActivity(intent);
} ```

Step 5: Retrieving data stored in any activity in the app

  • Get a reference to the SharedPreferences object
  • Use the key provided earlier to get data
  • Supply default values if the data is not found
    public class LoadData extends AppCompatActivity {
    public static final String DEFAULT = "N/A";
    EditText username, password1;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_load_data);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    
        username = (EditText) findViewById(R.id.load_username);
        password1 = (EditText) findViewById(R.id.load_password);
    
    }
    
    public void load(View view) {
    
        SharedPreferences sharedPreferences = getSharedPreferences("MyData", MODE_PRIVATE);
        String name = sharedPreferences.getString("name",DEFAULT);
        String password =  sharedPreferences.getString("password",DEFAULT);
    
        if (name.equals(DEFAULT) || password.equals(DEFAULT)){
    
            Toast.makeText(this,"loading details not found",Toast.LENGTH_SHORT).show();
        }
        else {
            username.setText(name);
            password1.setText(password);
    
            Toast.makeText(this,"loading details successfully",Toast.LENGTH_SHORT).show();
        }
    }
    
    public void previous(View view) {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    }
    
    
    

Proof of Work Done

The full code of the tutorial is found in the githup link below.
https://github.com/Godwyyn/AndroidSharedPreference

Sort:  

Thank you for your contribution.

  • Try to come up with new and more innovative/useful ways to utilize Android using Shared Preferences.
  • There is a lot of information on this subject. For example, I found something similar on this site.

Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Coin Marketplace

STEEM 0.27
TRX 0.11
JST 0.031
BTC 67863.38
ETH 3708.58
USDT 1.00
SBD 3.65