Caused by: java.lang.RuntimeException: Cannot create an instance of class com.example.lifecycleobserver.MyLocationListener
at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:223)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:278)
at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:112)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
at com.example.lifecycleobserver.MainActivity.onCreate(MainActivity.java:18)
at android.app.Activity.performCreate(Activity.java:7009)
at android.app.Activity.performCreate(Activity.java:7000)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.IllegalAccessException: java.lang.Class<com.example.lifecycleobserver.MyLocationListener> is not accessible from java.lang.Class<androidx.lifecycle.ViewModelProvider$NewInstanceFactory>
سلام خسته نباشید
ببخشید من به این مشکل برخوردم، این هم کد منه!
راه حلهای تو اینترنت رو پیدا کردم ولی هیچکدومش مشکل رو حل نکرد
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyLocationListener myLocationListener = new ViewModelProvider(this).get(MyLocationListener.class);
Log.i(TAG, "onCreate: " + myLocationListener.getStringMutableLiveData().getValue());
myLocationListener.getStringMutableLiveData().observe(this, new Observer<String>() {
@Override
public void onChanged(String s) {
Log.i(TAG, "onChanged: " + s);
}
});
}
}
class MyLocationListener extends ViewModel {
private Timer timer = new Timer();
private MutableLiveData<String> stringMutableLiveData = new MutableLiveData<>();
public MyLocationListener() {
timer.schedule(new TimerTask() {
@Override
public void run() {
stringMutableLiveData.postValue("Time : " + System.currentTimeMillis());
}
}, 0, 1000);
}
public LiveData<String> getStringMutableLiveData() {
return stringMutableLiveData;
}
@Override
protected void onCleared() {
super.onCleared();
timer.cancel();
timer.purge();
timer = null;
}
}