SoFunction
Updated on 2025-04-09

Android Learning Notes--Sample Passing Data Code Through Application

In the entire Android program, sometimes it is necessary to save certain global data (such as user information) to facilitate calls anywhere in the program. There is a relatively common way to use data transfer between activities, which is global objects. Those who have used J2EE should know the four scopes of JavaWeb. The Application domain can be used and accessed anywhere in the application. Unless the web server stops, the global objects in Android are very similar to the Application domain in JavaWeb. Unless the Android application clears memory, the global objects will always be accessible.

When starting Application, the system creates a PID, that is, the process ID, and all activities will run on this main process. Therefore, all activities in the same Application can obtain the same Application object through the () method, inherit the Application class, and access custom data.

Simply put, the steps to pass data using Application are as follows:
Create a new class, name MyApp, inherit the parent class, and define the attributes to be saved in MyApp, such as: user name, user type.
In the Activity, the MyApp object is obtained through the () method (need to cast) and operate on its data.
Modify the android:name attribute of the application node in the file (android:name=".MyApp").

Code Example
Step 1:
Copy the codeThe code is as follows:

public class MyApp extends Application {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
= name;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
();
setName("Dick");
}
}

Step 2:
Copy the codeThe code is as follows:

public class MainActivity extends Activity {
private Button btn;
private MyApp myApp;
@Override
protected void onCreate(Bundle savedInstanceState) {
(savedInstanceState);
setContentView(.activity_main);
btn=(Button)();
(new () {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
myApp=(MyApp)getApplication();
("jack");
Intent intent=new Intent(, );
startActivity(intent);
}
});
}
}

Step 3:
Copy the codeThe code is as follows:

<manifest xmlns:andro
package=""
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:name=".MyApp"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=""
android:label="@string/app_name" >
<intent-filter>
<action android:name="" />
<category android:name="" />
</intent-filter>
</activity>
<activity android:name=".otherActivity"/>
</application>
</manifest>