对于我的Android应用程序,我编写了一个由应用程序中各种活动所需的实用函数组成的类。在这个类中,我需要一个上下文变量(for用文件)和偏好经理和偏好editor.Also,一个长整型,因为需要一个时间戳represnting当前日期的实例工作:在一类实用函数中初始化静态变量
private static long today;
private static Context myContext;
private static SharedPreferences sharedPrefs;
private static Editor editor;
这是初始化这些变量正确的方法。我试图通过如下所示的私人构造函数来做到这一点,但我越来越错误。
private NetworkController()
{
//Getting the Unix timestamp for today
GregorianCalendar aDate = new GregorianCalendar();
GregorianCalendar tDate = new
GregorianCalendar(aDate.get(Calendar.YEAR),aDate.get(Calendar.MONTH),
aDate.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
today = (tDate.getTimeInMillis())/1000;
//The preferences manager for reading in the preferences
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(myContext);
//The preferences editor for modifying the preferences values
editor = sharedPrefs.edit();
}
一种方法是创建它的地方使用这个类在每一个活动的一个实例,但我不知道,不想做that.Any另一种方法是可能的吗?
你究竟在犯什么错误?你是否熟悉单身人士的想法? –
我收到了有关sharedPrefs和editor的空指针异常。我不熟悉这个概念,这就是为什么我问:) – user1107888
只是一个提示:小心你使用Context作为静态变量。这很容易造成内存泄漏。确保当您切换到新的上下文时它被清零或取消引用。 – Codeman