获取java.lang.NullPointerException的Android Fragment Recycler视图

时间:2016-07-11 04:37:30

标签: java android fragment android-recyclerview adapter

我希望RecyclerView中有Fragment。我正在使用https://developer.android.com/samples/RecyclerView/src/com.example.android.recyclerview/RecyclerViewFragment.html#l19中的RecyclerViewFragment.java,但我仍然得到例外。

这是代码。

RecyclerViewFragment.java

package com.example.narehh.todolist.Fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;

import com.example.narehh.todolist.Adapters.TaskListAdapter;
import com.example.narehh.todolist.JavaClasses.Task;
import com.example.narehh.todolist.R;

import java.util.ArrayList;



/**
 * Demonstrates the use of {@link RecyclerView} with a {@link LinearLayoutManager} and a
 * {@link GridLayoutManager}.
 */
public class TaskListFragment extends Fragment {

    private static final String TAG = "TaskListFragment";
    private static final String KEY_LAYOUT_MANAGER = "layoutManager";
    private static final int SPAN_COUNT = 2;
    private static final int DATASET_COUNT = 60;

    private enum LayoutManagerType {
        GRID_LAYOUT_MANAGER,
        LINEAR_LAYOUT_MANAGER
    }

    protected LayoutManagerType mCurrentLayoutManagerType;

    protected RadioButton mLinearLayoutRadioButton;
    protected RadioButton mGridLayoutRadioButton;

    protected RecyclerView mRecyclerView;
    protected TaskListAdapter mAdapter;
    protected RecyclerView.LayoutManager mLayoutManager;
    //    protected String[] mDataset;
    protected ArrayList<Task> mDataset;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Initialize dataset, this data would usually come from a local content provider or
        // remote server.
        initDataset();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_task_list,container, false);
        rootView.setTag(TAG);

        mRecyclerView = (RecyclerView) rootView.findViewById(R.id.task_list_rv);

        // LinearLayoutManager is used here, this will layout the elements in a similar fashion
        // to the way ListView would layout elements. The RecyclerView.LayoutManager defines how
        // elements are laid out.
        mLayoutManager = new LinearLayoutManager(getActivity());

        mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;

        if (savedInstanceState != null) {
            // Restore saved layout manager type.
            mCurrentLayoutManagerType = (LayoutManagerType) savedInstanceState
                    .getSerializable(KEY_LAYOUT_MANAGER);
        }
        setRecyclerViewLayoutManager(mCurrentLayoutManagerType);

        mAdapter = new TaskListAdapter(mDataset);
        // Set CustomAdapter as the adapter for RecyclerView.
        mRecyclerView.setAdapter(mAdapter);

//        mLinearLayoutRadioButton = (RadioButton) rootView.findViewById(R.id.linear_layout_rb);
//        mLinearLayoutRadioButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                setRecyclerViewLayoutManager(LayoutManagerType.LINEAR_LAYOUT_MANAGER);
//            }
//        });
//
//        mGridLayoutRadioButton = (RadioButton) rootView.findViewById(R.id.grid_layout_rb);
//        mGridLayoutRadioButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                setRecyclerViewLayoutManager(LayoutManagerType.GRID_LAYOUT_MANAGER);
//            }
//        });

        return rootView;
    }

    /**
     * Set RecyclerView's LayoutManager to the one given.
     *
     * @param layoutManagerType Type of layout manager to switch to.
     */
    public void setRecyclerViewLayoutManager(LayoutManagerType layoutManagerType) {
        int scrollPosition = 0;

        // If a layout manager has already been set, get current scroll position.
        if (mRecyclerView.getLayoutManager() != null) {
            scrollPosition = ((LinearLayoutManager) mRecyclerView.getLayoutManager())
                    .findFirstCompletelyVisibleItemPosition();
        }

        switch (layoutManagerType) {
            case GRID_LAYOUT_MANAGER:
                mLayoutManager = new GridLayoutManager(getActivity(), SPAN_COUNT);
                mCurrentLayoutManagerType = LayoutManagerType.GRID_LAYOUT_MANAGER;
                break;
            case LINEAR_LAYOUT_MANAGER:
                mLayoutManager = new LinearLayoutManager(getActivity());
                mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;
                break;
            default:
                mLayoutManager = new LinearLayoutManager(getActivity());
                mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;
        }

        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.scrollToPosition(scrollPosition);
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        // Save currently selected layout manager.
        savedInstanceState.putSerializable(KEY_LAYOUT_MANAGER, mCurrentLayoutManagerType);
        super.onSaveInstanceState(savedInstanceState);
    }

    /**
     * Generates Strings for RecyclerView's adapter. This data would usually come
     * from a local content provider or remote server.
     */
    private void initDataset() {
//        mDataset = new String[DATASET_COUNT];
//        for (int i = 0; i < DATASET_COUNT; i++) {
//            mDataset[i] = "This is element #" + i;
//        }
        mDataset = new ArrayList<Task>();
        Task task1 = new Task(0, "task1", "01-09-2016", "10:10");
        Task task2 = new Task(0, "task2", "01-09-2016", "10:10");
        Task task3 = new Task(0, "task3", "01-09-2016", "10:10");
        mDataset.add(task1);
        mDataset.add(task2);
        mDataset.add(task3);
    }
}

