java - AppCompatActivity 未观察到 ViewModel

标签 java android gradle viewmodel android-architecture-components

我尝试在我的 EarthquakeActivity 中一起使用 ViewModel,但我不断收到此错误:

Wrong 1st argument type. Found: 'com.example.android.quakereport.EarthquakeActivity', required: 'androidx.lifecycle.LifecycleOwner'

这是我尝试做的事情

mainViewModel.getEarthquakeData().observe(this, new Observer<List<Earthquake>>() {
        @Override
        public void onChanged(List<Earthquake> earthquakes) {
                // do something
        }
    });

作为 Activity 的 this 返回错误。

我读到here AppCompatActivity 已经扩展了 LifecycleOwner,这正是我正在使用的。这是怎么回事?其他所有教程都没有这个问题。

我的EarthquakeActivity.java:

package com.example.android.quakereport;

import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

import POJO.Earthquake;
import POJO.RootEarthquakeResponse;
import androidx.lifecycle.Observer;
import retrofit2.Call;


public class EarthquakeActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;
    private LinearLayoutManager  layoutManager;

    public static final String LOG_TAG = EarthquakeActivity.class.getName();

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

        // Create a fake list of earthquake locations.
        final ArrayList<Earthquake> earthquakes = getEarthquakes();

        setupRecyclerView(earthquakes); // set up recycler view

        MainViewModel mainViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
        mainViewModel.getEarthquakeData().observe(this, new Observer<List<Earthquake>>() {
            @Override
            public void onChanged(List<Earthquake> earthquakes) {
                    // do something
            }
        });

    }

    private void setupRecyclerView(ArrayList<Earthquake> earthquakes){
        // set up recyclerview
    }
}

我的MainViewModel:

package com.example.android.quakereport;

import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

import POJO.Earthquake;
import POJO.Feature;
import POJO.RootEarthquakeResponse;
import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainViewModel extends AndroidViewModel {

    private MutableLiveData<List<Earthquake>> earthquakeLiveData;
    private String LOG_TAG = MainViewModel.class.getName();

    public MainViewModel(@NonNull Application application) {
        super(application);
//        earthquakeLiveData = new EarthquakeLiveData();
    }

    public LiveData<List<Earthquake>> getEarthquakeData(){
        if (earthquakeLiveData == null){
            earthquakeLiveData = new MutableLiveData<>();
            loadEarthquakes();
        }

        return earthquakeLiveData;
    }

    private void loadEarthquakes(){
        EarthquakeService earthquakeService = EarthquakeServiceGenerator.createService(EarthquakeService.class);

        Call<RootEarthquakeResponse> call = earthquakeService.getEarthquakes("geojson", "time", 6, 10);

        call.enqueue(new Callback<RootEarthquakeResponse>() {
            @Override
            public void onResponse(Call<RootEarthquakeResponse> call, Response<RootEarthquakeResponse> response) {
                List<Earthquake> earthquakes = new ArrayList<>();
                for (Feature f: response.body().getFeatures()) {
                    earthquakes.add(f.getEarthquake());
                }

                earthquakeLiveData.setValue(earthquakes);
                Log.d(LOG_TAG, "Successful!");
                Log.d(LOG_TAG, response.body().toString());
            }

            @Override
            public void onFailure(Call<RootEarthquakeResponse> call, Throwable t) {
                Log.e(LOG_TAG, call.request().toString()); // check request if failed
                Log.e(LOG_TAG, t.toString()); // check error
            }
        });
    }
}

这是我的 gradle 依赖项:

implementation fileTree(dir: 'libs', include: ['*.jar'])
testImplementation 'junit:junit:4.12'
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:recyclerview-v7:26.1.0'
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'

implementation "androidx.lifecycle:lifecycle-viewmodel:2.0.0" // use -ktx for Kotlin
// alternatively - just LiveData
implementation "androidx.lifecycle:lifecycle-livedata:2.0.0"
implementation "android.arch.lifecycle:extensions:1.1.1"

我是否需要处理覆盖生命周期的问题,或者我的依赖项是否有问题?

最佳答案

您正在使用 AndroidX 库中的 ViewModel,并且还使用 AppCompatActivity 的支持库。

将您的支持库迁移到 AndroidX 以解决您的问题。

关于java - AppCompatActivity 未观察到 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53739995/

相关文章:

android-studio - 如何依赖另一个项目的androidTestCompile?

shell - 从 Gradle 脚本运行 shell 命令

java - Kraken API在Java中的实现

java - 图标处理抛出 NullPointerException

javascript - 地理定位 HTML5 API enableHighAccuracy :True does not force GPS to turn on om Android devices

c# - 填充编辑文本后启用按钮

android - gradle build错误:没有这样的属性:COMPILE SDK for class:org.gradle.api.Project

java - Java 中最好的 "closable TabbedPane"组件是什么?

java - Phaser 类别和分层

android - 如何解决以编程方式从 wifi 出来后在 android 中丢失的移动数据连接(2G/3G/EDGE/GPRS)?