我有一个保存音乐应用的类别和频道的单身人士。我使用单例,因为类别和通道是从嵌入在应用程序中的本地JSON文件加载的。但是,业务需求已更改,我现在从服务器上的远程JSON文件加载它们。
这里是ChannelLab类(大致):
private ArrayList<Channel> mChannels;
private ArrayList<Category> mCategories;
// To be removed later...
private ArrayList<ChannelOld> mChannelsOld;
private static final int CHANNELS_OLD_JSON = R.raw.channels;
//
private static ChannelLab sChannelLab;
private Context mAppContext;
...
public ChannelLab(Context appContext) {
sChannelLab = this;
mAppContext = appContext;
mChannels = new ArrayList<Channel>();
mCategories = new ArrayList<Category>();
//
// To be removed later
mChannelsOld = new ArrayList<ChannelOld>();
//
//
}
public static ChannelLab get(Context c) {
if (sChannelLab == null) {
//Crashlytics.log(1, TAG, "sChannelLab NULL");
sChannelLab = new ChannelLab(c.getApplicationContext());
}
return sChannelLab;
}
public void loadAll() {
try {
//mChannels = loadChannels();
new LoadChannelsFromServer().execute();
//
// To be removed later
mChannelsOld = loadChannelsOld();
//
//
} catch (Exception e) {
mChannels = new ArrayList<Channel>();
Log.e(TAG, "Error loading channels: ", e);
}
try {
//mCategories = loadCategories();
new LoadCategoriesFromServer().execute();
} catch (Exception e) {
mCategories = new ArrayList<Category>();
Log.e(TAG, "Error loading categories: ", e);
}
}
在发布时,我运行以下代码来加载类别和频道:
clab = new ChannelLab(getApplicationContext());
clab.setCallback(this);
clab.loadAll();
和mCategories和mChannels填充了类别和渠道。
问题是有时候(很可能是当活动被破坏时),ChannelLab实例仍然可用,mChannels和mCategories也是,但它们是空的。它们不是null,但它们的大小为0,并且在使用以下命令恢复行为并访问ChannelLab时会导致空指针异常:
ChannelLab(getActivity().getApplicationContext())
在没有活动时,我需要做些哪些更改才能确保mCategories和mChannels仍然填充数据?提前谢谢......