初步了解AndroidViewModel

ViewModel与SharedPreferences


本文为学习类文档,通过学习B站up主longway777的视频,如有侵权,请联系博主进行删除

ViewModel与SharedPreferences的关系

在学习了ViewModel之后,我们知道了其功能是最大限度的保存系统的数据状态(系统配置改变,后台无声杀死程序的情况下都能保存数据),然而在系统主动退出或者是系统重新启动时,由于ViewModel也被重置,数据不再保留造成数据丢失。正因如此,引入SharedPreferences来进行数据的永久保存,ViewModel的数据也得到恢复,界面上的数据得到恢复。
在这里插入图片描述
使用SharedPreferences需要使用Context来指向应用程序
在这里插入图片描述

  1. 添加依赖
android {
...
    dataBinding.enabled true
}
dependencies {
...
    implementation 'androidx.lifecycle:lifecycle-viewmodel-savedstate:1.0.0'
}

Sync
2. 要想使创建的MyViewModel类访问全局,可以使用Application或者Context(两者是继承关系)再在controller中实现传递

package com.example.viewmodelshp;
import android.app.Application;
import android.content.Context;
import androidx.lifecycle.ViewModel;

public class MyViewModel extends ViewModel {
    //Application application;//或者用Context传递参数
    Context context;
    public void fun(){
        context.getSharedPreferences();//实现对系统的数据进行访问
    }
}
package com.example.viewmodelshp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
    MyViewModel myViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //myViewModel.application = getApplication();//传递过去所需参数,或者用Context
        myViewModel.context = getApplicationContext();
    }
}
  1. 也可以使用简便方法:利用AndroidViewModel
    将ViewModel的继承类由ViewModel改变为AndroidViewModel,其为ViewModel的一个子类,好处在于内部有直接对Context访问的工具
    缺少缺省参数
    对于缺省的参数根据代码提示创建即可:在这里插入图片描述
    并在MyViewModel中带入第二个参数savedStateHandle
public MyViewModel(@NonNull Application application, SavedStateHandle handle) {
        super(application);
        this.handle = handle;
        if (!handle.contains(key)) {
            load();
        }
    }

完善代码以便于完成数据的更新操作:

package com.example.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;
        if (!handle.contains(key)) {
            load();
        }
    }

    public LiveData<Integer> getNumber() { //声明为共有类用以xml中的使用
        return handle.getLiveData(key);
    }

    private void load() {
        SharedPreferences sharedPreferences = getApplication().getSharedPreferences(shpName, Context.MODE_PRIVATE);
        int x = sharedPreferences.getInt(key, 0);
        handle.set(key, x);//读取
    }

    void save() {
        SharedPreferences sharedPreferences = getApplication().getSharedPreferences(shpName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt(key, getNumber().getValue() == null ? 0 : getNumber().getValue());//warning中说没判空,但是逻辑中我们已经会显示为0。消除警告方法:
        editor.apply();
    }

    public void add(int x) {
        handle.set(key, getNumber().getValue() == null ? 0 : getNumber().getValue() + x);
        //保存法一,但是保存开销大占用内存极高
        //save();
    }
}

MainActivity中添加代码:

package com.example.viewmodelshp;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.SavedStateViewModelFactory;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;

import com.example.viewmodelshp.databinding.ActivityMainBinding;

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        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);
    }

    //法二,在onPause()中保存
    @Override
    protected void onPause() {
        super.onPause();
        myViewModel.save();
    }
}

更改xml格式为databinding layout

<?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.example.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="36sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.285"
            tools:text="100" />

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/button_plus"
            android:onClick="@{()->data.add(1)}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.2"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.6" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/button_minus"
            android:onClick="@{()->data.add(-1)}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.8"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.6" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

运行后能对数据进行变动,后台杀死与重启设备依然能够保存:
在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值