Parsing the data transfer method between the activity _android

Source: Internet
Author: User
Tags commit gettext sqlite sqlite database stub
1 message-based communication mechanism Intent--------Boudle,extra
In this simple form, it is relatively easy to pass some simple types, such as int, string, etc.
Introduce the intent mechanism in detail
intent consists of two parts:
1 Purpose "action"-------Where to go
2 Content "category, data"----------What's on the road, differentiated data and content data
Simple Data delivery:
Copy Code code 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");
/////////////////////////////////////////////////////////

Data types are limited, it is not easy to encounter data types that are not serializable, Bitmap,inputstream, or linklist lists.
2 Using static data, the public static member variable
We must not assume that the garbage collector of the Davlik virtual machine will help us reclaim unwanted memory garbage. In fact, the collector is unreliable,
Especially on the phone, is more unreliable. So, unless we want to make our programs worse, try to stay away from static.
Note: If you frequently use static bitmap, drawable, and other variables. Might throw a very famous exception in the Android system (
Before budget this word has been unable to remember what meaning, since often throw this exception, the word finally learned in the heart,
Error/androidruntime (4958): caused by:java.lang.OutOfMemoryError:bitmap size exceeds VM budget
Note: If you frequently use static bitmap, drawable, and other variables. Might throw a very famous exception in the Android system (
Before budget this word has been unable to remember what meaning, since often throw this exception, the word finally learned in the heart,
3 based on external storage transmission, file/preference/sqlite, if you need content provider for third party applications
As a completed application, data storage operations are essential. As a result, the Android system provides a total of four ways to store data.
respectively: Sharepreference, SQLite, Content provider and file. Because of the Android system, the data is basically private.
, are stored in the "data/data/package name" directory, so to achieve data sharing, the correct way is to use the content Provider.
Sqlite:sqlite is a lightweight database that supports basic SQL syntax and is a commonly used method of data storage. Android
This database provides a class named Sqlitedatabase that encapsulates some of the APIs that manipulate the database.
Sharedpreference: In addition to SQLite database, another common way of data storage, its essence is an XML file, often used to
Stores simpler parameter settings.
File: That is, a commonly used document (I/O) storage method, often used to store a large number of data, but the disadvantage is that updating the data will be a difficult
Things.
Contentprovider:contentprovider is a mechanism for the implementation of data sharing between different applications in an Android platform. One
Applications can use this mechanism if they need to allow other programs to manipulate their own data. And this way ignores the underlying data store
Implementation, ContentProvider provides a unified way of implementing data operations through URIs.
detailed introduction to the use process
File passes the data through the reading of the contents of the files
Preference:sharedpreferences is also a lightweight way to store data, and its essence is to store Key-value key values based on XML files
For data, typically used to store some simple configuration information
The Sharedpreferences object itself can only fetch data and does not support storage and modification, and storage modifications are implemented through editor objects. Realize
the steps for sharedpreferences storage are as follows:
first, get the Sharedpreferences object according to the context
Second, use the edit () method to obtain the editor object.
Store Key-value key value pairs through the editor object.
Submission of data through the commit () method.
Copy Code code as follows:

Sharedpreferences sp=getsharedpreferences ("login", 0);//login store filename
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 steps are:
1. Define a ContentProvider in the current application.
2. Register this contentprovider in the androidmanifest.xml of the current application
3. Other applications obtain this ContentProvider data through Contentresolver and URIs.
In program A, inherit the Contprovider class and override the method
Copy Code code 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;
}

Initializing a database in Create
@Override
public Boolean onCreate () {
Sqlitedatabase db = This.getcontext (). Openorcreatedatabase ("Test_db.db3",
Context.mode_private, NULL);
Db.execsql ("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;
}

Implementing the 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, NULL, NULL, NULL, null,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, where the authorities property defines the URI of this ContentProvider
Identity.
<provider android:name= ". MyProvider "android:authorities=" Com.test.MyProvider "/>
In application B, the data in the ContentProvider of program A is obtained by Contentresolver.
Copy Code code as follows:

public class Mainactivity extends activity {
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);

Get context
Context ctx = Mainactivity.this;
Get Contentresolver Object
Contentresolver resolver = Ctx.getcontentresolver ();
Get URI Object
Uri uri = uri.parse ("Content://com.test.myprovider");
Get Data
Cursor C = resolver.query (URI, NULL, NULL, NULL, 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 look at the structure of two applications, the program structure of a, you can see clearly that it has a database called "TEST_DB.DB3", B's program structure, and no database is used to store data. From this diagram, you can determine that the data that is queried in application B comes from application A.
The above is the use of ContentProvider, this storage way compared to SQLite and sharedpreferences, its complexity is obvious, but everywhere in the "cloud" today, The data interaction requirements between programs make the ContentProvider storage mechanism an essential part.
4 communication mechanism based on IPC
Transmission between context and service, such as communication between activity and service
5 based on application context
Initializes a ArraylistAn activity outside, the first directly consider using Putextra, the test found that the data can only be transmitted once, consider using application to pass
Java usually uses a static variable (such as singleton) to synchronize the state between the activity (between the classes in the program). The more plausible approach to Android is to use the application context to correlate these states.
Each activity is a context that contains the state of the runtime. Similarly application also has a context,android that will ensure that the context is the only instance.
Copy Code code 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>

To get the code for the bitmap object:
Copy Code code 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. of the 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.