You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 use getContext().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 Application instance (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:23:51