RecyclerView: inner classes cannot have static declaration

I'm a little confused, I have a recyclerview setting according to the tutorial on google / android and I get the following error.

Inner classes cannot have static declaration 

Of course, I have a nested static class, but this is how android / google defined it.

  public class ItemsViewAdapter extends RecyclerView.Adapter<ItemsViewAdapter.ViewHolder> { ... ... public static class ViewHolder extends RecyclerView.ViewHolder { ... } 

Why am I getting this error, I hear that it is better to use the nested class as static so that you do not lose the link, but the current version of Android studio complains

Any ideas?

thanks

+4
source share
2 answers

Directly to your question: -

 1. Inner classes cannot have static declaration 

This is absolutely true, this is not a mistake, and even the message is not misleading.

 2. I hear its better to use nested class as a static so you are not wasting a reference 

You are absolutely right.

 3. Solution to You 

Create a new class (file) in your project for ItemsViewAdapter , and there will be no such error.


General discussion:

Java and Android support the fact that you can declare a Static inner class / member / function BUT that the class must be the parent class, you cannot do this inside the Inner Class

i.e. class Main may have a static class Adapter , but if the Adapter class is not static and is still an inner class of Main, then it cannot have a static inner class / member.

What do you have?:

 class Main static class Adapter static class Holder 

or

  class Adapter static class Holder 

If you want to declare any member of the STATIC class, then the immediate OuterClass must be your main class in this file.


Why is this?

This is because the inner class is implicitly bound to an instance of its outer class; it cannot define any static methods. Since a static nested class cannot refer directly to instance variables or methods defined in its enclosing class, it can only use them through an object reference; it is safe to declare static methods in a static nested class.


Sites to visit:

1 http://www.geeksforgeeks.org/inner-class-java/

2 http://www.javaworld.com/article/2077372/learn-java/static-class-declarations.html

3 http://viralpatel.net/blogs/inner-classes-in-java/

+5
source

You can also just implement the ItemViewAdapter as a static class

 public static class ItemsViewAdapter extends RecyclerView.Adapter<ItemsViewAdapter.ViewHolder> { ... ... public static class ViewHolder extends RecyclerView.ViewHolder { ... } 

This should take care of the error.

-one
source

All Articles