I am creating an app to scan a barcode and get that information into a Room Database using Android View Model and LiveData.
Here is the error message
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.davin.scoutingapp2019/com.example.davin.scoutingapp2019.DataDisplay}: java.lang.RuntimeException: Cannot create an instance of class com.example.davin.scoutingapp2019.TeamViewModel
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Caused by: java.lang.RuntimeException: Cannot create an instance of class com.example.davin.scoutingapp2019.TeamViewModel
at android.arch.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:207)
at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:134)
at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:102)
at com.example.davin.scoutingapp2019.DataDisplay.onCreate(DataDisplay.java:30)
at android.app.Activity.performCreate(Activity.java:6672)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
at android.arch.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:199)
at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:134)
at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:102)
at com.example.davin.scoutingapp2019.DataDisplay.onCreate(DataDisplay.java:30)
at android.app.Activity.performCreate(Activity.java:6672)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.example.davin.scoutingapp2019.TeamDAO com.example.davin.scoutingapp2019.TeamsDatabase.teamDAO()' on a null object reference
at com.example.davin.scoutingapp2019.TeamRepository.<init>(TeamRepository.java:15)
at com.example.davin.scoutingapp2019.TeamViewModel.<init>(TeamViewModel.java:15)
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
at android.arch.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:199)
at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:134)
at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:102)
at com.example.davin.scoutingapp2019.DataDisplay.onCreate(DataDisplay.java:30)
at android.app.Activity.performCreate(Activity.java:6672)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
This is the AndroidViewModel class
package com.example.davin.scoutingapp2019;
import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.LiveData;
import java.util.List;
public class TeamViewModel extends AndroidViewModel {
private TeamRepository mRepository;
private LiveData<List<Team>> mAllData;
public TeamViewModel(Application application) {
super(application);
mRepository = new TeamRepository(application);
mAllData = mRepository.getAllWords();
}
public LiveData<List<Team>> getAllTeams() {
return mAllData;
}
public void insert(Team team) {
mRepository.insert(team);
}
}
Here is the class/activity DataDisplay which has an instance of TeamViewModel
package com.example.davin.scoutingapp2019;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import java.util.List;
public class DataDisplay extends AppCompatActivity {
private TeamViewModel teamViewModel;
public static final int NEW_WORD_ACTIVITY_REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_display);
RecyclerView recyclerView = findViewById(R.id.recyclerview);
final TeamListAdapter adapter = new TeamListAdapter(this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
teamViewModel = ViewModelProviders.of(this).get(TeamViewModel.class);
teamViewModel.getAllTeams().observe(this, new Observer<List<Team>>() {
#Override
public void onChanged(#Nullable final List<Team> teams) {
// Update the cached copy of the words in the adapter.
adapter.setTeams(teams);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == NEW_WORD_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
Destring destring=new Destring(data.getStringExtra("str"));
Team newTeam= new Team(destring.getTeamNumber(),destring.getPosition(),destring.getSandstorm("hab line"),destring.getSandstorm("cargo balls"),destring.getSandstorm("cargo hatches"),destring.getSandstorm("rocket balls"),destring.getSandstorm("rocket hatches"),destring.getTeleop("cargo balls"),destring.getTeleop("cargo hatches"),destring.getTeleop("rocket balls"),destring.getTeleop("rocket hatches"),destring.getRocketRole(),destring.getClimberRole(),destring.getOverallRole(),destring.getOtherComments());
teamViewModel.insert(newTeam);
} else {
Toast.makeText(
getApplicationContext(),
R.string.empty_not_saved,
Toast.LENGTH_LONG).show();
}
}
}
This question is similar to another question but I only have one parameter in my constructor for TeamViewModel.
The rest of the code is on github
Thank You
You need to have a factory class for your ViewModel.
public class MyViewModelFactory implements ViewModelProvider.Factory {
private Application mApplication;
private String mParam;
public MyViewModelFactory(Application application, String param) {
mApplication = application;
mParam = param;
}
#Override
public <T extends ViewModel> T create(Class<T> modelClass) {
return (T) new MyViewModel(mApplication, mParam);
}
And when instantiating the view model, you do like this:
MyViewModel myViewModel = new ViewModelProvider(this, new MyViewModelFactory(this.getApplication(), "my awesome param")).get(MyViewModel.class);
orginal answer
Simply type
ViewModelProvider(
this#RecipeListActivity,
ViewModelProvider.AndroidViewModelFactory(this.application)
).get(RecipeListViewModel::class.java)
this problem maybe from other parts
like repository or Room
i just update dependencies
def room_version = "2.2.5"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
I agree with the accepted answer by #AyoubBenzahia in this post that you need a factory class for creating the AndroidViewModel object but you don't need to create a new java class for that.
You can do it in a simpler version as well.
ViewModelProvider.AndroidViewModelFactory factory = new ViewModelProvider.AndroidViewModelFactory(this.getApplication());
teamViewModel = ViewModelProviders.of(this, factory).get(TeamViewModel.class);
Related
I am learning android programming. thank you for your help.
the last time i run my app in android studio, it run completely and without errors. the next day i run the app did not give any error but the program did not run and showed in the emulator: "unfortunately, My Application1 has stopped" and in the run part in android studio i encountered these cases:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication1, PID: 1701
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.myapplication1/com.example.myapplication1.MainActivity}: java.lang.InstantiationException: java.lang.Class<com.example.myapplication1.MainActivity> cannot be instantiated
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.InstantiationException: java.lang.Class<com.example.myapplication1.MainActivity> cannot be instantiated
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
its code:
package com.example.myapplication1;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public abstract class MainActivity extends AppCompatActivity implements View.OnClickListener, TextWatcher {
private static final String TAG= "MainActivity";
Button btn1, btn2;
ImageView imageView;
#SuppressLint("ResourceAsColor")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1=findViewById(R.id.firstButton);
btn2=findViewById(R.id.secondButton);
imageView=findViewById(R.id.imageView);
btn1.setText(R.string.btn);
btn1.setTextColor(getResources().getColor(R.color.purple_700));
btn1.setBackgroundColor(getResources().getColor(R.color.teal_700));
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "click btn1");
}
});
btn2.setOnClickListener(this);
imageView.setScaleType(ImageView.ScaleType.FIT_START);
Toast.makeText(this,"salam",Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View v) {
Log.d(TAG, "click btn2");
}
}
where is the problem and is there a solution?
I am new to Android in-app purchases. I have followed the official documentation and I can't go beyond building the BillingClient as app crashes when it tries to build the BillingClient. Any help or any reference to a android in-app purchases in Java is much appreciated. My MainActivity.java codes is as follows:
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.PurchasesUpdatedListener;
import java.util.List;
public class MainActivity extends AppCompatActivity{
private PurchasesUpdatedListener purchaseUpdateListener = new PurchasesUpdatedListener() {
#Override
public void onPurchasesUpdated(BillingResult billingResult, List<Purchase> purchases) {
// To be implemented in a later section.
}
};
private BillingClient billingClient = BillingClient.newBuilder(MainActivity.this)
.setListener(purchaseUpdateListener)
.enablePendingPurchases()
.build();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Crash Log is as follows:
2020-07-07 01:19:40.667 27956-27956/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.js.bs, PID: 27956
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.js.bs/com.js.bs.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3272)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3500)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2049)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:122)
at com.android.billingclient.api.BillingClientImpl.initialize(com.android.billingclient:billing##3.0.0:26)
at com.android.billingclient.api.BillingClientImpl.<init>(com.android.billingclient:billing##3.0.0:13)
at com.android.billingclient.api.BillingClientImpl.<init>(com.android.billingclient:billing##3.0.0:1)
at com.android.billingclient.api.BillingClient$Builder.build(com.android.billingclient:billing##3.0.0:14)
at com.js.bs.MainActivity.<init>(MainActivity.java:31)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:41)
at android.app.Instrumentation.newActivity(Instrumentation.java:1253)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3260)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3500)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2049)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)
2020-07-07 01:19:41.044 27956-27956/? I/Process: Sending signal. PID: 27956 SIG: 9
Please change the billingClient object creation as below. While creating this object from outside the context may be null, so crashing. Move the object creation to onCreate() method of the activity.
private BillingClient billingClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
billingClient = BillingClient.newBuilder(this)
.setListener(purchaseUpdateListener)
.enablePendingPurchases()
.build();
}
I posted this question yesterday but I think that I might not have been very clear with the doubt.
In the line where I use ViewModel to link up with MainActivity using the ViewProvider, the code returns the Runtime Exception. Additionally, the code also returns the message "Cannot create an instance of class at com.example.viewmodelpractice.ViewModelStorage".
The error message points specifically at this line:
viewModelStorage = new ViewModelProvider(this).get(ViewModelStorage.class);
Here are the rest of the classes:
ViewModelStorage.java
package com.example.viewmodelpractice;
import androidx.lifecycle.ViewModel;
class ViewModelStorage extends ViewModel {
private String name;
private String age;
String getName() {
return name;
}
void setName(String name){
this.name = name;
}
String getAge() {
return age;
}
void setAge(String age){
this.age = age;
}
}
Main Activity.java
package com.example.viewmodelpractice;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private EditText nameEditText;
private EditText ageEditText;
private TextView resultTextView;
private ViewModelStorage viewModelStorage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameEditText = findViewById(R.id.name_notice_editText);
ageEditText = findViewById(R.id.age_notice_editText);
resultTextView = findViewById(R.id.result_textView);
viewModelStorage = new ViewModelProvider(this).get(ViewModelStorage.class);
storeDataMethod();
}
private void storeDataMethod() {
viewModelStorage.setName(nameEditText.getText().toString());
viewModelStorage.setAge(ageEditText.getText().toString());
getDataMethod();
}
private void getDataMethod() {
resultTextView.setText(("Hey there, ").concat(viewModelStorage.getName().concat(". You are ").concat(viewModelStorage.getAge()).concat(" years old.")));
}
}
Error Message
2020-05-04 12:06:38.744 20688-20688/com.example.viewmodelpractice E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.viewmodelpractice, PID: 20688
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.viewmodelpractice/com.example.viewmodelpractice.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.example.viewmodelpractice.ViewModelStorage
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2946)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6823)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: java.lang.RuntimeException: Cannot create an instance of class com.example.viewmodelpractice.ViewModelStorage
at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:223)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
at com.example.viewmodelpractice.MainActivity.onCreate(MainActivity.java:27)
at android.app.Activity.performCreate(Activity.java:7224)
at android.app.Activity.performCreate(Activity.java:7213)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2926)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6823)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: java.lang.IllegalAccessException: java.lang.Class<com.example.viewmodelpractice.ViewModelStorage> is not accessible from java.lang.Class<androidx.lifecycle.ViewModelProvider$NewInstanceFactory>
at java.lang.Class.newInstance(Native Method)
at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:219)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
at com.example.viewmodelpractice.MainActivity.onCreate(MainActivity.java:27)
at android.app.Activity.performCreate(Activity.java:7224)
at android.app.Activity.performCreate(Activity.java:7213)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2926)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6823)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Instead of this:
class ViewModelStorage extends ViewModel {
Make it like this:
public class ViewModelStorage extends ViewModel {
Due to this, you are getting the IllegalAccessException!
In my MVVM app, I am extending AndroidViewModel and through a Repository class, I am trying to get an instance of a DB (in a separate abstract class that extends the RoomDatabase superclass). I call the ViewModel from the MainActivity class by the ViewModelProviders method. I get the following error:
Here is the whole stack trace of the exception:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.roomlistingapllicate, PID: 31766
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.roomlistingapllicate/com.example.roomlistingapllicate.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.example.roomlistingapllicate.NOtesViewModel
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2572)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2654)
at android.app.ActivityThread.access$900(ActivityThread.java:175)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5728)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
Caused by: java.lang.RuntimeException: Cannot create an instance of class com.example.roomlistingapllicate.NOtesViewModel
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:238)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:164)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:130)
at com.example.roomlistingapllicate.MainActivity.onCreate(MainActivity.java:19)
at android.app.Activity.performCreate(Activity.java:6309)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2519)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2654)
at android.app.ActivityThread.access$900(ActivityThread.java:175)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5728)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance(Native Method)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:230)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:164)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:130)
at com.example.roomlistingapllicate.MainActivity.onCreate(MainActivity.java:19)
at android.app.Activity.performCreate(Activity.java:6309)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2519)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2654)
at android.app.ActivityThread.access$900(ActivityThread.java:175)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5728)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
Caused by: java.lang.RuntimeException: cannot find implementation for com.example.roomlistingapllicate.NotesDatabase. NotesDatabase_Impl does not exist
at androidx.room.Room.getGeneratedImplementation(Room.java:94)
at androidx.room.RoomDatabase$Builder.build(RoomDatabase.java:851)
at com.example.roomlistingapllicate.NotesDatabase.getInstance(NotesDatabase.java:23)
at com.example.roomlistingapllicate.NoteRepository.<init>(NoteRepository.java:15)
at com.example.roomlistingapllicate.NOtesViewModel.<init>(NOtesViewModel.java:15)
at java.lang.reflect.Constructor.newInstance(Native Method)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:230)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:164)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:130)
at com.example.roomlistingapllicate.MainActivity.onCreate(MainActivity.java:19)
at android.app.Activity.performCreate(Activity.java:6309)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2519)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2654)
at android.app.ActivityThread.access$900(ActivityThread.java:175)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5728)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
I am working on the AndroidX arch. Here are some parts of the code I think the issue hides in:
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProviders;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
private NOtesViewModel nOtesViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nOtesViewModel = ViewModelProviders.of(this).get(NOtesViewModel.class);
}
}
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import java.util.List;
public class NOtesViewModel extends AndroidViewModel {
private NoteRepository noteRepository;
private LiveData<List<Note>> allNotes;
public NOtesViewModel(#NonNull Application application) {
super(application);
noteRepository = new NoteRepository(application);
allNotes = noteRepository.getAllNotes();
}
import android.app.Application;
import android.os.AsyncTask;
import androidx.lifecycle.LiveData;
import java.util.List;
public class NoteRepository {
private NoteDAO noteDAO;
private LiveData<List<Note>> allNotes;
public NoteRepository(Application application) {
NotesDatabase notesDatabase = NotesDatabase.getInstance(application.getApplicationContext());
noteDAO = notesDatabase.noteDAO();
allNotes = noteDAO.getAllNotes();
}
import android.content.Context;
import android.os.AsyncTask;
import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteDatabase;
#Database(entities = {Note.class}, version = 1)
public abstract class NotesDatabase extends RoomDatabase {
private static NotesDatabase instance;
public abstract NoteDAO noteDAO();
public static synchronized NotesDatabase getInstance(Context context) {
if (instance == null) {
instance = Room.databaseBuilder(context.getApplicationContext(), NotesDatabase.class,
"note_database").fallbackToDestructiveMigration()
.addCallback(roomCallback)
.build();
}
return instance;
}
The stacktrace says you're getting this error because Room can not find an implementation of your Notes Database abstract class.
Please make sure you have added the room annotation processor dependency in your app's build.gradle file.
annotationProcessor "androidx.room:room-compiler:$room_version"
Edit: If you are using Kotlin, use kapt instead of annotationProcessor, and make sure to add apply plugin: 'kotlin-kapt' at top of the app's build.gradle file.
Ok, so I'm trying to inflate a DialogPreference in a PreferenceFragment which is nested in an AppCompatActivity. Whenever I try to go to the Activity hosting said PreferenceFragment, this error occurs.
01-14 09:40:37.002 29689-29689/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.santinocampos.android.count, PID: 29689
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.santinocampos.android.count/com.myname.android.count.Settings.SettingsActivity}: android.view.InflateException: Binary XML file line #16: Binary XML file line #4: Error inflating class (not found)com.santinocampos.android.count.Settings.OptionDialogPreference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.view.InflateException: Binary XML file line #16: Binary XML file line #4: Error inflating class (not found)com.santinocampos.android.count.Settings.OptionDialogPreference
at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:276)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
at com.santinocampos.android.count.Settings.SettingsActivity.onCreate(SettingsActivity.java:20)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.view.InflateException: Binary XML file line #4: Error inflating class (not found)com.santinocampos.android.count.Settings.OptionDialogPreference
at android.support.v7.preference.PreferenceInflater.createItemFromTag(PreferenceInflater.java:300)
at android.support.v7.preference.PreferenceInflater.rInflate(PreferenceInflater.java:358)
at android.support.v7.preference.PreferenceInflater.inflate(PreferenceInflater.java:167)
at android.support.v7.preference.PreferenceInflater.inflate(PreferenceInflater.java:117)
at android.support.v7.preference.PreferenceManager.inflateFromResource(PreferenceManager.java:115)
at android.support.v7.preference.PreferenceFragmentCompat.addPreferencesFromResource(PreferenceFragmentCompat.java:366)
at com.santinocampos.android.count.Settings.SettingsFragment.onCreate(SettingsFragment.java:19)
at android.support.v4.app.Fragment.performCreate(Fragment.java:1951)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1029)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1230)
at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1332)
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2288)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:357)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:31)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:80)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:754)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:276)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
at com.santinocampos.android.count.Settings.SettingsActivity.onCreate(SettingsActivity.java:20)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.myname
Here's my DialogPreferenceClass
import android.content.Context;
import android.preference.DialogPreference;
import android.support.v7.preference.PreferenceViewHolder;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
import com.myname.android.count.R;
import java.util.Set;
/**
* Created by thedr on 1/13/2017.
*/
public class MyDialogPreference extends DialogPreference {
public static final int KEY = R.string.preference_phoneNumber;
private EditText mPhoneNumberEditText;
public MyDialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
setPersistent(false);
setKey(getContext().getString(KEY));
String summary = getSharedPreferences().getString(SettingsActivity.PHONE_NUMBER_KEY, "");
setSummary(summary);
}
public void onBindDialogView(View view) {
super.onBindDialogView(view);
mPhoneNumberEditText = ((EditText) view.findViewById(R.id.editText_changeNumber));
}
public void onDialogClosed(boolean positive) {
getSharedPreferences()
.edit()
.putString(SettingsActivity.PHONE_NUMBER_KEY, mPhoneNumberEditText.getText().toString())
.apply();
super.onDialogClosed(positive);
persistBoolean(positive);
}
}
Here's my Preference xml where the inflation fails
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<com.myname.android.count.Settings.OptionDialogPreference
android:key="#string/preference_phoneNo"
android:dialogIcon="#android:drawable/ic_dialog_alert"
android:title="Reset Quests"
android:summary="Reset all quest-progress."
android:dialogMessage="Are you sure you wish to reset your quest progress? This action cannot be undone!"
android:positiveButtonText="Clear Quests"
android:negativeButtonText="Cancel"
/>
</PreferenceScreen>
Here's my PreferenceFragment
package com.myname.android.count.Settings;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.support.v7.preference.*;
import com.santinocampos.android.count.R;
/**
* Created by thedr on 1/13/2017.
*/
public class SettingsFragment extends PreferenceFragmentCompat {
private static final String TAG = "SettingsFragment";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
}
#Override
public void onDisplayPreferenceDialog(Preference preference) {
super.onDisplayPreferenceDialog(preference);
if (preference.getKey().equals(getContext().getString(MyDialogPreference.KEY))) {
}
}
#Override
public void onCreatePreferences(Bundle bundle, String s) {
}
public static String getTagString() {
return TAG;
}
}
And here's my host activity
public class SettingsActivity extends AppCompatActivity {
public static final String PHONE_NUMBER_KEY = "PHONE_NUMBER";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
Toolbar toolbar = ((Toolbar) findViewById(R.id.toolbar_settings));
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(R.string.settings_title);
}
}