gpt4 book ai didi

java - 安卓 : Getting error "cannot resolve getSharedPreferences(java.lang.String, int)"

转载 作者:行者123 更新时间:2023-12-02 04:09:41 25 4
gpt4 key购买 nike

我尝试访问非 Activity 类中的 SharedPreferences,但总是收到此错误 cannot parse getSharedPreferences(java.lang.String, int) 。但是当我在正常 Activity 类中使用 getSharedPreferences 时,我不会收到此错误。

有人知道如何解决这个问题吗?

这是我的代码:

public class ConnectionClass {

SharedPreferences pref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
String ip = pref.getString("serverIP", "");

// String ip = "";
// String ip = server_IP;
String classDriver = "net.sourceforge.jtds.jdbc.Driver";
String db = "passoDB";
String un = "sa";
String password = "dhen1234";

@SuppressLint("NewApi")
public Connection CONN(Context context) {

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String ConnURL = null;
try {
Class.forName(classDriver);
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;
}
}

最佳答案

是的,正如西蒙所说,要访问共享首选项,您需要上下文,因此为了使该代码正常工作,我将添加这一行。

    public class ConnectionClass {


String classDriver = "net.sourceforge.jtds.jdbc.Driver";
String db = "passoDB";
String un = "sa";
String password = "dhen1234";


String ip = "";


public ConnectionClass(Context context){
SharedPreferences prefs = context.getSharedPreferences("MyPrefs", context.MODE_PRIVATE);
ip = prefs.getString("serverIP", "");

}


@SuppressLint("NewApi")
public Connection CONN(Context context) {

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String ConnURL = null;
try {
Class.forName(classDriver);
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;
}
}

我没有正确缩进,希望有帮助。

在调用类时,您应该这样调用:

ConnectionClass connectionClass = new ConnectionClass(YourActivity.this);//if in activity

ConnectionClass connectionClass = new ConnectionClass(getActivity());//if in fragment

关于java - 安卓 : Getting error "cannot resolve getSharedPreferences(java.lang.String, int)",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33911033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com