SoFunction
Updated on 2025-04-04

Detailed explanation of the data transfer method between activities

1 Message-based communication mechanism Intent-------boudle,extra
In this simple form, it is generally easier to pass some simple types, such as int, string, etc.
Introduce the Intent mechanism in detail
Intent contains two parts:
1 Purpose 【action】------Where to go
2 Content [category, data]----------What to bring on the road, distinguishing data from content data
Simple data transfer:
Copy the codeThe code is as follows:

Intent intent = new Intent(, );
("flag", flag);
startActivity(intent);
/////////////////////////////////////////////////////////
String flag = "   ";
Intent intent1 = (); 
flag = ("flag");
/////////////////////////////////////////////////////////

The data types are limited, so it is not easy to use when encountering data that cannot be serialized.
2. Use static static data, public static member variables
We must not think that the garbage collector of the Davlik virtual machine will help us recycle unwanted memory garbage. In fact, the recycler is not reliable.
Especially on mobile phones, it is even more unreliable. So, unless we are going to make our programs worse and worse, try to stay away from static.
Note: If you often use static Bitmap, Drawable and other variables. It may throw an exception that is very famous in the Android system (
In the past, I couldn't remember what the word budget means. Since I often threw this exception, I finally got to know it.)
ERROR/AndroidRuntime(4958): Caused by: : bitmap size exceeds VM budget
Note: If you often use static Bitmap, Drawable and other variables. It may throw an exception that is very famous in the Android system (
In the past, I couldn't remember what the word budget means. Since I often threw this exception, I finally got to know it.)
3. Transmission based on external storage, File/Preference/Sqlite, if you want to target third-party applications, Content provider is required
As a completed application, data storage operations are essential. Therefore, the Android system provides a total of four data storage methods.
They are: SharePreference, SQLite, Content Provider and File. Since the data in the Android system is basically private
, are all stored in the "data/data/package name" directory, so to realize data sharing, the correct way is to use Content Provider.
SQLite: SQLite is a lightweight database that supports basic SQL syntax and is a commonly used data storage method. Android
This database provides a class called SQLiteDatabase, encapsulating some APIs for operating the database.
SharedPreference: In addition to SQLite database, another commonly used data storage method is essentially an XML file, which is often used in
Store simpler parameter settings.
File: It is commonly referred to as file (I/O) storage method. It is commonly used to store a large amount of data, but the disadvantage is that updating data will be difficult.
matter.
ContentProvider: ContentProvider is a mechanism for implementing data sharing among different applications in the Android platform. one
If an application needs to allow other programs to operate its own data, this mechanism can be adopted. And this method ignores the underlying data storage
Implementation, ContentProvider provides a unified way to implement data operations through Uri.
Detailed introduction to the usage process
File passes data through reading of file content
Preference: SharedPreferences is also a lightweight data storage method. Its essence is to store key-value key values ​​based on XML files.
For data, it is usually used to store some simple configuration information.
The SharedPreferences object itself can only obtain data but does not support storage and modification. Storage modification is implemented through the Editor object. accomplish
The steps for SharedPreferences storage are as follows:
1. Get SharedPreferences object according to Context
2. Use the edit() method to obtain the Editor object.
3. Store key-value key-value pair data through Editor object.
4. Submit data through commit() method.
Copy the codeThe code is as follows:

SharedPreferences sp=getSharedPreferences("login",0);//login store file name
   se=();;
   ("server", ().toString());
   ("port", ().toString());
   ();
/////////////////////////////////////////////////////////////
SharedPreferences ps=getSharedPreferences("login",0);//login is a storage file
  server=("server", "");
  port=("port", "");

  (server);
  (port);
/////////////////////////////////////////////////////////////
ContentProvider

The steps are:
1. Define a ContentProvider in the current application.
2. Register this ContentProvider in the current application
3. Other applications obtain the data of this ContentProvider through ContentResolver and Uri.
In program A, inherit the ContProvider class and override the methods in it
Copy the 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 = ().openOrCreateDatabase("test_db.db3",
Context.MODE_PRIVATE, null);
         ("create table tab(_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT
NULL)");
         ContentValues values = new ContentValues();
         ("name", "test");
         ("tab", "_id", values);
         ();
         return true;
     }

//Implement query method
     @Override
     public Cursor query(Uri uri, String[] projection, String selection,
             String[] selectionArgs, String sortOrder) {
         SQLiteDatabase db = ().openOrCreateDatabase("test_db.db3",
Context.MODE_PRIVATE, null);
         Cursor c = ("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 it, where the authorities attribute defines the Uri of this ContentProvider
Identification.
<provider android:name=".MyProvider" android:authorities=""/>
In application B, the data in the ContentProvider of program A is obtained through ContentResolver.
Copy the codeThe code is as follows:

public class MainActivity extends Activity {
     @Override
     public void onCreate(Bundle savedInstanceState) {
         (savedInstanceState);
         setContentView();

//Get the context
         Context ctx = ;
//Get ContentResolver object
         ContentResolver resolver = ();
//Get Uri object
         Uri uri = ("content://");
//Get data
         Cursor c = (uri, null, null, null, null);
         ();
         for(int i=0; i<(); i++){
             int index = ("name");
             String src = (index);
             ("", src);
             ();
         }
     }
 }

After observing the structure of the two applications, A's program structure, you can clearly see that it has a database named "test_db.db3" and B's program structure, which does not have any database used to store data. From this figure, it can be determined that the data result queryed in application B is from application A.
The above is how ContentProvider is used. Compared with SQLite and SharedPreferences, the complexity of this storage method is obvious. However, today, the data interaction requirements between programs have become an indispensable part of the ContentProvider storage mechanism.
4 Ipc-based communication mechanism
Transmission between context and service, such as communication between Activity and Service
5 Based on Application  Context
Initialize an ArrayList<HashMap<Sting,Map>> object in an activity, and then pass it to another tableactivity.
External activity, first, directly consider using putExtra. When the test finds that the data can only be passed once, consider using Application
Java usually uses a static variable (such as singleton or something) to synchronize the state between activities (between classes in the program). A more reliable way in Android is to use application context to associate these states.
Each activity is a context that contains the runtime state. Similarly, the application also has a context, and Android will ensure that this context is the only instance.
Copy the codeThe code is as follows:

package .mobile1;
import ;
import ;
public class MyApp extends Application
{
    private Bitmap mBitmap;
    public Bitmap getBitmap()
    {
        return mBitmap;
    }
    public void setBitmap(Bitmap bitmap)
    {
        = bitmap;
    }

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

The code to get the Bitmap object:
Copy the codeThe code is as follows:

    ImageView imageview = (ImageView)findViewById();

    MyApp myApp = (MyApp)getApplication();

    (());

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