Android shared preferences code...

       In this application we will use shared preferences to remember a piece of data entered by user,that can be used later during application reuse.The data can be a user settings,a piece of user name or password or anything.

      Here we simply save a piece of string and later we will use it after application restart.So here we take a xml layout containing a EditText widget and a button.When we will press the button the data in EditText is saved and when the application is restarted the data will still be there for using.So here is the xml code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
<EditText
    android:id="@+id/EditText01"
    android:layout_height="wrap_content"
    android:layout_width="200dip">
</EditText>
<Button 
    android:id="@+id/Button01"
    android:layout_height="wrap_content"
    android:layout_width="150dip"
    android:text="Save">
</Button>
</LinearLayout>
Now we write the java code for the application.Look carefully...
package com.android.pref;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MyPref extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final EditText et = (EditText)findViewById(R.id.EditText01);
        Button btn = (Button)findViewById(R.id.Button01);     

        SharedPreferences settings=getSharedPreferences("mypers",0);
        String val1=settings.getString("data1","");   

        et.setText(val1);   

        btn.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {               
                String a = et.getText().toString();           
                SharedPreferences settings=getSharedPreferences("mypers",0);
                SharedPreferences.Editor editor=settings.edit();
                editor.putString("data1", a);               
                editor.commit();                 
            }       
        });
    }
       Here when we press the 'save' button,the value in EditText will get saved in variable 'data1' that will be saved for future use in SharedPreferences variable 'mypers'.

No comments:

Post a Comment