简体   繁体   English

如何在 Java 中使用 androidx.lifecycle.ViewModelProvider

[英]How to use the androidx.lifecycle.ViewModelProvider in Java

I'm recently learning about the architectural components and was following the old tutorial where they used the old method:我最近正在学习架构组件,并且正在学习他们使用旧方法的旧教程:

mainActivityViewModel =
    new ViewModelProvider(this).get(MainActivityViewModel.class);

But in the documentation for the ViewModelProvider, the only constructors available are ViewModelProvider(ViewModelStoreOwner, Factory) & ViewModelProvider(ViewModelStore, Factory) .但是在 ViewModelProvider 的文档中,唯一可用的构造函数是ViewModelProvider(ViewModelStoreOwner, Factory)ViewModelProvider(ViewModelStore, Factory)

So I did something like this but I'm not sure what to do in the overridden method and it currently returns null that crashes the program.所以我做了这样的事情,但我不确定在重写的方法中做什么,它目前返回 null 导致程序崩溃。

public class MainActivity extends AppCompatActivity {
    private NoteViewModel noteViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        noteViewModel = new ViewModelProvider(this, new ViewModelProvider.Factory() {
            @NonNull
            @Override
            public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
                return null;
            }
        }).get(NoteViewModel.class);

        noteViewModel.getAllNotes().observe(this, new Observer<List<NoteEntity>>() {
            @Override
            public void onChanged(List<NoteEntity> noteEntities) {
                Toast.makeText(MainActivity.this,"Changed",Toast.LENGTH_LONG).show();
            }
        });
    }
}

Is my approach correct?我的方法正确吗? I'm absolutely lost right now.我现在完全迷失了。 What am I supposed to return from the overridden method?我应该从重写的方法返回什么?

Use this用这个

noteViewModel = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(NoteViewModel.class;

We use custom factory, when we pass param to the constructor of ViewModel (apart from Application param).我们使用自定义工厂,当我们将 param 传递给 ViewModel 的构造函数时(除了 Application param)。

and gradle dependency in case,和 gradle 依赖,以防万一,

def lifecycle_version = "2.2.0"

    // LiveData
    implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
    //
    implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
    // ViewModel
    implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"

First you need to initialize viewmodel in activity class like :首先,您需要在活动类中初始化视图模型,例如:

noteViewModel = ViewModelProvider(this).get(NoteViewModel.class);

In NoteViewModel.javaNoteViewModel.java

You need to define livedata variable for storing updated data provided by model and update post to view model您需要定义 livedata 变量来存储模型提供的更新数据和更新帖子以查看模型

NoteViewModel.java file look like : NoteViewModel.java 文件如下所示:

public class NoteViewModel extends AndroidViewModel {
    AppRepository appRepository;
    MediatorLiveData<List<NoteEntity>> mediatorData;
   
    public NoteViewModel (@NonNull Application application) {
        super(application);
        mediatorData=new MediatorLiveData<>();
        appRepository=new AppRepository((MyApplication).apiService, application.retrofit);

    }

    public MediatorLiveData<List<NoteEntity>> getMediatorLiveData() {
        return mediatorVideoData;
    }

   

    public void getNoteEntry()
    {
        try {

            mediatorData.addSource(appRepository.getNoteEntry(), new Observer<List<NoteEntity>>() {
                @Override
                public void onChanged(@Nullable List<NoteEntity> data) {
                    mediatorData.postValue(data);
                }
            });
        }catch (Exception e)
        {

        }
    }

   
}

In onCreate() of Mainactivity register observer like and call the API from view model likeMainactivity onCreate()中注册观察者之类的,并从视图模型中调用 API 之类的

 noteViewModel.getMediatorLiveData().observe(this, new Observer<List<NoteEntity>>() {
            @Override
            public void onChanged(List<NoteEntity> noteEntities) {
                Toast.makeText(MainActivity.this,"Changed",Toast.LENGTH_LONG).show();
            }
        });

  noteViewModel.getNoteEntry();

AppRepository.java file look like AppRepository.java 文件看起来像

class AppRepository() {
ApiService apiService;
Retrofit retrofit;
public AppRepository(ApiService apiService ,Retrofit retrofit){
 this.apiService = apiService;
 this.retrofit = retrofit;
}

    public MediatorLiveData<List<NoteEntity>>  getNotes() {

        MediatorLiveData<List<NoteEntity>> data = new MediatorLiveData<List<NoteEntity>>()
       
        apiService.getNotes()
            .enqueue(new Callback<List<NoteEntity>> {

                @Override 
                void onResponse(
                    Call<List<NoteEntity>> call,
                    Response<List<NoteEntity>> response
                ) {
                    if (response.isSuccessful()) {
                        if(response.body()!=null){
                        data.postValue(response.body()); //successfull data
                         }else{
                         data.postValue(null); //error
                         }
                        
                    } else {
                        data.postValue(null); //error
                    }
                }
                 @Override
                fun onFailure(
                    Call<List<NoteEntity>> call,
                    Throwable t
                ) {
                     data.postValue(null); //error 
                }
            })

        return data;
    }
}

Kotlin Code.科特林代码。

In build.gradle add在 build.gradle 添加

implementation "androidx.activity:activity-ktx:1.1.0"

then然后

val noteViewModel by viewModels<NoteViewModel>()

Figured it out after 4 hours. 4小时后搞定。

noteViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(NoteViewModel.class);

Also these dependencies should be added to the gradle file.这些依赖项也应该添加到 gradle 文件中。

    def room_version = "2.2.5"
    def lifecycle_version = "2.2.0"

    implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
// LiveData
    implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
    annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"

    implementation "androidx.room:room-runtime:$room_version"
    annotationProcessor "androidx.room:room-compiler:$room_version"

Not sure if the error was caused because I missed the annotation dependency.不确定错误是否是因为我错过了注释依赖。 But everything works now.但现在一切正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ViewModelProvider.of 和 ViewModelProvider 在 Android Java 中均已弃用 - ViewModelProvider.of and ViewModelProvider both are deprecated in Android Java 如何使用 Androidx 的 PreferenceScreen - How to use PreferenceScreen of Androidx 如何修复 BroadcastReceiver 中的 [找到:'android.content.Context',必需:'androidx.lifecycle.LifecycleOwner']? - How to fix [Found: 'android.content.Context', required: 'androidx.lifecycle.LifecycleOwner' ] in BroadcastReceiver? 在 Android 中,如何在单独的文件中获取 OnItemSelectedListener 中的 viewmodelprovider? - In Android, how to get viewmodelprovider in OnItemSelectedListener in separate file? 如何在 java 中获取和更新 azure 生命周期规则 - How to get and update azure lifecycle rules in java 什么是生命周期观察者以及如何正确使用它? - What is lifecycle observer and how to use it correctly? 使用Android上的Dagger和Java,ViewModelProvider.Factory在片段上保持为空 - ViewModelProvider.Factory remains null on fragment using Dagger and Java on Android 如何使用 Java 修复 AndroidX 中 Mapbox 9.5.0 未解析的导入 - How to fix unresolved imports for Mapbox 9.5.0 in AndroidX using Java 如何在一个项目中同时使用 Androidx 库和支持库? - How to use both Androidx libraries and support libraries in one project? 让javac使用androidx - Get javac to use androidx
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM