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", ""));
}
}
- Data is displayed in LogCat window
Click to Enlarge
- Data is created in preference
Click to Enlarge
How To Access Preference?
- Go to View → Tools Windows → Device File Explorer
Click to Enlarge
- In the Device File Explorer windows, go to data/data/your_package_name/shared_prefs
Click to Enlarge