问题
I have a a customer adapter (SongsAdapter
) that extends ArrayAdapter
and it contains an array of Song
objects. In my fragments onCreateView
method I'm trying to initialize this adapter.
adapter = new SongsAdapter(getContext(), arrayOfSongs);
the problem is that arrayOfSongs
is initially null. The user should search for a song on the iTunes database and when I get a response, I parse the JSON and create song objects and then add them to my adapter
adapter.addAll(songs);
and then
adapter.notifyDataSetChanged();
but I'm getting an exception
java.lang.NullPointerException at android.widget.ArrayAdapter.getCount
How can I hide the listview until the first search by the user, and then unhide it to display the results. How would I properly initialize the adapter?
Here is my adapter
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:
You can check if the arraylist is null in getCount method and return the data accordingly.
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;
}
}
Mark this up if it helps else let me know if you need any description. Happy coding.
来源:https://stackoverflow.com/questions/36157482/creating-an-adapter-for-listview-without-passing-an-array-initially