Intent后及Fragment切换后全局变量为空问题求助
Hey there, let's break down why your global variables keep getting cleared after launching Intents or switching Fragments—this is a super common Android pitfall, so let's fix it step by step!
First, Let's Diagnose the Common Culprits
1. You're not retrieving the actual Application class instance
A lot of developers make the mistake of creating a new instance of GlobalClass directly (like new GlobalClass()) instead of grabbing the singleton instance tied to your app's lifecycle. That new instance won't hold any of your stored values, hence the empty variables.
2. Your GlobalClass isn't registered in the Manifest
If Android doesn't know to use your custom Application subclass, it'll fall back to the default Application class. Your GlobalClass never gets initialized, so none of your variable logic works.
3. App process got killed by the system
Android aggressively reclaims memory when resources are low. If your app is in the background and gets terminated, when it restarts, your GlobalClass will reinitialize—wiping out any in-memory variables that weren't persisted.
Step-by-Step Fixes
1. Verify your GlobalClass implementation
Make sure it extends Application properly, with getter/setter methods:
public class GlobalClass extends Application { private String myGlobalVariable; public String getMyGlobalVariable() { return myGlobalVariable; } public void setMyGlobalVariable(String value) { myGlobalVariable = value; } @Override public void onCreate() { super.onCreate(); // Optional: Initialize default values here (avoid heavy operations!) } }
2. Register GlobalClass in your AndroidManifest.xml
Add the android:name attribute to your <application> tag to tell Android to use your custom class:
<application android:name=".GlobalClass" <!-- This line is critical! --> android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme"> <!-- Your Activities, Fragments, etc. --> </application>
3. Correctly retrieve the GlobalClass instance
Never create a new instance—always use the app's context to get the singleton:
- In an Activity:
// Store a value GlobalClass globalClass = (GlobalClass) getApplicationContext(); globalClass.setMyGlobalVariable("Your value here"); // Retrieve a value String storedValue = globalClass.getMyGlobalVariable();
- In a Fragment:
Always usegetContext().getApplicationContext()to avoid issues with Activity lifecycle changes:
if (getContext() != null) { GlobalClass globalClass = (GlobalClass) getContext().getApplicationContext(); String storedValue = globalClass.getMyGlobalVariable(); }
4. Persist variables for process recovery
If you need values to survive app process restarts, add persistence using SharedPreferences (or Room for more complex data):
Update your GlobalClass to save/load values automatically:
public class GlobalClass extends Application { private String myGlobalVariable; private SharedPreferences prefs; @Override public void onCreate() { super.onCreate(); prefs = getSharedPreferences("GlobalPrefs", MODE_PRIVATE); // Load saved value on initialization myGlobalVariable = prefs.getString("myGlobalVar", null); } public String getMyGlobalVariable() { return myGlobalVariable; } public void setMyGlobalVariable(String value) { myGlobalVariable = value; // Save value to SharedPreferences prefs.edit().putString("myGlobalVar", value).apply(); } }
Quick Notes to Avoid Future Issues
- Don't store large objects or context-dependent references (like
Activity/View) in your global class—this can cause memory leaks. - If you're using navigation components, make sure you're not accidentally recreating the
Applicationinstance (the above steps should prevent this).
Give these fixes a try—9 times out of 10, it's either the Manifest registration or incorrect instance retrieval causing the empty variables!
内容的提问来源于stack exchange,提问作者Mon Pinoliad

