Android Sharedpreferences (Android Store user status information method)

Source: Internet
Author: User


In the Andorid many application development all need to record the user login information, uses the static variable handset shutdown User State Purge, the solution is uses the sharedpreferences to store the Android user information.

Introduction of Sharedpreferences basic knowledge

Two ways to get sharedpreferences:
1 invoke the Getsharedpreferences () method of the context object
2 Invoke the Getpreferences () method of the Activity object
The difference between two ways:
The Sharedpreferences object obtained by invoking the Getsharedpreferences () method of the context object can be shared by other components under the same application.
The Sharedpreferences object obtained by invoking the Getpreferences () method of the activity object can only be used in that activity.

Four modes of operation for Sharedpreferences:
Context.mode_private
Context.mode_append
Context.mode_world_readable
Context.mode_world_writeable

Context.mode_private: For the default mode of operation, the file is private data and can only be accessed by the application itself, in which case the written content overwrites the contents of the original file.
Context.mode_append: Mode checks whether the file exists, appends to the file, or creates a new file.
Context.mode_world_readable and context.mode_world_writeable are used to control whether other applications have permission to read and write to the file.
Mode_world_readable: Indicates that the current file can be read by another application.
Mode_world_writeable: Indicates that the current file can be written by another application.

Second, the data save to Sharedpreferences:

Log logon information method after user login success
Sharedpreferences preferences=getsharedpreferences ("user", context.mode_private);
Editor Editor=preferences.edit ();
String username= "user name";
Editor.putstring ("UserName", userName);
Editor.commit ();

Iii. obtaining data from Sharedpreferences:

Sharedpreferences preferences=getsharedpreferences ("user", context.mode_private);
String name=preferences.getstring ("name", null);

Four, clear sharedpreferences value

Sharedpreferences preferences=getsharedpreferences ("user", context.mode_private);
Preferences.edit (). Clear (). commit ();
The user clicks the user program to exit after clears the sharedpreferences login information


Five, sharedpreferences to save user parameters and read


Software Requirements: User input name and age click the Save button to save the information in XML when you log in again, the information you enter appears in the text box

Activity file

[Java] View plain copy
Package com.example.shareperences;

Import Java.util.Map;

Import android.app.Activity;
Import Android.os.Bundle;
Import Android.view.Menu;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.EditText;
Import Android.widget.Toast;

Import Com.example.service.PrefercesService;

public class Mainactivity extends activity {
Private button button;
Private EditText name,age;
Private Prefercesservice Prefercesservice;
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
button= (Button) This.findviewbyid (R.id.button);
Name= (EditText) This.findviewbyid (r.id.name);
Age= (EditText) This.findviewbyid (r.id.age);
Prefercesservice=new Prefercesservice (this);
Map<string,string> params=prefercesservice.getpreferences ();
Name.settext (Params.get ("name"));
Age.settext (Params.get ("Age"));
}

@Override
public boolean Oncreateoptionsmenu (Menu menu) {
Inflate the menu; This adds items to the action bar if it is present.
Getmenuinflater (). Inflate (R.menu.main, menu);
return true;
}
public void Save (View v) {
/*
* If you want to get sharedpreferences objects in an activity, you can use the method
* This.getpreferences (mode) there is only one parameter file storage type, at which time the file name defaults to
* The name of the current activity does not include the package name
*/
String Namestring=name.gettext (). toString ();
String Agestring=age.gettext (). toString ();
Prefercesservice.save (Namestring,integer.parseint (agestring));
Toast.maketext (Mainactivity.this, R.string.success, Toast.length_long). Show ();
}

}

[Java] View plain copy
Package com.example.service;

Import Java.util.HashMap;
Import Java.util.Map;

Import Android.content.Context;
Import android.content.SharedPreferences;
Import Android.content.SharedPreferences.Editor;

public class Prefercesservice {
private context;
Public Prefercesservice {
Super ();
This.context = context;
}
/**
* Save Parameters
* @param name Name
* @param age
*/
public void Save (String name, int age) {
The first argument specifies that the name does not need to write the suffix name the operation mode of the second parameter file
Sharedpreferences preferences=context.getsharedpreferences ("Itcast", context.mode_private);
Fetch to Editor
Editor Editor=preferences.edit ();
Editor.putstring ("name", name);
Editor.putint (' age ', age);
Submit the data to the file
Editor.commit ();
}
/**
* Get each configuration parameter
* @return
*/
Public map<string,string> getpreferences () {
Sharedpreferences pre=context.getsharedpreferences ("Itcast", context.mode_private);
If the resulting name has no value, it is set to an empty pre.getstring ("name", "");
Map<string,string> params=new hashmap<string,string> ();
Params.put ("Name", Pre.getstring ("name", ""));
Params.put ("Age", String.valueof (Pre.getint ("age", 0));

return params;


}
}

Layout file Note The button should be set this way

[HTML] View plain copy
<Button  
         android: Layout_width= "Match_parent"  
         android:layout_height= " Wrap_content " 
         android:id=" @+id/button " 
         android:text= "@string/save"  
          android:onclick= "Save"  
        />  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.