0

我是「整體碎片」概念的新手,我需要一些幫助。片段中的自定義列表視圖 - 空指針異常

我想在片段中使用自定義列表視圖,我的代碼在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) 

回答

0

審查Fragment lifecycle。總是在onCreateView()之前調用onCreate()

這意味着當從onCreate()調用fillNewsFeedListView()時,list將始終爲空。

而是將條件語句從onCreate()移動到onViewCreated()。您可以將其直接移動到onCreateView(),但最好將不相關的邏輯分開。

我也有一個非常基本的問題,我應該在片段活動或片段本身使用 片段的內容?

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

+0

謝謝!就像你說的我剛剛將條件語句移動到onViewCreated(),它的工作就像一個魅力! – gregaj

+0

不客氣! –

+0

可以幫我在這裏http://stackoverflow.com/questions/41938475/empty-custom-listview-in-fragment-on-back-tab – Panache

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,你就可以走了。

+0

感謝您的快速響應和代碼示例。我確定有人會使用它。 – gregaj