我通过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类上,专门用于初始化inflater 。
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错误条目
答案 0 :(得分:1)
创建Fragment
时,在onAttach(Activity)被调用之前,它尚未附加到Activity
- 在此之前,getActivity()
将返回null
您应该通过setArguments()将Bundle
传递到Fragment
,然后通过getArguments()检索,并在asyncExecuted
中执行onAttach()
方法}或稍后的fragment lifecycle。
答案 1 :(得分:0)
检查标题和其他变量是否存在于Api中
使用try和catch方法添加代码。
try{
title = bundle.getString("M_TITLE");
isbn = bundle.getString("M_ISBN_13");
author = bundle.getString("M_AUTHOR_NAME");
}catch(...){}
答案 2 :(得分:0)
1)通过检查getActivity()是否为null,您应该在调用onPostExecute时验证您的片段是否仍附加到活动。如果为null,则片段已分离。在这种情况下,您通常想要退出。
2)如果它是getActivity的有效实例,请尝试:
View row = LayoutInflater.from(getContext()).inflate(R.layout.list_item_result, parent, false);