ArrayList作为全局变量 [英] ArrayList as global variable
问题描述
我创建了类似应用程序扩展的类
I created class that extend of application like that
package com.appnetics;
import java.util.ArrayList;
import android.app.Application;
public class GlobalVariables extends Application {
public ArrayList<Encounter> encounters;
}
并将其设置为像这样的表现
and set it in manifist like this
<application
android:name="GlobalVariables"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
在一个Actiity中我使用此代码填充此数组
in one Actiity I fill this array using this code
GlobalVariables appState = new GlobalVariables();
appState.encounters =new ArrayList<Encounter>();
................
then add
当试图使用它时会崩溃并出现null异常,我在另一个活动或类中使用它
when trying to use it it crash with null exception, I use it in another activity or class like that
GlobalVariables appState = new GlobalVariables();
Encounter EncounterObject = appState.encounters.get(position);
请找不到的东西,如何修复
is there something missing please , how to fix that
推荐答案
这是 GlobalVariables
类的实例变量,所以每次创建新的实例 GlobalVariables
,您将获得一个单独的变量。
It's an instance variable of the GlobalVariables
class, so every time you create a new instance of GlobalVariables
, you'll get a separate variable.
如果您真的想要一个全局变量,它应该是一个静态变量 - 但即便如此,只有当你在同一个进程中的活动之间共享数据时才会这样。您应该阅读 Android应用程序框架常见问题解答以获取更多信息。
If you really want a global variable, it should be a static variable - but even that will only work if you're sharing data between activities in the same process. You should read the Android Application Framework FAQ for more information.
这篇关于ArrayList作为全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!