2013-12-07 69 views
1

我正在构建一个包含SharedPreferences的Android项目。SharedPreferences在android程序中产生强制关闭

我的SharedPreferences工作正常,我在多项活动中测试它。但是在我为全局变量定义的类中,定义SharedPreferences将导致关闭力(日食没有在代码中显示任何错误)。

public class Globals extends Application { 

    final SharedPreferences s = getSharedPreferences("Prefs", MODE_PRIVATE); 

} 

什么问题?

+1

SharedPreferences只能从上下文来获得。所以它需要'context.getSharedPreferences(“Prefs”,Context.MODE_PRIVATE);'你的类对Context没有任何的了解 - 这是问题。您需要在方法中或通过构造函数传递Context变量作为参数。 – Sajmon

+0

我改变了它:final SharedPreferences s = this.getSharedPreferences(“Prefs”,MODE_PRIVATE);但仍然产量逼近。 – user3077909

+0

你不能使用这个,因为你不在活动(活动从Context延伸出于这个原因,你可以使用或不)。您需要显式传递Context作为参数或方法或构造函数。没有其他方式如何做到这一点。 – Sajmon

回答

1

您应该通过Context,并使用

SharedPreferences prefs = Context.getSharedPreferences( "Prefs", Context.MODE_PRIVATE);

0

创建一个构造函数,并通过上下文变量作为参数。任何想要使用此偏好的活动都必须通过活动。下面是代码如下:

public class Globals extends Application { 

    private Context context; 

    public Globals (Context context) { 
     this.context = context; 
    } 

    SharedPreferences myPref = context.getSharedPreferences("Prefs", Context.MODE_PRIVATE); 
} 
0

你不能在实际的类中运行getSharedPreferences()。您所做的一切必须在应用程序的onCreate方法中。如果你尝试在课堂上运行它,它会失败,因为它还没有被初始化。将它看作一种活动,因为活动和应用程序都有一个生命周期。

尝试以下方法:

public class Globals extends Application { 

    @Override 
    public void onCreate() { 
     super.onCreate(); 

     final SharedPreferences s = getSharedPreferences("Prefs", MODE_PRIVATE); 
    } 
}