Extending Application to share variables globally
我尝试在我的应用程序中的各种活动中共享两个数组列表,使用这里解释的方案:如何在Android中声明全局变量?.
这是我的应用程序子类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public class GlobalVars extends Application{ ArrayList<Player> players = new ArrayList<Player>(); ArrayList<String> playerNames = new ArrayList<String>(); public ArrayList<Player> getPlayers(){ return players; } public ArrayList<String> getPlayerNames(){ return playerNames; } public void setPlayers(ArrayList<Player> p){ players = p; } public void setPlayerNames(ArrayList<String> pn){ playerNames = pn; } } |
使用代码:
1 2 3 | GlobalVars gv = (GlobalVars)getApplicationContext(); players = gv.getPlayers(); playerNames = gv.getPlayerNames(); |
访问这些变量。我定义gv的第一行抛出一个ClassCastException。有人知道为什么吗?
这是我添加到清单中的代码:
1 2 3 | <application android:name="com.myname.GlobalVars" android:icon="@drawable/icon" android:label="@string/app_name"></application> |
编辑:澄清一下,这是我的全部清单:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.myname.bpstattracker" android:versionCode="1" android:versionName="1.0"> <intent-filter> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </activity> </activity> </activity> </application> <application android:name="com.myname.GlobalVars" android:icon="@drawable/icon" android:label="@string/app_name"> </application> </manifest> |
为了详细说明PeterK的答案,您不需要为派生应用程序类创建第二个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.myname.bpstattracker" android:versionCode="1" android:versionName="1.0"> <intent-filter> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </activity> </activity> </activity> </application> </manifest> |
说清楚,
1 2 3 4 5 | <application android:allowBackup="true" android:icon="@drawable/icon_app" android:label="@string/app_title" android:theme="@android:style/Theme.NoTitleBar.Fullscreen"> |
是我现有的舱单。要在我现有的清单中声明另一个应用程序和/或全部应用程序,我只需添加:
1 | android:name="com.XXXXXX.data.DataStore" |
所以最终结果是:
1 2 3 4 5 6 | <application android:name="com.XXXXXX.data.DataStore" *<-- class that extends Application and has global variables with exact package and class name* android:allowBackup="true" android:icon="@drawable/icon_app" android:label="@string/app_title" android:theme="@android:style/Theme.NoTitleBar.Fullscreen"> |
在您的活动或服务中,您应该致电
1 | GlobalVars gv = (GlobalVars)getApplication(); |
编辑:
您的舱单中有两次定义了