简体   繁体   中英

Android: are adapters only declared/instantiated in onCreate()?

I can boil this down into two questions:

  1. As the title suggests, is onCreate() the only place to create adapters?

  2. I'm following this guide to create a Gridview , except I'm pulling from the Spotify API to get a list of playlists. The thing is that I don't have the playlists on hand when an adapter is created in onCreate() , which means I'm passing in null when I create the GridViewAdapter . Any design suggestions?

Thanks for your feedback and time.

I think you're mixing 2 things because of the example you're following - creating the adapter and setting the data. The example uses an ArrayAdapter which requires AFAIK it's data in the constructor.

There's no de facto standard for adapters, but here's what I usually do:

public class GridViewAdapter extends BaseAdapter {
  private final Context context;
  private List<DataClass> data = new ArrayList<>();

  public GridAdapter(Context context) {
    this.context = context;
  }

  public void setData(List<DataClass> data) {
    this.data = data;
    notifyDataSetChanged();
  }

  @Override
  public int getCount() {
    return data.size();
  }

  @Override
  public Object getItem(int i) {
    return data.get(i);
  }

  @Override
  public long getItemId(int i) {
    return i;
  }

  @Override
  public View getView(int i, View view, ViewGroup viewGroup) {
    // usual thing here
  }
}

A couple of things to notice here. DataClass is basically your data class that should hold all info need to populate the items. You should favour List and not ArrayList as the example describes because it's more generic and allows you to change the adapter implementation without changing it's contract. You also should specify the type the list holds and not do as the example did where nothing is told to the compiler about the objects the array holds.

Now on to the good part and actually answering your questions. You can create the adapter whenever you want. I'm passing the context, but you might not even need this. Usually onCreate is a good place to create it, but you can do whenever.

Once you receive the data, you simply call adapter.setData(...) and it will populate the adapter's data and notify it that the data has changed.

You can even separated these last 2 methods - setData and notifyDataSetChanged - and have the set data only set the data and call the notifyDataSetChanged() whenever you want.

Hope this helps

EDIT

I'm not trying in anyway to say the example you're following is bad. It's still a valid example and ArrayAdapters do the job when needed. I just think you're questions are very valid and that you didn't see the big picture yet because the example is quite specific.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM