ViewModel没有零参数构造函数错误-即使它具有零参数构造函数 [英] ViewModel has no zero argument constructor error - even when it has a zero argument constructor

查看:154
本文介绍了ViewModel没有零参数构造函数错误-即使它具有零参数构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Android和Java的新手,正在尝试制作一个基于位置的应用程序.

I'm new to Android and Java and am trying to make a location-based app.

编辑

我编写了非常简单的测试代码,并得到了相同的错误.这是java:

I've made a much, much simpler test code and get the same error. Here's the java:

package com.example.viewmodeltest;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    public class MyViewModel extends ViewModel {
        public int scoreTeamA = 0;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MyViewModel locationViewModel = new ViewModelProvider(this).get(MyViewModel.class);
    }
}

我得到同样的错误.这是我的应用程序级别build.gradle中的依赖项:

I get the same error. Here are the dependencies in my app-level build.gradle:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    //dependencies for ViewModel, LiveData, etc.
    def lifecycle_version = "2.2.0"
    def arch_version = "2.1.0"

    // ViewModel
    implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
    // LiveData
    implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
    // Lifecycles only (without ViewModel or LiveData)
    implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"
    // Saved state module for ViewModel
    implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version"
    // Annotation processor
    annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
}

原始帖子

我正在尝试使用ViewModel和LiveData更新用户位置,因为我了解这是了解生命周期的最佳方法.我有默认的地图活动...

I'm attempting to use ViewModel and LiveData to update the user location as I understand that's the best way to be lifecycle-aware. I have a default maps activity...

public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {...}

扩展LiveData以存储用户位置的类...

A class which extends LiveData to store the user location...

public class LocationLiveData extends LiveData<Location> {
        private final Context context;
        private FusedLocationProviderClient fusedLocationClient;
        private LocationRequest locationRequest;

        public LocationLiveData(Context context) {
            this.context = context;
            this.fusedLocationClient = LocationServices.getFusedLocationProviderClient(context);
        }

        private void setLocationData(Location location) {
            Location value = new Location("SetInternal");
            value.setLatitude(location.getLatitude());
            value.setLongitude(location.getLongitude());
            setValue(value);
        }

        protected void createLocationRequest() {
            LocationRequest locationRequest = LocationRequest.create();
            locationRequest.setInterval(1000);
            locationRequest.setFastestInterval(500);
            locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        }

        private LocationCallback locationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                if (locationResult == null) {
                    return;
                }
                for (Location location : locationResult.getLocations()) {
                    setLocationData(location);
                }
            }
        };

        private void startLocationUpdates() {
            createLocationRequest();
            fusedLocationClient.requestLocationUpdates(locationRequest,
                    locationCallback,
                    Looper.getMainLooper());
        }

        @Override
        protected void onInactive() {
            super.onInactive();
            fusedLocationClient.removeLocationUpdates(locationCallback);
        }

        @Override
        protected void onActive() {
            super.onActive();
            fusedLocationClient.getLastLocation()
                    .addOnSuccessListener(new OnSuccessListener<Location>() {
                        @Override
                        public void onSuccess(Location location) {
                            if (location != null)
                                setValue(location);
                        }
                    });
            startLocationUpdates();
        }
    }

还有一个扩展ViewModel以允许主要活动到达LocationLiveData的类.

And a class which extends ViewModel to allow the main activity to reach the LocationLiveData.

 public class LocationViewModel extends ViewModel {
        private LocationLiveData locationLiveData;

        public LocationViewModel () {
            locationLiveData = new LocationLiveData(getApplicationContext());
        }

        public LocationLiveData getLocationLiveData() {
            return locationLiveData;
        }
    }

然后,当我尝试在onMapReady方法中创建locationViewModel实例时:

Then when I attempt to make an instance of locationViewModel in the onMapReady method:

LocationViewModel locationViewModel = new ViewModelProvider(this).get(LocationViewModel.class);

我在那条线上出现错误:

I get an error on that line:

无法创建com.example.MapsActivity $ LocationViewModel类的实例

Cannot create an instance of class com.example.MapsActivity$LocationViewModel

原因:java.lang.InstantiationException:java.lang.Class没有零参数构造函数

Caused by: java.lang.InstantiationException: java.lang.Class has no zero argument constructor

即使我完全在locationViewModel中删除构造函数,并且尝试改为扩展AndroidViewModel,也会遇到此错误.

I get this error even if I take out the constructor entirely in locationViewModel, and also if I attempt to extend AndroidViewModel instead.

有什么想法吗?我见过其他类似的查询,但答案一直是从构造函数中取出参数-我已经完成了!

Any ideas? I've seen other similar queries but the answer has always been to take arguments out of the constructor - which I've already done!

非常感谢您的帮助

推荐答案

任一:

  • MyViewModel移至单独的Java文件,或

  • Move MyViewModel to a separate Java file, or

使MyViewModel成为static class

现在,您已将MyViewModel定义为MainActivity的内部类.这将不起作用,因为只有MainActivity的实例才能创建MyViewModel的实例.特别是ViewModelProvider无法创建MyViewModel的实例.

Right now, you have defined MyViewModel as an inner class of MainActivity. That will not work, as only an instance of MainActivity can create an instance of MyViewModel. In particular, ViewModelProvider cannot create an instance of MyViewModel.

这篇关于ViewModel没有零参数构造函数错误-即使它具有零参数构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