所以我试图在一个no activity类中使用我的共享prefference但是我一直在我的
上获得空指针private SharedPreferences setingPreferences = context.getSharedPreferences(“Settings”,Activity.MODE_PRIVATE);
我该如何解决这个问题?
public class ConnectionClass
{
Context context;
private SharedPreferences setingPreferences = context.getSharedPreferences("Settings", Activity.MODE_PRIVATE);
String ip;
String classs = "net.sourceforge.jtds.jdbc.Driver";
String db = "ISTABLocalDB";
String un = "istab_wpf";
String password = "istab_!234";
@SuppressLint("NewApi")
public Connection CONN() {
ip = setingPreferences.getString("server", "");
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String ConnURL = null;
try {
Class.forName(classs);
ConnURL = "jdbc:jtds:sqlserver://" + ip + ";"
+ "databaseName=" + db + ";user=" + un + ";password="
+ password + ";";
conn = DriverManager.getConnection(ConnURL);
} catch (SQLException se) {
Log.e("ERRO", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERRO", e.getMessage());
} catch (Exception e) {
Log.e("ERRO", e.getMessage());
}
return conn;
答案 0 :(得分:2)
在初始化之前使用上下文。在您的类构造函数中,将context作为参数,然后初始化您的首选项Object。
答案 1 :(得分:2)
您需要初始化您的上下文变量。一种方法是通过在ConnectionClass中定义构造函数将上下文变量从活动类传递给此非活动类
public ConnectionClass (Context context)
{
this.context = context;
}
无论您要在何处实例化此类,都要通过从调用类传递上下文来实例化它。
例如,如果要从活动类中实例化,则可以通过
执行此操作ConnectionClass conn = new ConnectionClass(MyActivity.this.getApplicationContext());
答案 2 :(得分:0)
您必须初始化上下文。
在构造函数中获取上下文:
Context context;
private SharedPreferences setingPreferences;
public ConnectionClass(Context context){
this.context = context;
}
public Connection CONN() {
setingPreferences = context.getSharedPreferences("Settings", Activity.MODE_PRIVATE);
ip = setingPreferences.getString("server", "");
...
或者您可以直接在您调用的方法上获取上下文:
private SharedPreferences setingPreferences;
public Connection CONN(Context context) {
setingPreferences = context.getSharedPreferences("Settings", Activity.MODE_PRIVATE);
ip = setingPreferences.getString("server", "");
...