我正在为我的音乐播放器应用制作自定义ArrayAdapter,当我尝试设置View的文本时,我的应用程序崩溃了。我知道从论坛上看你无法从后台线程访问UI元素,或者在尝试这样的事情之前你必须setContentView(),但是我的情况有点不同。有什么想法吗?
MusicAdapter.class
Context context;
int layoutResourceId;
Song data[] = null;
private Handler threadHandler = new Handler();
public MusicAdapter(Context context, int layoutResourceId, Song[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
SongHolder holder = null;
if(row == null){
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new SongHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.songName);
row.setTag(holder);
}else{
holder = (SongHolder)row.getTag();
}
Song song = data[position];
holder.txtTitle.setText(song.title); //This line crashes
return row;
}
static class SongHolder{
TextView txtTitle;
}
}
我的错误讯息: 01-11 21:34:38.226:E / AndroidRuntime(32319):致命异常:主要 01-11 21:34:38.226:E / AndroidRuntime(32319):java.lang.NullPointerException 01-11 21:34:38.226:E / AndroidRuntime(32319):at com.example.audity.MusicAdapter $ SongHolder。(MusicAdapter.java:51)
答案 0 :(得分:2)
因为我看到你的代码你的崩溃可能是:
if(row == null){
holder.txtTitle = (TextView) row.findViewById(R.id.songName);
}else{
//txtTitle not initialized here
}
holder.txtTitle.setText(song.title);
txtTitle未在else块上初始化并在其下方使用
希望有用:)