ViewModel没有零参数构造函数错误-即使它具有零参数构造函数

问题描述 投票:0回答:2

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

编辑

我编写了非常简单的测试代码,并得到了相同的错误。这是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中的依赖项:

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更新用户位置,因为我了解这是了解生命周期的最佳方法。我有默认的地图活动...

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

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

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。

 public class LocationViewModel extends ViewModel {
        private LocationLiveData locationLiveData;

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

        public LocationLiveData getLocationLiveData() {
            return locationLiveData;
        }
    }

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

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

我在该行出现错误:

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

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

即使我完全在locationViewModel中取出构造函数,也尝试改为扩展AndroidViewModel,我都会收到此错误。

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

非常感谢您的帮助

java android android-livedata android-viewmodel android-fusedlocation
2个回答
0
投票

任一:

  • MyViewModel移动到单独的Java文件,或

  • 使MyViewModelstatic class

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


0
投票

写作时

public class MainActivity extends AppCompatActivity {

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

这使MyViewModel成为MainActivity的内部类,意味着它隐含了对外部类的引用(根据Java documentation),并且不能与MainActivity分开构造。这实际上意味着在字节码中,即使您不写出该构造函数,其构造函数也始终采用MainActivity的实例。

您可以通过添加static关键字使内部类成为静态嵌套类。这将删除对外部类的隐式引用,并使它类似于任何其他顶级类:

public class MainActivity extends AppCompatActivity {

    public static class MyViewModel extends ViewModel {
       public int scoreTeamA = 0;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.