这是我的连接类,我真正想要的是如何在SharedPreference中获取数据并将其设置到我的String IPadd中。
public class ConnectionClass {
String IPadd ="192.168.254.117";
String classs = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://"+IPadd+"/dblight";
String un = "light";
String password = "12345";
@SuppressLint("NewApi")
public Connection CONN() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String ConnURL = null;
try {
Class.forName(classs);
conn = DriverManager.getConnection(url, un, 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;
}
}
我的SharedPreference
代码来设置数据
try {
String strIP = ip.getText().toString();
SharedPreferences sharedPref = getSharedPreferences(Filename, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("name", strIP);
editor.commit();
Toast.makeText(getBaseContext(), "IP Saved Successfully", Toast.LENGTH_LONG).show();
}
catch (Exception ex)
{
}
答案 0 :(得分:0)
1)添加一个应用程序类
public class MyApplication extends Application {
private static final String TAG = MyApplication.class.getSimpleName();
private static MyApplication sInstance;
@Nullable
public static Context getAppContext() {
return sInstance;
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate() called");
sInstance = this;
}
}
2)将android:name行添加到清单应用程序标签中
<application
android:name="your.package.name.MyApplication"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
3)在ConnectionClass类中执行此操作
IPadd = MyApplication.getAppContext().getSharedPreferences(Filename,Context.MODE_PRIVATE).getString("name","defaultValue");