android - ListView.setAdapter错误:java.lang.NullPointerException

时间:2016-04-01 09:20:46

标签: java android listview nullpointerexception

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

这是我的代码:

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;
    }
}

2 个答案:

答案 0 :(得分:1)

您已经ListFragment扩展了

setListAdapter(adapter);

看看tutorial

答案 1 :(得分:1)

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

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