android - There is no default constructor for ArrayAdapter

蹲街弑〆低调 提交于 2019-12-18 05:09:07

问题


I m making adapter to adapt my book collection to be visible in list view.

Issue is solved if I add super(context, position):

    public BookAdapter(Context context, int position, List <Book> updatedBooksList) {
    super(context, position);
    this.context = context;
    this.booksList = updatedBooksList ;
}

However, I want to know why I need this argument (int position) and call superclass constructor?

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

Also, in the broader sense why do we always(?) need to call super.onCreate like here in every onCreate?

Aren't we supposed to override all our activity lifecycle stages - onPause, onREsume, onStop, OnDestroy, yet we still have to call super's in each of them?


回答1:


Issue is solved if I add super(context, position):

The second parameter is not a position. It is the ID of a layout resource, one that is used by default for the rows created by the ArrayAdapter. You can tell that by reading the JavaDocs for the constructor that you are calling.

However, I want to know why I need this argument (int position) and call superclass constructor?

Because, as the IDE told you, there is no default constructor on ArrayAdapter. In Java, the "default constructor" is a zero-argument constructor. Every constructor in Java needs to chain to a superclass constructor. If the superclass has a zero-argument ("default") constructor, Java will chain to it automatically. If the superclass does not have a zero-argument constructor, you need to chain to a superclass constructor manually.

Also, in the broader sense why do we always(?) need to call super.onCreate like here in every onCreate?

Because the developers who created Activity elected to make that a requirement.

Aren't we supposed to override all our activity lifecycle stage

No. You override those that you need.

yet we still have to call super's in each of them?

Activity wants to do its processing for those lifecycle methods, in addition to anything that you want to do. To enforce that, Activity demands that you chain to the superclass and throws a SuperNotCalledException if you do not.



来源:https://stackoverflow.com/questions/29333692/android-there-is-no-default-constructor-for-arrayadapter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!