// 声明一个共享参数对象
private SharedPreferences shared;
shared = getSharedPreferences("Database", MODE_PRIVATE);
// 获得编辑器对象
SharedPreferences.Editor editor = shared.edit();
// 添加内容
editor.putString("name", "database");
editor.putInt("version", version);
editor.putBoolean("isExist", true);
editor.commit();
在一个Activity里写了SharedPreferences,如果想要在另外一个类里面读取Database.xml 里的version,像这样int version = shared.getInt("version", 0)
,会发现读取不了。
可以自定义一个ContextApplication类继承Application,利用Application操作全局变量,代码如下
import android.app.Application;
import android.content.Context;
/**
* @author wunu
*/
public class ContextApplication extends Application {
private static Context context;
@Override
public void onCreate() {
super.onCreate();
ContextApplication.context = getApplicationContext();
}
public static Context getAppContext(){
return ContextApplication.context;
}
}
在Activity外可以这么调用:
SharedPreferences preferences;
preferences = ContextApplication.getAppContext().getSharedPreferences("Database",0);
int version = preferences.getInt("version", 0);
helper = new PersonSQLiteOpenHelper(getContext(),version);
最后一步,打开AndroidManifest.xml
,给application节点加上name
属性,表示application
的入口代码是ContextApplication.java
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:name=".ContextApplication">
希望能帮到你们,如果你们有更好的方式也可以告诉我