适配器

package com.example.narehh.todolist.Adapters;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;

import com.example.narehh.todolist.JavaClasses.Task;
import com.example.narehh.todolist.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Narehh on 7/10/2016.
 */
public class TaskListAdapter extends RecyclerView.Adapter<TaskListAdapter.TaskViewHolder> {

    private ArrayList<Task> taskList = new ArrayList<Task>();

    public TaskListAdapter(ArrayList<Task> taskList) {
        this.taskList = taskList;
    }


    @Override
    public TaskListAdapter.TaskViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return null;
    }

    @Override
    public void onBindViewHolder(TaskViewHolder holder, int position) {
        Task task = taskList.get(position);
        holder.title.setText(task.getName());
        holder.date.setText(task.getDate() + task.getTime());
        holder.isDone.setChecked(false);
    }

    @Override
    public int getItemCount() {
        return taskList.size();
    }


    public static class TaskViewHolder extends RecyclerView.ViewHolder {
        protected TextView title;
        protected TextView date;
        protected CheckBox isDone;

        public TaskViewHolder(View v) {
            super(v);
            title =  (TextView) v.findViewById(R.id.title);
            date = (TextView)  v.findViewById(R.id.date);
            isDone = (CheckBox)  v.findViewById(R.id.isDone);
        }
    }
}

我得到了这个例外

FATAL EXCEPTION: main
                 Process: com.example.narehh.todolist, PID: 16871
                                                                         java.lang.NullPointerException
                                                                             at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:5780)
                                                                             at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5003)
                                                                             at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4913)
                                                                             at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2029)
                                                                             at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1414)
                                                                             at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1377)
                                                                             at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:578)
                                                                             at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3260)
                                                                             at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3069)
                                                                             at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3518)
                                                                             at android.view.View.layout(View.java:15781)
                                                                             at android.view.ViewGroup.layout(ViewGroup.java:4884)
                                                                             at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
                                                                             at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
                                                                             at android.view.View.layout(View.java:15781)
                                                                             at android.view.ViewGroup.layout(ViewGroup.java:4884)
                                                                             at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
                                                                             at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
                                                                             at android.view.View.layout(View.java:15781)
                                                                             at android.view.ViewGroup.layout(ViewGroup.java:4884)
                                                                             at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1055)
                                                                             at android.view.View.layout(View.java:15781)
                                                                             at android.view.ViewGroup.layout(ViewGroup.java:4884)
                                                                             at android.support.design.widget.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:120)
                                                                             at android.support.design.widget.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:42)
                                                                             at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1319)
                                                                             at android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:815)
                                                                             at android.view.View.layout(View.java:15781)
                                                                             at android.view.ViewGroup.layout(ViewGroup.java:4884)
                                                                             at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
                                                                             at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
                                                                             at android.view.View.layout(View.java:15781)
                                                                             at android.view.ViewGroup.layout(ViewGroup.java:4884)
                                                                             at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1677)
                                                                             at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1531)
                                                                             at android.widget.LinearLayout.onLayout(LinearLayout.java:1440)
                                                                             at android.view.View.layout(View.java:15781)
                                                                             at android.view.ViewGroup.layout(ViewGroup.java:4884)
                                                                             at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
                                                                             at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
                                                                             at android.view.View.layout(View.java:15781)
                                                                             at android.view.ViewGroup.layout(ViewGroup.java:4884)
                                                                             at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1677)
                                                                             at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1531)
                                                                             at android.widget.LinearLayout.onLayout(LinearLayout.java:1440)
                                                                             at android.view.View.layout(View.java:15781)
                                                                             at android.view.ViewGroup.layout(ViewGroup.java:4884)
                                                                             at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
                                                                             at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
                                                                             at android.view.View.layout(View.java:15781)
                                                                             at android.view.ViewGroup.layout(ViewGroup.java:4884)
                                                                             at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2361)
                                                                             at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2074)
                                                                             at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1256)
                                                                             at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6658)
                                                                             at android.view.Choreographer$CallbackRecord.run(Choreographer.java:813)
                                                                             at android.view.Choreographer.doCallbacks(Choreographer.java:613)
                                                                             at android.view.Choreographer.doFrame(Choreographer.java:583)

你有过这种问题吗?

2 个答案:

答案 0 :(得分:1)

错误是因为您没有返回任何视图

首先在onCreateViewHolder

上执行此操作
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.your_individual_layout_name, null);
final TaskViewHolder holder = new TaskViewHolder(view);
// this is where the each item is inflated.

return holder;

这将解决问题..

答案 1 :(得分:1)

你不应该从oncreateviewholder()返回null,你应该总是返回你的查看者对象,该对象已经为你的recyclerview列表的每行增加了视图。