Simple SharedPreferences by using a third-party library in Android

   SharedPreferences is one of the way to persist data in Android (2 remaining options is SQLite database and Files). For the simple application, this is the common solution. The official document reminder us:
The SharedPreferences APIs are only for reading and writing key-value pairs and you should not confuse them with the Preference APIs, which help you build a user interface for your app settings (although they use SharedPreferences as their implementation to save the app settings). For information about using the Preference APIs, see the Settings guide.
    I already have a post about this API in Android Basic Training Course for the beginners. Because it's applicability is very popular and implementing it by the official way is so much complicated, I would like to provide a third-party library called Universal SharedPreferences that allows you to use SharedPreferences in an easy way.

Import and Usage

    After start a new Android Studio project, add this code to your project level build.gradle:
allprojects {
    repositories {
        maven { url "https://jitpack.io" }
    }
}
    Open your application level build.gradle and add this library dependency:
dependencies {
    compile 'com.github.zookey:universalpreferences:0.0.4'
}
    First you do need to initalize this libarary inside onCreate() of the Application class of your project:
MyApplication.java
package info.devexchanges.universalsharedpreferences;

import android.app.Application;

import com.zookey.universalpreferences.UniversalPreferences;


public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        UniversalPreferences.initialize(this);
    }
}

    Now you can use UniversalPreferences in any class of your project. This library is “universal” at accepting object types, so there is only one method to store and only one method to retrieve values.
    To store and retrieve a strings, you can use:
UniversalPreferences.getInstance().put("string", "some value");
String stringValue = UniversalPreference.getInstance().get("string", "");
    To store and retrieve boolean value:
UniversalPreferences.getInstance().put("bool", true);
boolean bool = UniversalPreference.getInstance().get("bool", false);
    To store and retrieve integer value:
UniversalPreferences.getInstance().put("int", 30);
int integerValue = UniversalPreference.getInstance().get("int", 0);
    To store and retrieve float value:
UniversalPreferences.getInstance().put("float", 3.0f);
float valueFloat = UniversalPreference.getInstance().get("float", 0.0f);
    To store and retrieve Set value:
Set<String> set = new HashSet<String>();
set.add("test 1");
set.add("test 2");
UniversalPreferences.getInstance().put("set", set);
Set<String> savedSet = UniversalPreference.getInstance().get("set", new HashSet<String>);
    Remove a value or clear all data available in UniversalPreferences by these methods:
UniversalPreferences.getInstance().remove("key"); //remove value with it's corresponding key
UniversalPreferences.getInstance().clear(); //clear all data on SharedPreferences

Sample project

    Now, I will make a sample project about using UniversalSharedPreferences to manage user session. After users logged in, I will save data (user name/password) and redirect them to main activity. They can only go back to the login screen by clicking logout button.
    Firstly, make sure that you've already had MyApplication.java file like above!
    The login activity code, which show you how to store data in UniversalSharedPreferences:
LoginActivity.java
package info.devexchanges.universalsharedpreferences;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.zookey.universalpreferences.UniversalPreferences;

public class LoginActivity extends AppCompatActivity {

    private TextInputLayout userName;
    private TextInputLayout password;
    public final static String KEY_USER_NAME = "username";
    public final static String KEY_PASSWORD = "password";
    public final static String IS_LOGIN = "is_login";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //checking user is logged in?
        //if logged in, redirect user to main activity
        boolean isLoggedIn = UniversalPreferences.getInstance().get(IS_LOGIN, false);
        if (isLoggedIn) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();
        } else {
            setContentView(R.layout.activity_login);

            userName = (TextInputLayout) findViewById(R.id.username_field);
            password = (TextInputLayout) findViewById(R.id.password_field);
            View btnLogin = findViewById(R.id.btn_login);

            btnLogin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    userName.setError(null);
                    userName.setError(null);
                    if (!hasText(userName)) {
                        userName.setError("Please input your user name");
                    } else if (!hasText(password)) {
                        password.setError("Please input your user password");
                    } else {
                        //go to the main screen after store data in Universal SharedPreferences
                        UniversalPreferences.getInstance().put(KEY_USER_NAME, getText(userName));
                        UniversalPreferences.getInstance().put(KEY_PASSWORD, getText(password));
                        UniversalPreferences.getInstance().put(IS_LOGIN, true);

                        //Go to Main Activity
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                    }
                }
            });
        }
    }

    private boolean hasText(TextInputLayout inputLayout) {
        return !inputLayout.getEditText().getText().toString().trim().equals("");
    }

    private String getText(TextInputLayout inputLayout) {
        return inputLayout.getEditText().getText().toString().trim();
    }
}
    And this is main activity code, you will retrieve/clear data here:
MainActivity.java
package info.devexchanges.universalsharedpreferences;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

import com.zookey.universalpreferences.UniversalPreferences;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        TextView userName = (TextView)findViewById(R.id.user_name_login);
        TextView password = (TextView)findViewById(R.id.password);
        View btnLogOut = findViewById(R.id.btn_logout);

        //get logged in user name and password in Universal SharedPreferences
        userName.setText(String.format("User name: %s", UniversalPreferences.getInstance().get(LoginActivity.KEY_USER_NAME, "")));
        password.setText(String.format("Password: %s", UniversalPreferences.getInstance().get(LoginActivity.KEY_PASSWORD, "")));

        //Logging out
        btnLogOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                UniversalPreferences.getInstance().clear(); //clear all data when user logout
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }
}
    Never forget to use your custom Application class in AndroidManifest.xml:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="info.devexchanges.universalsharedpreferences">

    <application
        android:allowBackup="true"
        android:name=".MyApplication"
        android:icon="@mipmap/ic_launcher"
        android:label="Login Screen"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity"
            android:label="Main Screen"/>
    </application>

</manifest>
    Running application, you'll have this output (login screen):

After login with user name and password, you'll be redirected to main screen:

Conclusions

    Through this post, I have presented a third-party library which help you using SharedPreferences in an easy way, simplifies data storage tasks. For the project code, you can get on @Github by clicking the button below!
    References:

Share


Previous post
« Prev Post
Next post
Next Post »