Explanation of data transfer methods between activities

Source: Internet
Author: User

1 message-based communication mechanism Intent -------- boudle, extra
In this simple form, it is easier to pass some simple types, such as int and string.
Introduce Intent mechanism in detail
Intent contains two parts:
1. Objective [action] ------- where to go
2. Content: [category, data] ---------- what is included on the road, differentiation data and content data
Simple data transmission: Copy codeThe Code is as follows: Intent intent = new Intent (LoginActivity. this, MainActivity. class );
Intent. putExtra ("flag", flag );
StartActivity (intent );
//////////////////////////////////////// /////////////////
String flag = "";
Intent intent1 = this. getIntent ();
Flag = intent1.getStringExtra ("flag ");
//////////////////////////////////////// /////////////////

The data type is limited, so Bitmap, Inputstream, or LinkList linked list data types that are not serializable are not easy to use.
2. Use static data and public static member variables
We should never think that the garbage collector of the Davlik virtual machine will help us reclaim unwanted memory garbage. In fact, the recycler is not reliable,
Especially on mobile phones, it is more unreliable. Therefore, unless we want to make our program worse and worse, we should try to stay away from static.
Note: static Bitmap, Drawable, and other variables are often used. It may throw a very famous exception in the Android system (
In the past, budget had never been able to remember what it meant. Since this exception was often thrown out, the word has finally become quite familiar ,)
ERROR/AndroidRuntime (4958): Caused by: java. lang. OutOfMemoryError: bitmap size exceeds VM budget
Note: static Bitmap, Drawable, and other variables are often used. It may throw a very famous exception in the Android system (
In the past, budget had never been able to remember what it meant. Since this exception was often thrown out, the word has finally become quite familiar ,)
3. Transmission Based on External Storage: File/Preference/Sqlite. If you want to target third-party applications, you need Content provider.
As a complete application, data storage operations are essential. Therefore, the Android system provides four data storage methods.
They are SharePreference, SQLite, Content Provider, and File. In Android, data is basically private.
, Are stored in the "data/package name" directory, so to achieve data sharing, the correct method is to use Content Provider.
SQLite: SQLite is a lightweight database that supports basic SQL syntax and is a common data storage method. Android
Therefore, the database provides a class named SQLiteDatabase, which encapsulates APIs for database operations.
SharedPreference: in addition to the SQLite database, SharedPreference is another common data storage method. In essence, SharedPreference is an xml file, which is often used in
Store simple parameter settings.
File: a commonly used File (I/O) storage method, which stores a large amount of data. However, it is difficult to update data.
Events.
ContentProvider: ContentProvider is a mechanism for data sharing between different applications on the Android platform. One
This mechanism can be used if an application needs to allow other programs to operate on its own data. In addition, this method ignores the underlying data storage.
ContentProvider provides a unified method for data operations through Uris.
Detailed introduction
File Reads and transmits data through File content
Preference: SharedPreferences is also a lightweight data storage method, which is essentially based on the key-value key value stored in XML files.
Data is usually used to store some simple configuration information.
The SharedPreferences object can only obtain data, but does not support storage and modification. The storage modification is implemented through the Editor object. Implementation
To store SharedPreferences, follow these steps:
1. Get the SharedPreferences object based on Context
2. Use the edit () method to obtain the Editor object.
3. Use the Editor object to store key-value pairs.
4. submit data using the commit () method.
Copy codeThe Code is as follows: SharedPreferences sp = getSharedPreferences ("login", 0); // login storage file name
SharedPreferences. Editor se = sp. edit ();;
Se. putString ("server", logEdit. getText (). toString ());
Se. putString ("port", portEdit. getText (). toString ());
Se. commit ();
//////////////////////////////////////// /////////////////////
SharedPreferences ps = getSharedPreferences ("login", 0); // login is the storage file
Server = ps. getString ("server ","");
Port = ps. getString ("port ","");

LogEdit. setText (server );
PortEdit. setText (port );
//////////////////////////////////////// /////////////////////
ContentProvider

