Articles → Android → Preferences In Android

Preferences In Android






What Are Preferences?





How To Create And Read Preferences?




package com.example.preferencedemo;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
  private SharedPreferences settings;

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

    if (settings == null) {
      settings = getSharedPreferences("MY_PREFERENCE", MODE_PRIVATE);
    }

    //*****************************************************************
    //  CREATE DATA IN PREFERENCE
    //*****************************************************************
    SharedPreferences.Editor preference_editor = settings.edit();

    preference_editor.putString("USER_NAME", "karan");
    preference_editor.putString("PASSWORD", "karan");

    preference_editor.commit();
    //*****************************************************************
    //  DISPLAY VALUE IN PREFERENCES
    //*****************************************************************
    Log.v("PREFERENCE_USER_NAME", settings.getString("USER_NAME", ""));
    Log.v("PREFERENCE_PASSWORD", settings.getString("PASSWORD", ""));

  }
}




  1. Data is displayed in LogCat window
  2. Picture showing the data in the logcat window
    Click to Enlarge

  3. Data is created in preference
  4. Picture showing the XML created inside in the My_Preference.xml file
    Click to Enlarge



How To Access Preference?




  1. Go to View → Tools Windows → Device File Explorer
  2. Picture showing the accessing the Device File Explorer using the View → Tools Windows menu
    Click to Enlarge

  3. In the Device File Explorer windows, go to data/data/your_package_name/shared_prefs
  4. Picture showing the Preferences file inside the device file explorer
    Click to Enlarge





Posted By  -  Karan Gupta
 
Posted On  -  Wednesday, September 4, 2019

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250