Thursday, 3 September 2015

Android Preferences Activity Example

Applications often include settings that allow users to modify app features and behaviors. For example, some apps allow users to specify whether notifications are enabled or specify how often the application syncs data with the cloud.
If you want to provide settings for your app, you should use Android'sPreference APIs to build an interface that's consistent with the user experience in other Android apps (including the system settings). Here I am going to  explain how to build your app settings using Preference APIs.

Step.1)MainActivity.java
package com.preference;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class MainActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.preferences);
}
}
Step.2)preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" ><EditTextPreference
        android:key="username"
        android:summary="Please provide your username"
        android:title="Your Name" >
    </EditTextPreference>
    <CheckBoxPreference
        android:defaultValue="false"
        android:key="Location"
        android:summary="let apps that have asked your permission use your                                            location permission."
        android:title="Access to my Location" />
     <ListPreference
        android:defaultValue="1"
        android:entries="@array/simArray"
        android:entryValues="@array/simValues"
        android:key="sim"
        android:summary="Select the SIM"
        android:title="Select SIM" />
  </PreferenceScreen>

Step.3)array.xml

  <?xml version="1.0" encoding="utf-8"?>
  <resources>
  <string-array name="simArray">
<item>SIM1</item>
<item>SIM2</item>
</string-array>
 <string-array name="simValues">
    <item>1</item>
    <item>2</item>
   
 </string-array>
 </resources>


To read the preferences values in any part of your application, you can use the code that is shown below:
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String UserName = SP.getString("username", "Dhina");
boolean LocationSP.getBoolean("Location",false);
String SIM= SP.getString("sim","1");



Happy Coding :)