Morty Choi
Morty Choi

Reputation: 373

Should adapter be local variable or instance variable?

When setting adapter for listView, should I just do listView.setAdapter(new MyAdapater()); or should I keep the adapter as instance variable and set it to null when onDestory() ?

Upvotes: 3

Views: 197

Answers (2)

JanBo
JanBo

Reputation: 2933

The answer depends on the use case.

  1. If you are going to do data manipulation such as rearranging the order of elements or changing the data dynamically in some way, then its "better" to have an instance variable of your adapter. It will safe you from casting your adapter from ListView getAdapter() method, whenever accessing your adapter.

  2. If you are creating a simple list view consisted of for ex. 10 Strings and you dont plan on doing anything with the data set, then you don't need to keep a reference to your adapter.

Upvotes: 3

Rathan Kumar
Rathan Kumar

Reputation: 2577

It is better to maintain adapter as instance variable because each and every time you have to create new adapter instead of that just change the data and you can call notifyDatasetChanged() so that adapter will be refreshed.

Upvotes: 0

Related Questions