Headertab

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Sunday, 3 January 2016

SharePrefrences in android

Hello Friends
Today we are study How to better use is SharePrefrences.
SharePrefrences using two type (1) By java code (2) By using xml
 then today we are learn about xml prefrences also known as Prefrencesscreen. So lets start...

Step 1 -->
Create a xml folder in a res folder and then create a xml file a name of settings.xml like...


and write below code

PreferenceCategory
    android:title="@string/pref_user_profile" >

    <EditTextPreference
        android:title="@string/pref_user_name"
        android:summary="@string/pref_user_name_summary"
        android:key="prefUsername"/>

</PreferenceCategory>

<PreferenceCategory android:title="@string/pref_update_setting" >

    <CheckBoxPreference
        android:defaultValue="false"
        android:key="prefSendReport"
        android:summary="@string/pref_send_report_summary"
        android:title="@string/pref_send_report" >

    </CheckBoxPreference>

    <ListPreference
        android:key="prefSyncFrequency"
        android:entries="@array/syncFrequency"
        android:summary="@string/pref_sync_frequency_summary"
        android:entryValues="@array/syncFrequencyValues"
        android:title="@string/pref_sync_frequency" />

</PreferenceCategory>

Step 2 --> Now create a array resource file in values folder and write this code.


<string-array name="syncFrequency">
    <item name="1">Once a day</item>
    <item name="7">Once a week</item>
    <item name="3">Once a year</item>
    <item name="0">Never (Update maually)</item>
</string-array>
<string-array name="syncFrequencyValues">
    <item name="1">1</item>
    <item name="7">7</item>
    <item name="30">30</item>
    <item name="0">0</item>

</string-array>



Step 3 --> Write a below code in string resource file.



<string name="menu_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>

<string name="pref_send_report">Send crash reports</string>
<string name="pref_send_report_summary">Helps to fix bugs</string>
<string name="pref_sync_frequency">Sync frequency</string>
<string name="pref_sync_frequency_summary">Set the sync frequency</string>
<string name="pref_user_name">Set username</string>
<string name="pref_user_name_summary">Set your username</string>

<string name="pref_user_profile">User Profile</string>
<string name="pref_update_setting">Update Settings</string>


Step 4 --> Now you create a menu.xml  file.

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/menu_settings"
        ic_menu_preferences=""
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="@string/menu_settings"
        android:icon="@android:drawable/ic_menu_preferences"/>

</menu>


Step 5 --> Now you create a SettingActivity.java  file.

import android.os.Bundle;
import android.preference.PreferenceActivity;


public class UserSettingActivity extends PreferenceActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.settings);
    }
}

Step 6 --> Now come with mainactivity.java and actvitymain.xml


public class MainActivity extends AppCompatActivity {
    private static final int RESULT_SETTINGS = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        showUserSettings();


    }

    @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) {
        switch (item.getItemId()) {

            case R.id.menu_settings:
                Intent i = new Intent(this, SettingActivity.class);
                startActivityForResult(i, RESULT_SETTINGS);
                break;

        }

        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case RESULT_SETTINGS:
                showUserSettings();
                break;

        }
    }

    private void showUserSettings() {
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        StringBuilder builder = new StringBuilder();

        builder.append("\n Username: "+ sharedPrefs.getString("prefUsername", "NULL"));

        builder.append("\n Send report:"+ sharedPrefs.getBoolean("prefSendReport", false));

        builder.append("\n Sync Frequency: "+ sharedPrefs.getString("prefSyncFrequency", "NULL"));
        TextView settingsTextView = (TextView) findViewById(R.id.textUserSettings);
        settingsTextView.setText(builder.toString());

    }

}

actvitymain.xml

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <TextView
            android:id="@+id/textUserSettings"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            tools:context=".MainActivity" />

</LinearLayout>
</RelativeLayout>

add SettingActivity class in androidmanifest.xml

<activity android:name=".SettingActivity"/>

I hope this article help you..

Now see below final view ..