【发布时间】:2015-03-15 04:22:51
【问题描述】:
我正在通过 API 获取数据并尝试将它们放在 ListView 中(我首先将它们包装在一个包中),我正在使用 BaseAdapter。问题是我在片段内传递给适配器的 Context/LayoutInflater 返回 NullPointer 异常
//AsyncTask中的onPostExecute
@Override
protected void onPostExecute(Bundle bundle) {
if(bundle != null){
ResultFragment resultFragment = new ResultFragment();
resultFragment.asyncExecuted(bundle);
}
}
//Fragment内部的方法
public void asyncExecuted(Bundle bundle) {
listResult.setAdapter(new ResultAdapter(bundle,getActivity()));
}
//Adapter 类,错误出现在 Adapter 类上,特别是在初始化充气机时。
public class ResultAdapter extends BaseAdapter {
String title, isbn, author;
String[] s_title, s_isbn, s_rating, s_image, s_author;
LayoutInflater inflater;
public ResultAdapter(Bundle bundle, Context context){
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
try {
title = bundle.getString("M_TITLE");
isbn = bundle.getString("M_ISBN_13");
author = bundle.getString("M_AUTHOR_NAME");
int size = bundle.getInt("M_SIMILAR_SIZE");
s_title = new String[size];
s_isbn = new String[size];
s_rating = new String[size];
s_image = new String[size];
s_author = new String[size];
s_title = bundle.getStringArray("M_SIMILAR_TITLE");
s_isbn = bundle.getStringArray("M_SIMILAR_ISBN_13");
s_rating = bundle.getStringArray("M_SIMILAR_RATING");
s_image = bundle.getStringArray("M_SIMILAR_IMAGE_URL");
s_author = bundle.getStringArray("M_SIMILAR_AUTHOR_NAME");
}catch (NullPointerException e){
Log.e(getClass().getSimpleName(),"Nothing is Inside!");
}
}
@Override
public int getCount() {
return s_title.length;
}
@Override
public Object getItem(int position) {
return s_isbn[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = inflater.inflate(R.layout.list_item_result, parent, false);
TextView txtTitle = (TextView)row.findViewById(R.id.txtTitle);
TextView txtAuthor = (TextView)row.findViewById(R.id.txtAuthor);
TextView txtRating = (TextView)row.findViewById(R.id.txtRating);
txtTitle.setText(s_title[position]);
txtAuthor.setText(s_author[position]);
txtRating.setText(s_rating[position]);
return row;
}
}
LOGCAT 错误条目
【问题讨论】:
标签: android layout-inflater android-context