Saturday, January 19, 2013

Android Working with Shared Preferences


Depending on the situation, different data storage methods are available to the
developer:
1) Shared Preferences for lightweight usage, such as saving application settings and the
user interface (UI) state
2) A built-in SQLite database for more complicated usage, such as saving application
records
3) The standard Java flat file storage methods: InputFileStream and
OutputFileStream


Shared Preferences
SharedPreferences is an interface that an application can use to quickly and efficiently
save data in name-values pairs, similar to a Bundle.The information is stored in an XML
file on the Android device. For example, if the application com.jitesh.datastorage
creates a shared preference, the Android system creates a new XML file under the
/data/data/com.jitesh.datastorage/shared_prefs directory. Shared preferences are
usually used for saving application settings such as user settings, theme, and other general
application properties. It can also save login information such as username, password,
auto-login flag and remember-user flag.The shared preferences data is accessible by every
component of the application which created it.

Creating and Retrieving Shared Preferences


The shared preferences for an activity can be accessed using the getPreferences()
method, which specifies the operating mode for the default preferences file. If instead
multiple preference files are needed, each can be specified using the
getSharedPreferences() method. If the shared preferences XML file exists in the data
directory, it is opened; otherwise, it is created.The operating mode provides control over
the different kinds of access permission to the preferences:
n MODE_PRIVATE—Only the calling application has access to the XML file.
n MODE_WORLD_READABLE—All applications can read the XML file.
n MODE_WORLD_WRITEABLE—All applications can write to the XML file.
After a SharedPreferences object is retrieved, an Editor object is needed to write the
name-value pairs to the XML file using the put() method. Currently, there are five
primitive types supported: int, long, float, String, and boolean.The following code
shows how to create and store shared preferences data:
SharedPreferences prefs = getSharedPreferences("myDataStorage",
MODE_PRIVATE);
Editor mEditor = prefs.edit();
mEditor.putString("username","datastorageuser1");
mEditor.putString("password","password1234");
mEditor.commit();
The following shows how to retrieve shared preferences data:
SharedPreferences prefs = getSharedPreferences("myDataStorage",
MODE_PRIVATE);
String username = prefs.getString("username", "");
String password = prefs.getString("password", "");


Using the Preferences Framework



Android provides a standardized framework for setting preferences across all applications.
The framework uses category preferences and screens to group related settings.
PreferenceCategory is used to declare a set of preferences into one category.
PreferenceScreen presents a group of preferences in a new screen.
This recipe uses the preferences defined in the XML file in Listing 9.1.A
PreferenceScreen is the root element with two EditTextPreference elements for
username and password. Other possible elements are CheckBoxPreference,
RingtonePreference, and DialogPreference.The Android system then generates a UI
to manipulate the preferences, as shown in Figure 9.1.These preferences are stored in
shared preferences, which means they can be retrieved by calling getPreferences().

res/xml/preferences.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference android:title="User Name"
android:key="username"
android:summary="Please provide user
name"></EditTextPreference>
<EditTextPreference android:title="Password"
android:password="true"
android:key="password"
android:summary="Please enter your
password"></EditTextPreference>
</PreferenceScreen>

src/com/jitesh/datastorage/MyPreferences.java


package com.jitesh.datastorage;

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

public class MyPreferences extends PreferenceActivity {

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


src/com/jitesh/datastorage/DataStorage.java

package com.jitesh.datastorage;


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

public class DataStorage extends Activity {
 SharedPreferences myprefs;
 EditText userET, passwordET;
 Button loginBT;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myprefs = PreferenceManager.getDefaultSharedPreferences(this);
        final String username = myprefs.getString("username", null);
        final String password = myprefs.getString("password", null);
        if (username != null && password != null){
            setContentView(R.layout.main);
            userET = (EditText)findViewById(R.id.userText);
            passwordET = (EditText)findViewById(R.id.passwordText);
            loginBT = (Button)findViewById(R.id.loginButton);
            loginBT.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    try {
                        if(username.equals(userET.getText().toString())&&password.equals(passwordET.getText().toString())){
                        Toast.makeText(DataStorage.this, "login passed!!", Toast.LENGTH_SHORT).show();
                       
                        }
                        else{
                        Toast.makeText(DataStorage.this, "login failed!!", Toast.LENGTH_SHORT).show();
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            });
            
        }
        else{
        Intent i = new Intent(this, MyPreferences.class);
        startActivity(i);
        }
    }
}


res/layout/main.xml

<?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="username"
    />
    <EditText
    android:id="@+id/userText"
            android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:singleLine="true"
    />
    
    <TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="password"
    />
    <EditText
        android:id="@+id/passwordText"
            android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:password="true"
   android:singleLine="true"
    />
    <Button
   android:id="@+id/loginButton"
            android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="login"
    android:textSize="20dp"
    />
</LinearLayout>











3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. sir, I need one register activity. it only displayed when app installed first time. don't appear the register activity whenever open the app..plz help me sir...

    ReplyDelete