The procedure is as follows:
1. Define a ContentProvider in the current application.
2. Register this ContentProvider in AndroidManifest. xml of the current application
3. Other applications use ContentResolver and Uri to obtain the data of this ContentProvider.
In program A, inherit the ContProvider class and override the methods in it.Copy codeThe Code is as follows: public class MyProvider extends ContentProvider {
@ Override
Public int delete (Uri uri, String selection, String [] selectionArgs ){
// TODO Auto-generated method stub
Return 0;
}

@ Override
Public String getType (Uri uri ){
// TODO Auto-generated method stub
Return null;
}

@ Override
Public Uri insert (Uri uri, ContentValues values ){
Return null;
}

// Initialize a database in Create
@ Override
Public boolean onCreate (){
SQLiteDatabase db = this. getContext (). openOrCreateDatabase ("test_db.db3 ",
Context. MODE_PRIVATE, null );
Db.exe cSQL ("create table tab (_ id integer primary key autoincrement, name TEXT NOT
NULL )");
ContentValues values = new ContentValues ();
Values. put ("name", "test ");
Db. insert ("tab", "_ id", values );
Db. close ();
Return true;
}

// Query method
@ Override
Public Cursor query (Uri uri, String [] projection, String selection,
String [] selectionArgs, String sortOrder ){
SQLiteDatabase db = this. getContext (). openOrCreateDatabase ("test_db.db3 ",
Context. MODE_PRIVATE, null );
Cursor c = db. query ("tab", null );
Return c;
}

@ Override
Public int update (Uri uri, ContentValues values, String selection,
String [] selectionArgs ){
// TODO Auto-generated method stub
Return 0;
}
}

Declare this ContentProvider in its AndroidManifest. xml. The authorities attribute defines the Uri of this ContentProvider.
Id.
<Provider android: name = ". MyProvider" android: authorities = "com. test. MyProvider"/>
In application B, use ContentResolver to obtain data in ContentProvider of program.Copy codeThe Code is as follows: public class MainActivity extends Activity {
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );

// Obtain the context
Context ctx = MainActivity. this;
// Obtain the ContentResolver object
ContentResolver resolver = ctx. getContentResolver ();
// Obtain the Uri object
Uri uri = Uri. parse ("content: // com. test. MyProvider ");
// Obtain data
Cursor c = resolver. query (uri, null );
C. moveToFirst ();
For (int I = 0; I <c. getCount (); I ++ ){
Int index = c. getColumnIndexOrThrow ("name ");
String src = c. getString (index );
Log. d ("", src );
C. moveToNext ();
}
}
}

Then observe the structure of the two applications. The program structure of A clearly shows that there is A database named "test_db.db3" and the program structure of B. It does not have any database for data storage. As shown in the following figure, we can determine that the data queried in application B comes from application.
The above is how ContentProvider is used. Compared with SQLite and SharedPreferences, this storage method has obvious complexity, but it is everywhere seen in today's "Cloud, the Data Interaction requirements between programs make the ContentProvider storage mechanism an essential part.
4. Ipc-based communication mechanism
Transmission between context and service, such as communication between Activity and Service
5 Application Context-based
Initialize an ArrayList <HashMap <Sting, Map> object in an activity, and then pass it to another
For an external activity, putExtra is directly considered at the beginning. If the test finds that the data can only be transmitted once, Application is used to transmit the data.
In Java, a static variable (such as singleton) is usually used to synchronize the status between activities (between classes in the program. In android, application context is used to associate these states.
Every activity is context, which contains the running status. Similarly, the application also has a context. android will ensure that this context is a unique instance.Copy codeThe Code is as follows: package net. blogjava. mobile1;
Import android. app. Application;
Import android. graphics. Bitmap;
Public class MyApp extends Application
{
Private Bitmap mBitmap;
Public Bitmap getBitmap ()
{
Return mBitmap;
}
Public void setBitmap (Bitmap bitmap)
{
This. mBitmap = bitmap;
}

}
<Application android: name = ". MyApp" android: icon = "@ drawable/icon" android: label = "@ string/app_name">
</Application>

Get Bitmap object code:Copy codeThe Code is as follows: ImageView imageview = (ImageView) findViewById (R. id. ivImageView );

MyApp myApp = (MyApp) getApplication ();

Imageview. setImageBitmap (myApp. getBitmap ());

The above two pieces of code can be used in any Service or Activity. Global

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.