Android多Activity静态变量更新不实时问题及变量管理方案咨询
Hey there! Let's tackle your problem step by step—first fixing the real-time display issue, then talking about the best way to manage those 10 variables long-term.
1. Fixing the Real-Time Display Problem
The root issue here is that your TextView only gets updated in onCreate(), which only runs when the Activity is first created. When you navigate back from Activity5 to Activity3/4, those Activities are just being resumed from the back stack—onCreate() doesn't run again, so the old value stays on screen.
Quick Fix: Update UI in onResume()
You can move the display update logic into onResume() (or call a shared method from both onCreate() and onResume()), since onResume() is always called when the Activity comes back to the foreground.
Here's how to adjust Class3 (repeat the same for Class4):
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_class3); // Call the update method when the Activity is first created updateMoneyDisplay(); // Rest of your initialization code... } @Override protected void onResume() { super.onResume(); // Update the display every time the Activity comes back to the foreground updateMoneyDisplay(); } private void updateMoneyDisplay() { TextView moneyView = findViewById(R.id.outputmoney); moneyView.setText(String.valueOf(Class3.money)); }
This way, every time you return to Activity3 or 4, the TextView will pull the latest value of money and refresh itself.
2. Best Management for Your 10 Variables
Using public static variables works for small tests, but it's not scalable (especially with 10 variables) and comes with risks like memory leaks, accidental value overwrites, and loss of data when your app's process is killed. Here are the recommended alternatives:
Option 1: ViewModel + LiveData (Google's Recommended Approach)
ViewModel is part of Android Jetpack, designed to hold UI-related data across Activity/Fragment lifecycle changes. Pairing it with LiveData lets your UI automatically update whenever the data changes—no more manual calls to updateMoneyDisplay().
Step 1: Create a Shared ViewModel
import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; public class WalletViewModel extends ViewModel { // Use MutableLiveData for variables that change, LiveData for read-only access private MutableLiveData<Integer> money = new MutableLiveData<>(100); // Add your other 9 variables here, e.g.: // private MutableLiveData<Integer> score = new MutableLiveData<>(0); // Getter for read-only access to the UI public LiveData<Integer> getMoney() { return money; } // Method to modify the value (encapsulates the logic) public void decreaseMoney(int amount) { int currentValue = money.getValue() != null ? money.getValue() : 0; money.setValue(currentValue - amount); } // Add getters and modifiers for your other variables... }
Step 2: Use the ViewModel in Your Activities
To share the same ViewModel instance across multiple Activities, use getApplication() as the ViewModel owner (this ensures all Activities get the same data):
// In Class3, Class4, and Class5 private WalletViewModel walletViewModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_class3); // Get the shared ViewModel instance walletViewModel = new ViewModelProvider((ViewModelStoreOwner) getApplication()).get(WalletViewModel.class); TextView moneyView = findViewById(R.id.outputmoney); // Observe the LiveData—UI auto-updates when the value changes walletViewModel.getMoney().observe(this, newMoneyValue -> { moneyView.setText(String.valueOf(newMoneyValue)); }); // For Activity5's button click: // findViewById(R.id.decrease_button).setOnClickListener(v -> { // walletViewModel.decreaseMoney(10); // }); }
With this setup, whenever you modify money in Activity5, all other Activities observing the LiveData will automatically refresh their TextViews. No need to handle onResume() manually!
Option 2: SharedPreferences (For Persistent Data)
If you need your variables to survive app restarts (e.g., the user closes and reopens the app), use SharedPreferences to store the values. However, you'll still need to trigger UI updates (either via onResume() or a listener).
Example of saving/loading money:
// Save the value SharedPreferences prefs = getSharedPreferences("MyAppPrefs", MODE_PRIVATE); prefs.edit().putInt("money", 90).apply(); // Load the value int currentMoney = prefs.getInt("money", 100); // 100 is the default value
Why Avoid public static Variables?
- Memory Leaks: Static variables can hold references to Activities, preventing them from being garbage collected.
- Unpredictable State: Any class can modify the static value without control, leading to bugs.
- No Persistence: If your app's process is killed (e.g., low memory), static values are lost.
内容的提问来源于stack exchange,提问作者GreekDeveloper

