我有一个扩展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;
}
}
答案 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;
}
}
如果有帮助请记下来,如果您需要任何说明,请告诉我。快乐的编码。