Data transfer between Android components

Source: Internet
Author: User
Tags sqlite database

Components we have, then we are missing a channel for passing information between components. It is a kingly way to use intent as a carrier. What's more, you can use the file system to do data sharing. You can also use application to set global data and use components to control data.

First, intent data transmission
  1. So the first is a simple jump. We can use this container of bundles to store the data we want to pass.
    Intent Intent = new Intent ();   Intent.setclass (Activity1.this, activity2.class);   Description start and target   bundle bundle = new bundle ();                           Create the Bundle object   bundle.putstring ("tag", "Activity1 data Sent");     Loading Data   Intent.putextras (bundle);                                Plug the bundle into the intent   startactivity (intent);                                     

    Another accepted data

    Intent Intent = This.getintent ();        Gets the existing intent object   Bundle bundle = Intent.getextras ();    Gets the bundle object inside the intent   string = bundle.getstring ("tag");    
  2. So the next step is how to accept the processing results returned from the target activity. There are two ways, one is to accept the processing result in the Onrestart method, the method realizes and Activity2 accepts the data processing from the Activity1. Another way is to use the answer mode switch. Here, mainly under the second way. Response mode switching and normal switching is different, the normal is to have to go back, the answer is accumulate. The code implementation is not the same:
    switch from Activity1 to Activity2:startactivityforresult (intent,0), return from Activity2 to Activity1:setresult (RESULT_OK, intent). Accept return Result: protected void Onactivityresult (). The specific code is as follows:
    Sender:
    Intent Intent = new Intent ();    Intent = Intent.setclass (Activity1.this, anotheractivity.class);    Bundle bundle = new bundle ();    Bundle.putstring ("string", "CPACM");    Intent.putextras (bundle);    Startactivityforresult (intent,0);       Only here, 0 is the request code, used to return the data recognition//activity1.this.finish ();  Cannot use finish, will trigger OnDestroy ();

    Receiving Party:

    Intent Intent = new Intent ();   Intent = Intent.setclass (Anotheractivity.this, activity1.class);   Bundle bundle = new bundle ();   Bundle.putint ("Result", "Results of Activity2 processing");   Intent.putextras (bundle);       AnotherActivity.this.setResult (RESULT_OK, intent);   RESULT_OK is the return status code   AnotherActivity.this.finish ();//Will trigger OnDestroy ();  

    Sender accepts message: (where Requestcode is the request code, can distinguish different processing modules according to the different request code)

                  protected void Onactivityresult (int requestcode, int resultcode, Intent data) {                       Super.onactivityresult (requestcode , ResultCode, data);                        Switch (ResultCode) {//According to the status code, processing the return result case                        RESULT_OK:                               Bundle Bundle =data.getextras ();   Gets the bundle object inside the intent                                  String result = Bundle.getint ("result");                         break;                           Default: Break                        ;                        }                         

Second, the file system to do data sharing
    1. With the context.getsharedpreferences (String filename,int mode) method, you can open an XML file with the location of the file in/data/data/package_name/shared_ Prefs/filename.xml, if it does not exist, it is created automatically. You can read and write to the file and share data among the components within the app. If MODE is set to Context.mode_world_read or Context.mode_world_write, it can also be accessed by other apps. However, this is not a recommended way for Android, and the recommended way to share data across applications is to implement it with ContentProvider. The specific implementation method can look at previously written articles on Android data storage (top) and Android data storage (below).
    2. In addition to the more convenient shared_prefs, you can also create a custom file by Context.openfileoutput (), you can create the specified file in the/data/data/package_name/files/directory, in addition, And the shared_prefs mentioned above are the same. But it's a little more complicated to operate. To read a file created in this way, you can use the Context.openfileinput () method.
    3. In addition, you can also manipulate the files on the SD card, via the API within the standard Java.io package. However, it is important to note that the SD card is in the FAT file system, so it does not support the Linux file read and Write permission control, which is not the same as shared_prefs. If you need to control the file read and write permissions, you cannot use the way to write to the SD card.
    4. You can also use the Android-brought SQLite database to do data persistence, the main classes used include Sqliteopenhelper and sqlitedatabase.

Third, application set global data

In Java, when we use global variables, we generally use static variables, and then the public type, so that all classes can use these variables. Of course, this can also be done on Android. But what we're saying here is that we can use application to manage these variables. The application class is a base class that is intended to obtain the state of the entire application. We can inherit or implement this class ourselves, when you want to use your own extended application class, as long as the manifest.xml in the <application> tag in the name of the class to apply their own definition of the line, The result of this is that the class is instantiated when your application or the process in which the package is created.

The method used is very simple, first inherit the application class and then go to rewrite it, mainly rewrite the inside of the OnCreate method, is the time of creation, initialize the value of the variable. The variable can then be manipulated in various files throughout the application.

When application is started, a PID, the process ID, is created, and all activity is run on this process. Then we initialize the global variables when the application is created, all the activity of the same application can fetch the values of these global variables, in other words, we change the values of these global variables in one activity, Then the value of the other activity in the same application will change. This way we achieve the goal of controlling global variables. (Of course application is not limited to this, it can be used to set up more features with developers)
Here's a small example:

public class MYAPP extends application{        private String learn;          Public String Getlearn () {          return learn;      }         public void Setlearn (String s) {          this.learn= s;      }        @Override public      void OnCreate () {          //TODO auto-generated method Stub          super.oncreate ();          Setlearn ("CPACM"); Initialize global variable             }     }

The above is a simple use that inherits the application class, and we just create a new string variable. There is no global, no static, and it has to be done through MyApp to use it.

Now let's see how we use it:

public class Mainactivity extends Activity {           private myyapp myApp;           @Override public      void OnCreate (Bundle savedinstancestate) {          super.oncreate (savedinstancestate);          Setcontentview (r.layout.main);          myapp= (Myyapp) getapplication (); Get the custom application Yapp          log.d ("TEST", "Initlabel:" +myapp.getlearn ());   Take out the global variables we put into the process and see if we have set the value           myapp.setlearn ("Ahaha");  Modify the          log.d ("TEST", "Changelabel:" +myapp.getlearn ()); Look, this value has changed no      }  }

Finally, register your own defined app in the configuration file

<!--here, set the default application to your own myapp-->      <application android:name= "MyApp" .../>
Iv. Component Control Data
  1. The first of course is the Orthodox ContentProvider component, how to use it, please read this blog post, here is no longer described. Android four components of the contentprovider.
  2. The service can also act as a component of data control, after all, the service is running in the background, and when it is tied to activity, the activity can fetch data from it (provided the service is not destroyed). Details: Service of Android four components
  3. Broadcast components are also available and can be usedSendorderedbroadcast(Intent, null, broadcastreceiver (, null, Activityresult_ok,  Null, null)

V. Concluding remarks

From the beginning of writing the first blog post, it has been one months now, and unconsciously the time has passed. During the intermittent write more than 10 blog post, but write good or not, write bad, anyway Bo master feel oneself Harvest very big, and the former want what function to learn what that fragment type of study compared, now this comprehensive study feel much better.

So far, the components of the Android Starter section is basically finished, of course, there is a lot of content to delve into, this aspect of the people to dig their own. Then the next is the Android control part, the amount, a thought so many control head is big, but the basic principles are interlinked, extrapolate well, if there is any problem can also contact me to discuss learning, finally hope that we have a good day.

========================================

Cpacm
Source: (http://www.cnblogs.com/cpacm/p/3946586.html)

Data transfer between Android components

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.