Unable to create an instance of the android studio class

Asked

Viewed 96 times

2

public class HomeFragment extends Fragment {


private RecyclerView categoryRecyclerView;
private CategoryAdapter categoryAdapter;

private HomeViewModel homeViewModel;

public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
     homeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
    View view = inflater.inflate(R.layout.fragment_home, container, false);

    categoryRecyclerView = view.findViewById(R.id.category_recyclerview);
    LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
    layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
    categoryRecyclerView.setLayoutManager(layoutManager);

    List<HomeViewModel> categoryModelList = new ArrayList<>();
    categoryModelList.add(new HomeViewModel("link", "Home"));
    categoryModelList.add(new HomeViewModel("link", "Electronics"));
    categoryModelList.add(new HomeViewModel("link", "Appliances"));
    categoryModelList.add(new HomeViewModel("link", "Furniture"));
    categoryModelList.add(new HomeViewModel("link", "Fashion"));
    categoryModelList.add(new HomeViewModel("link", "Toys"));
    categoryModelList.add(new HomeViewModel("link", "Sports"));
    categoryModelList.add(new HomeViewModel("link", "Wall Arts"));
    categoryModelList.add(new HomeViewModel("link", "Books"));
    categoryModelList.add(new HomeViewModel("link", "Shoes"));

    categoryAdapter = new CategoryAdapter(categoryModelList);
    categoryRecyclerView.setAdapter(categoryAdapter);
    categoryAdapter.notifyDataSetChanged();


    return view;
}
}

public class HomeViewModel extends ViewModel {

private String CategoryIconLink;
private String categoryName;

public HomeViewModel(String categoryIconLink, String categoryName) {
    CategoryIconLink = categoryIconLink;
    this.categoryName = categoryName;
}

public String getCategoryIconLink() {
    return CategoryIconLink;
}

public void setCategoryIconLink(String categoryIconLink) {
    CategoryIconLink = categoryIconLink;
}

public String getCategoryName() {
    return categoryName;
}

public void setCategoryName(String categoryName) {
    this.categoryName = categoryName;
}
}

public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.ViewHolder> {

private List<HomeViewModel> categoryModelList;

public CategoryAdapter(List<HomeViewModel> categoryModelList) {
    this.categoryModelList = categoryModelList;
}

@NonNull
@Override
public CategoryAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.category_item,viewGroup,false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull CategoryAdapter.ViewHolder viewHolder, int position) {
    String icon = categoryModelList.get(position).getCategoryIconLink();
    String name = categoryModelList.get(position).getCategoryName();
    viewHolder.setCategoryName(name);

}

@Override
public int getItemCount() {
    return categoryModelList.size();
}

public class ViewHolder extends RecyclerView.ViewHolder{

    private ImageView  categoryIcon;
    private TextView categoryName;

    public ViewHolder(@NonNull View itemView) {
        super(itemView);
        categoryIcon = itemView.findViewById(R.id.category_icon);
        categoryName = itemView.findViewById(R.id.category_name);
    }

    private void setCategoryIcon(){

    }

    private void setCategoryName(String name){
        categoryName.setText(name);
    }
}
}

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

private AppBarConfiguration mAppBarConfiguration;
private FrameLayout frameLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);


    DrawerLayout drawer = findViewById(R.id.drawer_layout);
    NavigationView navigationView = findViewById(R.id.nav_view);
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    mAppBarConfiguration = new AppBarConfiguration.Builder(
            R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow,
            R.id.nav_tools, R.id.nav_share, R.id.nav_send)
            .setDrawerLayout(drawer)
            .build();
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
    NavigationUI.setupWithNavController(navigationView, navController);


    frameLayout = findViewById(R.id.main_framelayout);
    setFragment(new HomeFragment());
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item){

    int id = item.getItemId();

    if (id == R.id.main_search_icon){
        return true;
    }else if (id == R.id.main_notification_icon){
        return true;
    }else if (id == R.id.main_cart_icon){
        return true;
    }

    return super.onOptionsItemSelected(item);

}

