片段中的自定义列表视图 - 空指针异常

时间:2014-03-13 20:46:17

标签: android listview android-fragments android-listview nullpointerexception

我是“整个片段”概念的新手,我需要一些帮助。

我想在片段中使用自定义列表视图,我的代码在Activity中工作正常,但片段中的实现非常痛苦。我得到2个空例外,我无法找到答案。

我也有一个非常基本的问题,我应该在片段中使用什么上下文,来自片段活动或片段本身?

这是我的片段代码

public class NewsFeed extends Fragment {

List<NewsFeedList> fr_ne_list = new ArrayList<NewsFeedList>();
Context ctx;
ListView list;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.activity_news_feed, container, false);
    list=(ListView)v.findViewById(R.id.listViewNewsFeedFriend);
    return v;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if(isAdded()) {
        ctx=getActivity();
        napolniseznamFriendList();
        /*"at com.osembitdesign.faceit.NewsFeed.onCreate(NewsFeed.java:49)"*/
        fillNewsFeedListView(fr_ne_list);
    }

}

//filling custom listview
private void fillNewsFeedListView(List<NewsFeedList> elem) {
    // TODO Auto-generated method stub
    ArrayAdapter<NewsFeedList> adapter = new MyListAdapter(ctx,R.layout.news_feed_list_item, elem);

    /*"at com.osembitdesign.faceit.NewsFeed.fillNewsFeedListView(NewsFeed.java:58)"*/
    list.setAdapter(adapter);

}


private class MyListAdapter extends ArrayAdapter<NewsFeedList> {
    public MyListAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
        // TODO Auto-generated constructor stub
    }

    private List<NewsFeedList> element;

    public MyListAdapter(Context context, int resource, List<NewsFeedList> items) {
        super(context, resource, items);
        this.element = items;

    }

    @Override
    public View getView...
}
//adding items to my (Array)List

private void napolniseznamFriendList() {
    // TODO Auto-generated method stub
    fr_ne_list.add(new NewsFeedList("xxxx", "xxxx","xxxx",R.drawable.ic_action_search));
    fr_ne_list.add(new NewsFeedList("xxx", "xx","xxx",R.drawable.ic_action_search));
}

}

错误

03-13 21:26:21.512  24416-24416/ E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at com.NewsFeed.fillNewsFeedListView(NewsFeed.java:58)
            at com.NewsFeed.onCreate(NewsFeed.java:49)

2 个答案:

答案 0 :(得分:0)

查看Fragment lifecycle。始终在onCreate()之前调用onCreateView()

这意味着从list调用fillNewsFeedListView()时,onCreate()将始终为空。

而是将条件语句从onCreate()移动到onViewCreated()。您可以将其直接移至onCreateView(),但最好将不相关的逻辑分开。

  

我也有一个非常基本的问题,我应该在哪个环境中使用   片段,来自片段活动还是片段本身?

Fragment s不是Context。使用getActivity(),这是有原因的。

答案 1 :(得分:0)

这是我在其中一个应用中使用的一些代码。它使用网格视图,如果需要,可以用listview替换它。仍然有用!

片段:

public class GalleryScreenFragment extends MyFragment{

private GalleryScreenGridAdapter mAdapter;
private GridView mGridView;
private boolean mActionMode = false;
private ImageButton mHomeButton,mBackButton,mDeleteButton, mShareButton;
private Animation mFadeInAnimation;
private Context mContext;
private OnGalleryItemSelectedListener mListener = mTempListener;

public GalleryScreenFragment(){
    if(null == Data.imagePathList)
        FileIO.readImageTasks();
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    if (activity instanceof OnGalleryItemSelectedListener) {
        mListener = (OnGalleryItemSelectedListener) activity;
        mContext = activity;
    }
    else{
        throw new ClassCastException(activity.toString()
            + " must implemenet GalleryScreenFragment.OnGalleryItemSelectedListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = mTempListener;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    RelativeLayout relativeLayout = (RelativeLayout) inflater.inflate(R.layout.activity_gallery_screen_main, null);
    mGridView = (GridView) relativeLayout.findViewById(R.id.gridview);
    mGridView.setEmptyView(relativeLayout.findViewById(R.id.emptyGridView));

    mHomeButton = (ImageButton) relativeLayout.findViewById(R.id.homeButton);
    mHomeButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            mListener.onGalleryHomeButtonPressed();
        }
    });

