ListView.setAdapter error: java.lang.NullPointerException



通过在ListFragment活动中设置适配器,我收到错误"java.lang.NullPointerException"。

这是我的代码:

private List<Music> musicList;
public View inflate;
ListView searchList;
public class SearchFragment extends ListFragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        context = getActivity().getApplicationContext();
        inflate = inflater.inflate(R.layout.search, container, false);
        musicList = new ArrayList<Music>();
        adapter = new CustomListAdapter(musicList, context);
        searchList.setAdapter(adapter);
}

我在以下代码中有一个NullPointerException:

错误在searchList.setAdapter(adapter);,所以我也尝试将适配器值从new ArrayList<Music>()更改为new <Music>ArrayList(),但没有成功。

我的音乐课是这样的:

public class Music {
    private String title, thumbnail, duration, uri, waveform;
    private int likes, playbackCount;
    public Music() {
    }
    public Music(String name, String thumbnailUrl, int likes, String rating, int playbackCount) {
        this.title = name;
        this.thumbnail = thumbnail;
        this.likes = likes;
        this.duration = rating;
        this.playbackCount = playbackCount;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String name) {
        this.title = name;
    }
    public String getThumbnail() {
        return thumbnail;
    }
    public void setThumbnail(String thumbnail) {
        this.thumbnail = thumbnail;
    }
    public int getLikes() {
        return likes;
    }
    public void setLikes(int likes) { this.likes = likes; }
    public String getDuration() {
        return duration;
    }
    public void setDuration(String duration) {
        this.duration = duration;
    }
    public int getPlayBackCount() {
        return playbackCount;
    }
    public void setPlayBackCount(int playbackCount) {
        this.playbackCount = playbackCount;
    }
    public String getUri() {
        return uri;
    }
    public void setUri(String uri) {
        this.uri = uri;
    }
    public String getWaveform() {
        return waveform;
    }
    public void setWaveform(String waveform) {
        this.waveform = waveform;
    }
}

您已经扩展了ListFragment,因此

setListAdapter(adapter);

看看教程

首先,您已经获取了ListView searchList和同一个尚未初始化的对象,因此在调用searchList.setAdapter(adapter);时它会给您NullPointerException。

其次,您已经获取了ListFragment,因此可以使用getListView()方法直接获取listview。甚至可以直接调用setListAdapter(adapter)方法。

相关内容

  • 没有找到相关文章

最新更新