@Override
public boolean onSupportNavigateUp() {
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    return NavigationUI.navigateUp(navController, mAppBarConfiguration)
            || super.onSupportNavigateUp();
}


@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.nav_my_mall) {

    } else if (id == R.id.nav_my_orders) {

    } else if (id == R.id.nav_my_rewards) {

    } else if (id == R.id.nav_my_cart) {

    } else if (id == R.id.nav_my_wishlist) {

    } else if (id == R.id.nav_my_account) {

    } else if (id == R.id.nav_sign_out) {

    }

    return true;
}

private void setFragment(Fragment fragment){
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(frameLayout.getId(),fragment);
    fragmentTransaction.commit();
}

}

Error Log

2019-09-11 13:38:13.575 25264-25264/com.example.grillo E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.grillo, PID: 25264
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.grillo/com.example.grillo.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.example.grillo.ui.home.HomeViewModel
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2895)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1616)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:176)
        at android.app.ActivityThread.main(ActivityThread.java:6651)
        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:824)
     Caused by: java.lang.RuntimeException: Cannot create an instance of class com.example.grillo.ui.home.HomeViewModel
        at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:184)
        at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:241)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:164)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:130)
        at com.example.grillo.ui.home.HomeFragment.onCreateView(HomeFragment.java:28)
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2595)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
        at androidx.fragment.app.FragmentManagerImpl.addAddedFragments(FragmentManagerImpl.java:2097)
        at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1871)
        at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1827)
        at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
        at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2660)
        at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2610)
        at androidx.fragment.app.Fragment.performActivityCreated(Fragment.java:2619)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:904)
        at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
        at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2656)
        at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2610)
        at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:246)
        at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:542)
        at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:201)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1335)
        at android.app.Activity.performStart(Activity.java:7108)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2780)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2895) 
        at android.app.ActivityThread.-wrap11(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1616) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:176) 
        at android.app.ActivityThread.main(ActivityThread.java:6651) 
        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:824) 
     Caused by: java.lang.InstantiationException: java.lang.Class<com.example.grillo.ui.home.HomeViewModel> has no zero argument constructor
        at java.lang.Class.newInstance(Native Method)
        at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:182)
        at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:241) 
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:164) 
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:130) 
        at com.example.grillo.ui.home.HomeFragment.onCreateView(HomeFragment.java:28) 
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2595) 
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881) 
        at androidx.fragment.app.FragmentManagerImpl.addAddedFragments(FragmentManagerImpl.java:2097) 
        at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1871) 
        at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1827) 
        at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727) 
        at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2660) 
        at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2610) 
        at androidx.fragment.app.Fragment.performActivityCreated(Fragment.java:2619) 
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:904) 
        at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238) 
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303) 
        at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2656) 
        at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2610) 
        at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:246) 
        at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:542) 
        at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:201) 
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1335) 
        at android.app.Activity.performStart(Activity.java:7108) 
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2780) 
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2895) 
        at android.app.ActivityThread.-wrap11(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1616) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:176) 
        at android.app.ActivityThread.main(ActivityThread.java:6651) 
        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:824)
  • 1

    @Joanatha, Hello! It would be interesting if you put the error log and made a comment next to the line that is giving error. The first thing we do when we get bad code is to analyze the error log and compare it to the source code.

1 answer

1

That information:

Caused by: java.lang.InstantiationException:
java.lang.Class<com.example.grillo.ui.home.HomeViewModel> has no zero argument constructor

Added to this information:

    at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:182)
    at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:241)

    at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:164) 
    at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:130)

Indicate that the error was caused due to the absence of a constructor with no class arguments HomeViewModel.

When initializing subclasses of ViewModel using ViewModelProviders, by default, your class is expected to have an argument absent constructor. Your class HomeViewModel has only one constructor with two arguments.

public HomeViewModel(String categoryIconLink, String categoryName)

The direct solution is to create the constructor without arguments for HomeViewModel and for each instance created to fill its properties.

You can also keep the constructor with two arguments but for that you will have to create a class Factory that implements the interface ViewModelProvider.Factory to instantiate HomeViewModel, is a laborious but amenable solution using the library Viewmodelfactory.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.