RESOLVED! Shared Preference Context Error

During android development, especially for a beginner like me the creepiest thing which I felt was Handling Contexts. Shared preferences is really a cool thing if we want to save some handy information by the user on a device even if an app is killed. BUT context exceptions are everywhere.

So here we will not go deep into context understanding or preferences documentations. We will only discuss the best approach to use Shared Preference in application from anywhere inside your app. Using this method you can SET or GET preference literally from anywhere

– Mainactivity
– Non-Mainactivity
– Services
– Broadcasts

etc etc.

Let’s Begin with code.

Step 1) Create a new app with MainActivity.

Step 2) In MainActivity add below line of code to above OnCreate method.

public static SharedPreferences preferences;

 

Step 3) Get instance of getSharedPreferences method providing name and MODE.

preferences = getSharedPreferences( getPackageName() + "_preferences", MODE_PRIVATE);

 

Step 4) Now we will create a new Class “PreferenceHelper” having getter and setters for preferences.

Our “PreferenceHelper” Class will look like this

 

Step 5) Let’s create an Input and a Button to save a value in preferences.

After some drag-drop in activity-layout added a text input and a button which will look like this.

 

You can try to save Entered Name. It will Show up on top and will reappear even if you kill and reopen the app.

Find source code in Google Drive here

Complete Files will Look like:

MainActivity.java

package demo.freakysharedprefrence.com.freakysharedpreferencedemo;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


    public static SharedPreferences preferences;
    private TextView showText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        preferences = getSharedPreferences( getPackageName() + "_preferences", MODE_PRIVATE);
        showSavedname();

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

    //Showing Saved Name on Application Start.
    public void showSavedname(){
        showText = (TextView) findViewById(R.id.showText);
        showText.setText(PreferenceHelper.getName());
    }


    public void onButtonClicked(View view) {
        TextView saveNameView = findViewById(R.id.saveText);
        if (!saveNameView.getText().toString().trim().equals("")) {
            PreferenceHelper.setName(saveNameView.getText().toString());
            showSavedname();
            Toast.makeText(this, "Saved successfully.!", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "Not Saved.!", Toast.LENGTH_SHORT).show();
        }
    }




    @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) {
        // 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);
    }
}

 

 

PreferenceHelper.java

package demo.freakysharedprefrence.com.freakysharedpreferencedemo;

public class PreferenceHelper {

    final public static String KEY_DEMO_NAME = "Demo Name";

    public static void setName(String value) {
        MainActivity.preferences.edit().putString(KEY_DEMO_NAME, value ).commit();
    }
    public static String getName() {
        return MainActivity.preferences.getString(KEY_DEMO_NAME,"");
    }


}

 

 

activity_main.xml

<?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"
    tools:context=".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>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

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

 

 

content_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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main">

    <EditText
        android:id="@+id/saveText"
        android:layout_width="247dp"
        android:layout_height="50dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="72dp"
        android:ems="10"
        android:hint="Enter Name"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/showText" />

    <Button
        android:id="@+id/saveButton"
        android:layout_width="160dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="100dp"
        android:onClick="onButtonClicked"
        android:text="Save Name"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/saveText" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="92dp"
        android:text="Freaky Jolly Preference Demo"
        android:textColor="#03cba6"
        android:textSize="18sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.503"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/saveButton" />

    <TextView
        android:id="@+id/showText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="16dp"
        android:textSize="36sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

 

 

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="demo.freakysharedprefrence.com.freakysharedpreferencedemo">

    <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=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

 

 

 

 

 

 

 

1 thought on “RESOLVED! Shared Preference Context Error”

  1. This is pretty ugly my dude, you depend on a static variable that you init on MainActivity, what happens if your code calls this PreferenceHelper after an async operation and preferences static variable has been cleared?? With all my respect this is a bad approach.

Leave a Comment

Your email address will not be published. Required fields are marked *