毕设博客(九)

立即学习:Android开发教程(2019最新版,使用JetPack)_哔哩哔哩_bilibili 

Android ViewModel:能访问SharedPreferences的ViewModel

1、先进行UI界面设计:

毕设博客(九)_第1张图片

 

2、在string.xlm中添加资源:


    ViewModelShp
     + 
     - 
    DATA_KEY
    SHP_NAME

3、创建一个MyViewModel类,用SavedStateHandle类型的handle来保存数据:

public class MyViewModel extends AndroidViewModel {
    SavedStateHandle handle;
    String key = getApplication().getResources().getString(R.string.data_key);
    String shpName = getApplication().getResources().getString(R.string.shp_name);
    public MyViewModel(@NonNull Application application,SavedStateHandle handle) {
        super(application);
        this.handle = handle;
        if(!handle.contains(key)){
            load();
        }
    }
    public LiveDatagetNumber(){
        return handle.getLiveData(key);
    }
    public void load(){
        SharedPreferences shp = getApplication().getSharedPreferences(shpName,Context.MODE_PRIVATE);
        int x = shp.getInt(key,0);
        handle.set(key,x);
    }
    public void save(){
        SharedPreferences shp = getApplication().getSharedPreferences(shpName,Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = shp.edit();
        editor.putInt(key,getNumber().getValue());
        editor.apply();
    }
    public void add(int x){
        handle.set(key,getNumber().getValue() + x);
        //save();
    }
}

4、在mainactivity中实例化和绑定参数:

public class MainActivity extends AppCompatActivity {
    MyViewModel myViewModel;
    ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_main);
        myViewModel = new ViewModelProvider(this, new SavedStateViewModelFactory(getApplication(),this)).get(MyViewModel.class);
        binding.setData(myViewModel);
        binding.setLifecycleOwner(this);
    }
    @Override
    protected void onPause(){
        super.onPause();
        myViewModel.save();
    }
}

以下这句可能会有报错,原因是没有添加依赖

myViewModel = new ViewModelProvider(this, new SavedStateViewModelFactory(getApplication(),this)).get(MyViewModel.class);

需要在build.gradle中添加:

...

android {
    ...
        buildFeatures{
            dataBinding = true
        }
    }

...

dependencies {

    ...
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-savedstate:1.0.0-alpha01'
}

5、最后运行程序,结果如图所示:

毕设博客(九)_第2张图片

 

此时,若是退出重进或是重启模拟器,数据依然会保存下来:

 毕设博客(九)_第3张图片

你可能感兴趣的:(毕设,android,webview,java)