How to Use Android Shared Preferences Database

Hello viewer, You can now have our Tutorial Lessons in your android mobile device and read it offline.
Download kotlin Programming APP on PlayStore
Download Website SEO Lessons APP on PlayStore

The class android.content.SharedPreferences allows developers to save the application settings to a file, with the ability to share them in the same application or between all applications. The file where these applications are saved is listed in the installation folder of the app, which is in the path

/ data / data / <package_applicazione> /

Android provides a framework for managing data persistence and presentation interface to edit them.

Topic: HOW TO USE ANDROID SHARED PREFERENCES

Shared Preferences Access Mode

There are primarily four access modes:

  • Context.MODE_PRIVATE : preferences can only be read from the current (default)
  • Context.MODE_WORLD_READABLE : All applications will be able to read the preferences (read-only permission)
  • Context.MODE_WORLD_WRITEABLE : All applications will have read and write permissions
  • Context.MODE_APPEND : If the file already exists, the preferences will be written at the end of the file rather than delete old (never used in my life)

The information will be associated with a name, in our case we will use a variable for convenience.

private static String MYIMP = "preferenceDefault";

 

Topic: HOW TO USE ANDROID SHARED PREFERENCES

Access and modification

To instantiate an object of type  SharedPreferences it is sufficient to use the method  getSharedPreferences (String name, int mode)  to which you have to pass an identifier that represents the name of preference, and then spend our variable MYIMP , and the access mode (mode) as seen previously.

SharedPreferences prefs = getSharedPreferences(MYIMP, Context.MODE_PRIVATE);

To manage the update of Android it provides SharedPreferences.Editor that manages saving information. To save the data is provided for the execution of a commit () in order to make the changes take effect.

SharedPreferences.Editor editor = prefs.edit();
editor.putString(PREF_TEXT, "Text to be saved");
editor.commit();

On the other hand in order to draw out the information stored in the preference you can simply read the data identified with the same key used previously, ie PREF_TEXT . If the preference is empty, ie if no item to it was saved, you can set a default value, in this case No Preferences!

String textData = prefs.getString(PREF_TEXT, "No Preferences!");

Topic: HOW TO USE ANDROID SHARED PREFERENCES

Practical Case

To complete the tutorial, we create a new project, you can simply do it all in an Activity, but I recommend to use more than one to see how in fact the work preferences. Let’s create our layout consists of a ‘ EditText , a Button and a TextView .

<LinearLayout xmlns:android="//schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <EditText
        android:id="@+id/txtPreference"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >
 
        <requestFocus />
    </EditText>
 
    <Button
        android:id="@+id/btnSave"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="Salva" />
 
    <TextView
        android:id="@+id/textviewid"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_gravity="center"
        android:text="TextView" />
 
</LinearLayout>

Let’s see the java code, just commented as has already been explained everything before.

package com.coding180.testsharedpreferences;
 
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
 
public class MainActivity extends Activity implements OnClickListener{
    private EditText txtPreference;
    private TextView textview;
    private Button btn;
    private final static String MYIMP = "preferenceDefault";
    private final static String PREF_TEXT = "prefText";
    private SharedPreferences prefs;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initialize();
    }
 
    private void initialize() {
        txtPreference = (EditText) findViewById (R.id.txtPreference);
        textview= (TextView) findViewById (R.id.textviewid);
        btn = (Button) findViewById (R.id.btnSave);
         
        btn.setOnClickListener(this);
         
 
        //the value of the preference
        prefs = getSharedPreferences(MYIMP, Context.MODE_PRIVATE);
        textview.setText(prefs.getString(PREF_TEXT, "No Preferences!"));
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
 
    @Override
    public void onClick(View v) {
        switch (v.getId()){
        case R.id.btnSave:
            //Save the value of the preference if we wrote something in EditText
            if (txtPreference.length() > 0){
                SharedPreferences.Editor editor = prefs.edit();
                editor.putString(PREF_TEXT, txtPreference.getText().toString());
                editor.commit();
            }
            // Update the value of TextView
            String textData = prefs.getString(PREF_TEXT, "No Preferences!");
            textview.setText(textData);
            break;
        }
         
    }
}

About The Author

Related posts

Leave a Reply