Methods of sharing data between applications (i)---sharepreferce

Source: Internet
Author: User
Tags deprecated

The Sharedpreferences class, which is a lightweight storage class, is especially suitable for saving software configuration parameters.

Sharedpreferences Save the data, behind it is the XML file to store data, files stored in the/data/data/<package name>/shared_prefs directory:

First, the analysis of several methods:

1, getsharedpreferences (Name,mode)

The first parameter of the method specifies the name of the file, the name does not have a suffix, and the suffix is automatically added by Android;

The second parameter of the method specifies the mode of operation of the file, with a total of six modes of operation.

Six modes of operation are:

1). Mode_append: Append mode storage

2). Mode_private: Private mode storage, other apps cannot access

3). mode_enable_write_ahead_logging Database Open default write-ahead logging enabled

4). Mode_multi_process: Multiple inter-process sharing, but no longer used after 2.3

5). Mode_world_readable: Indicates that the current file can be read by another app (deprecated)

6). Mode_world_writeable: Indicates that the current file can be written by another application (deprecated)

Sharedpreferences share = getsharedpreferences ("LSF", mode_private);   

2. Edit () method to get editor object

Editor storage objects are stored with Key-value key value pairs

Submitting data through the commit () method

Sharedpreferences share = Getsharedpreferences ("Jackie", mode_world_readable);   // other applications can get Sharedpreferences.editor edit ="" +987654321); Edit.putboolean ("Pass_state",  true

Ways to get data from other apps:

Otherappscontext = Createpackagecontext ("Com.jackie.contextprovider"= Otherappscontext.getsharedpreferences ("Jackie", context.mode_world_readable); String Password= sharedpreferences.getstring ("Password", "" "); Boolean false);   // The second parameter is the default value, and if the key does not exist in preference, the default value mtextview.settext ("Password:" +password+ "| | | | | | | | |" is returned. + "Pass_state:" +pass_state);

If you want to delete a file produced by sharedpreferences, you can do this by using the following methods:

New File ("/data/data/" +getpackagename (). toString () + "/shared_prefs", "Activity.xml"); if (File.exists ()) {    file.delete ();     Toast.maketext (testactivity. This, "delete succeeded", Toast.length_long). Show ();

Second, the application example:

A button is set in an app that can be set to share or not share its sharedpreferences generated files by pressing the trigger.

Another app gets the data from the previous app by pressing the button to trigger it.

1, the application of shared data files:

 PackageCom.jackie.contextprovider;Importandroid.app.Activity;Importandroid.content.SharedPreferences;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.widget.Button; Public classMainactivityextendsActivity { Public Static FinalString new_lifefrom_detected = "Com.jackie.contextprovider";  Public Static FinalString TAG = "Testprovider"; PrivateButton Snedbutton; Private BooleanIsshare =true; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Snedbutton=(Button) Findviewbyid (r.id.send_message); }     Public voidSendMessage (View v) {if(isshare) {sharedpreferences share= Getsharedpreferences ("Jackie", mode_world_readable); Sharedpreferences.editor Edit=Share.edit (); Edit.putstring ("Password","" +987654321); Edit.putboolean ("Pass_state",true);             Edit.commit (); Isshare=false;        Snedbutton.settext (R.string.no_send); }Else{sharedpreferences Share= Getsharedpreferences ("Jackie", mode_private); Sharedpreferences.editor Edit=Share.edit ();            Edit.clear ();             Edit.commit (); Isshare=true;                   Snedbutton.settext (R.string.send); }           }}

Layout configuration file

<Relativelayoutxmlns: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"Tools:context= "${relativepackage}.${activityclass}" >    <ButtonAndroid:id= "@+id/send_message"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:onclick= "SendMessage"Android:text= "@string/send"        /></Relativelayout>

2, read the application of shared data

 PackageCom.jackie.contextuser;Importandroid.app.Activity;ImportAndroid.content.Context;Importandroid.content.SharedPreferences;Importandroid.content.pm.PackageManager.NameNotFoundException;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportAndroid.widget.TextView; Public classMainactivityextendsActivity {Button Mbutton;    TextView Mtextview;    Context Otherappscontext; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Mbutton=(Button) Findviewbyid (r.id.get_message); Mtextview=(TextView) Findviewbyid (r.id.write_message); Otherappscontext=NULL; } @Overrideprotected voidOnresume () {Super. Onresume (); Otherappscontext=NULL; } @Overrideprotected voidOnStop () {Super. OnStop (); Otherappscontext=NULL; }     Public voidGetMessage (View v)throwsnamenotfoundexception{Otherappscontext= Createpackagecontext ("Com.tcl.contextprovider", context.context_ignore_security); Sharedpreferences sharedpreferences= Otherappscontext.getsharedpreferences ("Jackie", context.mode_world_readable); String Password= sharedpreferences.getstring ("Password", "" "); BooleanPass_state= Sharedpreferences.getboolean ("Pass_state",false); Mtextview.settext ("Password:" +password + "| | | | | | | |" + "Pass_state:" +pass_state); }}

Layout configuration file:

<Relativelayoutxmlns: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"Tools:context= "${relativepackage}.${activityclass}" >    <ButtonAndroid:id= "@+id/get_message"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:onclick= "GetMessage"Android:text= "@string/get"/>    <TextViewAndroid:id= "@+id/write_message"Android:layout_below= "@id/get_message"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"/></Relativelayout>

--------------------------------------------------------------------------------------------just started to learn, blogging just hope to record their own growth trajectory, welcome to the guidance.

Methods of sharing data between applications (i)---sharepreferce

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.