结合SharedPreferences实现保存数据
MainActivity.java
package com.tjjingpan.study.viewmodelshp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.SavedStateViewModelFactory;
import android.os.Bundle;
import com.tjjingpan.study.viewmodelshp.databinding.ActivityMainBinding;
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 MyViewModel();
//myViewModel.application= getApplication();
//myViewModel.context = getApplicationContext();
SavedStateViewModelFactory savedStateViewModelFactory = new SavedStateViewModelFactory(getApplication(), this);
myViewModel = savedStateViewModelFactory.create(MyViewModel.class);
binding.setData(myViewModel);
binding.setLifecycleOwner(this);
}
@Override
protected void onPause() {
super.onPause();
myViewModel.save();
}
}
MyViewModel.java
package com.tjjingpan.study.viewmodelshp;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.SavedStateHandle;
public class MyViewModel extends AndroidViewModel {
private SavedStateHandle handle;
private String key = getApplication().getResources().getString(R.string.data_key);
private String shpName = getApplication().getResources().getString(R.string.shp_name);
public MyViewModel(@NonNull Application application, SavedStateHandle handle) {
super(application);
this.handle = handle;
//判断handle是否存在需要的数据,不存在,从SharedPreferences加载
if (!handle.contains(key)) {
load();
}
}
public LiveData<Integer> getNumber() {
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() == null ? 0 : getNumber().getValue());
editor.apply();
}
public void add(int x) {
handle.set(key, getNumber().getValue() == null ? 0 : getNumber().getValue() + x);
//save();
}
//Application application;
// Context context;
//
// void foo(){
// }
}
布局文件
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="data"
type="com.tjjingpan.study.viewmodelshp.MyViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{String.valueOf(data.getNumber())}"
android:textSize="34sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.07999998"/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="@{()-> data.add(1)}"
android:text="@string/button_plus"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.241"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="@{()-> data.add(-1)}"
android:text="@string/button_minute"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.678"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
构建文件
plugins {
id 'com.android.application'
}
android {
namespace 'com.tjjingpan.study.viewmodelshp'
compileSdk 33
defaultConfig {
applicationId "com.tjjingpan.study.viewmodelshp"
minSdk 23
targetSdk 33
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
dataBinding.enabled = true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'androidx.lifecycle:lifecycle-viewmodel-savedstate:2.3.1'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}