Nitin Thakor
Nitin Thakor

Reputation: 67

RecyclerView With Fragment is not Working! Showing Error

RecyclerView with Fragment is not working, its showing error and application get crash at runtime .

public class FragmentList extends Fragment {
  String [] names={"Nitin","Manish","Ankit","Hardik","Mayur","Mayank"};

  RecyclerView mRecyclerView;
  Context context;
  RecyclerAdapter mAdapter;

  @Nullable
  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v=inflater.inflate(R.layout.fragment_list,container,false);

    setupRecyclerView();
    return v;
  }

  private void setupRecyclerView() {
    mRecyclerView= (RecyclerView)getView().findViewById(R.id.recycler_nit);
    LinearLayoutManager mLayout= new LinearLayoutManager(context);
    mLayout.setOrientation(LinearLayoutManager.VERTICAL);

    mAdapter= new RecyclerAdapter(context,names);
    mRecyclerView.setAdapter(mAdapter);
  }

Its showing error at run time and app get crash before starting,

and here is adapter class for that RecyclerView:

Context context;
String[] names;

public RecyclerAdapter(Context context, String[] names) {
  this.context = context;
  this.names = names;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

  RecyclerView.ViewHolder vh;
  View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.raw_list,parent,false);

  vh=new ViewHolder(v);

  return (ViewHolder) vh;
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
  holder.txt.setText(names[position]);
}

@Override
public int getItemCount() {
  return 0;
}

public class ViewHolder extends RecyclerView.ViewHolder {
  TextView txt;
  public ViewHolder(View itemView) {
    super(itemView);

    txt= (TextView) itemView.findViewById(R.id.name_listtext);

  }
}

its showing:

FATAL EXCEPTION: main Process: com.example.hp.newfragment, PID: 3354

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.hp.newfragment/com.example.hp.newfragment.MainActivity}: android.view.InflateException: Binary XML file line #17: Error inflating class fragment

Thanks for help in advance ......

Upvotes: 0

Views: 1840

Answers (1)

Nitin Thakor
Nitin Thakor

Reputation: 535

U have to set Layout manager

like This

private void setupRecyclerView() {
mRecyclerView= (RecyclerView)getView().findViewById(R.id.recycler_nit);
LinearLayoutManager mLayout= new LinearLayoutManager(context);
mRecyclerView.setLayoutManager(mLayout);// here u have to add 
mLayout.setOrientation(LinearLayoutManager.VERTICAL);

Upvotes: 3

Related Questions