为listview创建适配器而不是最初传递数组

时间:2016-03-22 14:42:39

标签: android listview android-adapter

我有一个扩展SongsAdapter的客户适配器(ArrayAdapter),它包含一组Song个对象。在我的片段onCreateView方法中,我尝试初始化此适配器。

adapter = new SongsAdapter(getContext(), arrayOfSongs);

问题是arrayOfSongs最初为空。用户应该在iTunes数据库中搜索一首歌曲,当我收到回复时,我会解析JSON并创建歌曲对象,然后将它们添加到我的适配器

adapter.addAll(songs); 

然后

adapter.notifyDataSetChanged();

但我得到了例外

java.lang.NullPointerException at android.widget.ArrayAdapter.getCount

如何在用户首次搜索之前隐藏列表视图,然后取消隐藏它以显示结果。我如何正确初始化适配器?

这是我的适配器

public class SongsAdapter extends ArrayAdapter<Song> {


    public SongsAdapter(Context context, ArrayList<Song> songs) {

        super(context, 0, songs);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Song song = getItem(position);

        if (convertView == null)
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_song, parent, false);

        TextView artistName = (TextView) convertView.findViewById(R.id.artistName);
        TextView trackName = (TextView) convertView.findViewById(R.id.trackName);

        artistName.setText(song.getArtist());
        trackName.setText(song.getTitle());

        return convertView;
    }
}

1 个答案:

答案 0 :(得分:1)

您可以在getCount方法中检查arraylist是否为null并相应地返回数据。

  public class SongsAdapter extends BaseAdapter {

ArrayList<Song> mList;
Context mContext;

public SongsAdapter(Context context, ArrayList<Song> songs) {

    mList = songs;
    mContext = context;

}



@Override
public int getCount() {
    if(mList==null)
    {

        return 0;
    }
    else {

        return mList.size();


    }
}

@Override
public Object getItem(int position) {
    return mList.get(position);
}

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
      Song song = getItem(position);

    if (convertView == null)
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_song, parent, false);

    TextView artistName = (TextView) convertView.findViewById(R.id.artistName);
    TextView trackName = (TextView) convertView.findViewById(R.id.trackName);

    artistName.setText(song.getArtist());
    trackName.setText(song.getTitle());

    return convertView;
}
}

如果有帮助请记下来,如果您需要任何说明,请告诉我。快乐的编码。