    mShareButton = (ImageButton) relativeLayout.findViewById(R.id.shareButton);
    mShareButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

        }
    });

    mBackButton = (ImageButton) relativeLayout.findViewById(R.id.backButton);
    mBackButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

        }
    });

    mDeleteButton = (ImageButton) relativeLayout.findViewById(R.id.deleteButton);
    mDeleteButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

        }
    });

    mAdapter = new GalleryScreenGridAdapter(mContext);
    mGridView.setAdapter(mAdapter);

    mGridView.setVerticalScrollBarEnabled(false);

    mGridView.setOnScrollListener(new PauseOnScrollListener(ImageLoader.getInstance(), true, false));

    mFadeInAnimation = AnimationUtils.loadAnimation(mContext, R.anim.fade_in);

    return relativeLayout;
}
}

的活动:

public class GalleryScreenActivity extends MyFragmentActivity implements OnGalleryItemSelectedListener{

private boolean mSelectionMode = false;
private GalleryScreenFragment mGalleryScreenFragment;

@Override
public void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    setContentView(R.layout.activity_gallery_screen_content_frame);

    mGalleryScreenFragment = (GalleryScreenFragment) getSupportFragmentManager().findFragmentById(R.id.mainFragment);
}
}

适配器:

public class GalleryScreenGridAdapter extends BaseAdapter implements BitmapProcessor{
private LayoutInflater inflater;
private Context mContext;
private DisplayImageOptions mOptions;
private ImageLoader mImageLoader = ImageLoader.getInstance();

public GalleryScreenGridAdapter(Context context){
    mContext = context;
    inflater = (LayoutInflater) mContext.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
    mOptions = new DisplayImageOptions.Builder()
    .imageScaleType(ImageScaleType.EXACTLY)
    .bitmapConfig(Bitmap.Config.RGB_565)
    .preProcessor(this)
    .cacheInMemory(true)
    .resetViewBeforeLoading(true)
    .build();
}

@Override
public int getCount() {
    return (null == Data.imagePathList) ? 0 : Data.imagePathList.size();
}

@Override
public Object getItem(int position) {
    return position;
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    final GridObject object = Data.imagePathList.get(position);

    final GalleryScreenGridItem view = (GalleryScreenGridItem) inflater.inflate(R.layout.activity_gallery_screen_grid_item_layout, null);

    final ImageView imageView = (ImageView) view.findViewById(R.id.image);

    imageView.setImageBitmap(null);
    view.setChecked(false);

    mImageLoader.loadImage(object.getUrl(), new ImageSize(200, 200), mOptions, new SimpleImageLoadingListener(){

        @Override
        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
            imageView.setImageResource(android.R.drawable.ic_delete);
        }

        @Override
        public void onLoadingComplete(String imageUri, View tempView, Bitmap loadedImage) {
            view.setChecked(object.getState());
            imageView.setImageBitmap(loadedImage);
            AlphaAnimation fadeImage = new AlphaAnimation(0, 1);
            fadeImage.setDuration(100);
            fadeImage.setInterpolator(new DecelerateInterpolator());
            imageView.startAnimation(fadeImage);
        }
    }, Data.imagePathList.get(position).getPictureType());
    return view;
}
}

如果您需要更多帮助,请告诉我。它在活动中使用片段。片段有一个gridview,由适配器填充。只需使用您自己的代码将gridview替换为listview和适配器的getview,您就可以了。