How to inflate RecyclerView from constraintLayout in fragment? - android

My app was working completely fine , when I just had the recyclerview
in fragment's xml , but I need to wrap it in constraintlayout for
some reason but my app starts crashing after that.
error message :
*java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.*
Fragment code
public class AdminPostFragment extends Fragment {
RecyclerView recyclerView;
DatabaseReference database;
MyAdapter myAdapter;
ArrayList<Updates> list;
private FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_admin_post, container, false);
recyclerView = view.findViewById(R.id.updates_recycler);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
if (FirebaseAuth.getInstance().getCurrentUser() != null) {
FirebaseRecyclerOptions<Updates> options =
new FirebaseRecyclerOptions.Builder<Updates>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("updates"), Updates.class)
.build();
myAdapter = new MyAdapter(options);
recyclerView.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
}
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);
itemTouchHelper.attachToRecyclerView(recyclerView);
return recyclerView;
}
Fragment XML file
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="#+id/parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/updates_recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0">
</androidx.recyclerview.widget.RecyclerView>
</androidx.constraintlayout.widget.ConstraintLayout>
My Adapter code
package com.project.adminapp.adapter;
import java.util.ArrayList;
.....
public class MyAdapter extends FirebaseRecyclerAdapter< Updates ,MyAdapter.MyViewHolder> {
public MyAdapter(#NonNull FirebaseRecyclerOptions<Updates> options)
{
super(options);
}
#Override
protected void onBindViewHolder(#NonNull final MyViewHolder holder, final int position, #NonNull final Updates model) {
holder.updates_text.setText(model.getUpdate());
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.updates,parent,false);
return new MyViewHolder(v);
}
public class MyViewHolder extends RecyclerView.ViewHolder
{
TextView updates_text ;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
updates_text = (TextView) itemView.findViewById(R.id.updates_text);
}
}
}
when I am using the code like:
recyclerview =
(RecyclerView) inflater.inflate(R.layout.fragment_admin_post, container, false);
getting the ClassCastException saying ConstraintLayout cannot be cast to recyclerview.

You need fix return in onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_admin_post, container, false);
recyclerView = view.findViewById(R.id.updates_recycler);
...
return view;
}

As the ClassCastException is printing the message, you cannot cast the ConstraintLayout to RecyclerView. its because earlier, when you had only recyclerview in your fragment_admin_post.xml file the root view in that file was a recycler view that could be type casted to a RecyclerView. now that you have wrapped it in a ConstraintLayout, you may inflate the view like this:
wrappinggConstraintLayout = (ConstraintLayout) inflater.inflate(R.layout.fragment_admin_post, container, false);
if you can show more detailed code sections, it would be more understandable.

Related

Android RecyclerView GridLayout setText and onClick not working propery

I want to use GridLayout in RecyclerView and set onlickListener to every views to set texts and expand its height. The listener works but when I click one view, a view next to it is also set its text and changed its height.
When I change the column count number from 2 to 4 and then click a view, the click action changes all 4 views height and set their text.
card_item.xml.java
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/top_image_bottom_text_card"
android:layout_width="match_parent"
android:layout_height="200dp"
app:drawableTopCompat="#drawable/cherry_tomatoes_card_icon" />
TestFragment.java
public class TestFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_calendar, container, false);
RecyclerView mRecyclerView = rootView.findViewById(R.id.recycler_view);
CustomAdapter mCustomAdapter = new CustomAdapter();
mRecyclerView.setAdapter(mCustomAdapter);
GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
mRecyclerView.setLayoutManager(mLayoutManager);
return rootView;
}
CustomAdapter.java
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
public static class ViewHolder extends RecyclerView.ViewHolder {
private final TextView textViewContainingImageOnTop;
public ViewHolder(#NonNull View itemView) {
super(itemView);
textViewContainingImageOnTop = itemView.findViewById(R.id.top_image_bottom_text_card);
}
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View cardItem = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_item, parent, false);
return new ViewHolder(cardItem);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.textViewContainingImageOnTop.setOnClickListener(getOnClickListener());
holder.textViewContainingImageOnTop.setText("position: " + position);
}
private View.OnClickListener getOnClickListener() {
return view -> {
final int additionalHeight = 50;
int viewHeight = view.getHeight();
ViewGroup.LayoutParams viewLayoutParams = view.getLayoutParams();
viewLayoutParams.height = viewHeight + additionalHeight;
view.setLayoutParams(viewLayoutParams);
};
}
#Override
public int getItemCount() {
return 20;
}
}
I found this but it doesn't help me. I hope someone help me.
UPDATE
I put FrameLayout in card_item.xml like below and then when I clicked a view, it set text to the view only but it expanded itself and a view next to it both.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/top_image_bottom_text_card"
android:layout_width="match_parent"
android:layout_height="200dp"
app:drawableTopCompat="#drawable/cherry_tomatoes_card_icon" />
</FrameLayout>

I am new in Recyclerview.i want to show recyclerview for every bottomnavigationview item.how can i do it?

this is my first question in stackoverflow.if you dont understant anything i am sorry for that :should i use fragment instead Framelayout??
Here's my xml of bottomnavigation
```
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/bottomnavid"
>
</FrameLayout>
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottomnavid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:menu="#menu/bottom_nav"
/>
```
here's my xml of recyclerview xml :
```
<android.support.v7.widget.RecyclerView
android:id="#+id/featurerecyclerid"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
```
Here is my myadapter class:
```
#NonNull
#Override
public Myviewholder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(c).inflate(R.layout.cardview,viewGroup,false);
Myviewholder VH = new Myviewholder(v);
return VH;
}
//replacing the contents of a view
#Override
public void onBindViewHolder(#NonNull Myviewholder myviewholder, int i) {
myviewholder.nametext.setText(Citynames.get(i));
}
#Override
public int getItemCount() {
return Citynames.size();
}
}
the project builds withot any error but its not showing the recyclerview how can i implement recyclerview in this part,i think the problem is here..help me out please
public class Feature extends Fragment {
ArrayList<String> Citynames = new ArrayList<> (Arrays.asList("dhaka","rongpur","bagura","sylhet","vhola"));
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.feature,container,false);
final FragmentActivity c = getActivity();
final RecyclerView recyclerView = view.findViewById(R.id.featurerecyclerid);
LinearLayoutManager layoutManager = new LinearLayoutManager(c);
recyclerView.setLayoutManager(layoutManager);
Myadapter myadapter = new Myadapter(Citynames,c);
recyclerView.setAdapter(myadapter);
return inflater.inflate(R.layout.feature,container,false);
}
}
```
I'm not sure what really you are trying to do,what appears to me you wronged with the layout,before trying recycler view first practice some different types of layout which will help to understand you how design object works in xmal attribute,try your layout like this
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/bottomnavid"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/featurerecyclerid"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottomnavid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:menu="#menu/bottom_nav"
/>
</FrameLayout>
Did you create any inner class for initializing your R.layout.cardview ?Another thing is you have to initialize and set your RecyclerView with Adapter in onViewCreated() method in your Fragment.
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
final FragmentActivity c = getActivity();
final RecyclerView recyclerView = view.findViewById(R.id.featurerecyclerid);
LinearLayoutManager layoutManager = new LinearLayoutManager(c);
recyclerView.setLayoutManager(layoutManager);
Myadapter myadapter = new Myadapter(Citynames,c);
recyclerView.setAdapter(myadapter);
}

Migrating RecyclerView from Activity to Fragment - can't use findViewById

I copied the following code from the MainActivity to a separate fragment, but I can't get findViewById to work:
I get "cannot resolve method findViewById(int)"
these are the related files:
**Also as a beginner, could you let me know if there's a general problem with my code that needs to fixed?
MyFragment.java:
public class MyFragment extends Fragment {
public myFragment() {
// Required empty public constructor
}
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_my, container, false);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
//placeholder data
String[] myDataset = new String[16];
myDataset[0] = "Data0";
myDataset[1] = "Data1";
myDataset[2] = "Data2";
myDataset[3] = "Data3";
myDataset[4] = "Data4";
myDataset[5] = "Data5";
myDataset[6] = "Data6";
myDataset[7] = "Data7";
myDataset[8] = "Data8";
myDataset[9] = "Data9";
myDataset[10] = "Data10";
myDataset[11] = "Data11";
myDataset[12] = "Data12";
myDataset[13] = "Data13";
myDataset[14] = "Data14";
myDataset[15] = "Data15";
// specify an adapter (see also next example)
mAdapter = new MyAdapter(myDataset);
mRecyclerView.setAdapter(mAdapter);
}
}
MyAdapter.java:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private String[] mDataset;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class MyViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView upTv;
public TextView downTv;
public View layout;
public MyViewHolder(View v) {
super(v);
layout = v;
upTv = (TextView)v.findViewById(R.id.upTv);
downTv = (TextView)v.findViewById(R.id.downTv);
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(String[] myDataset) {
mDataset = myDataset;
}
// Create new views (invoked by the layout manager)
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_text_view, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.upTv.setText(mDataset[position]);
holder.downTv.setText(mDataset[position]);
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.length;
}
}
fragment_my.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="4dp"
android:scrollbars="vertical"/>
</android.support.constraint.ConstraintLayout>
my_text_view.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip" >
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_marginRight="6dip"
android:contentDescription="TODO"
android:src="#drawable/ic_launcher_background" />
<TextView
android:id="#+id/downTv"
android:layout_width="fill_parent"
android:layout_height="26dip"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_toRightOf="#id/icon"
android:text="downTv"
android:textSize="12sp" />
<TextView
android:id="#+id/upTv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignWithParentIfMissing="true"
android:layout_toRightOf="#id/icon"
android:gravity="center_vertical"
android:text="upTv"
android:textSize="16sp" />
</RelativeLayout>
Here's your problem:
return inflater.inflate(R.layout.fragment_my, container, false);
You cannot add more code after the return statement. You will need to take the reference of the inflated view and use it to find the reference of child views.
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
// other code
return rootView;
A really good way to use fragments is to initialize certain variables(e.g- activity,context,root view etc) associated with the parent activity when you switch to a fragment.
for example you can do sth like,
private Context context;
private MainActivity activity; //Let MainActivity is your parent activity
private View view; //fields kept inside the fragment class,now we need to keep them initialized
//initialize activity/context from onAttach
#Override
public void onAttach(Context c) {
super.onAttach(c);
Activity a;
context=c;
if (c instanceof Activity){
a=(Activity) c;
if(a instanceof MainActivity)
activity=(MainActivity) a;
}
}
//initialize view from onViewCreated
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.view=view;
}
now you can use them wherever u want inside the fragment class without triggering any nullptrs and other stuff
e.g- you can go
this.view.findViewById(your_resId);
this.activity.getSupportFragmentManager();
etc and a lot of other stuffs when you need ,using these fields you initialized
also specifically in this case of using recyclerView dont forget to call,
adapter.notifyDataSetChanged() whenever you think the list you are showing in the recyclerView went through some change.
I do not have enough reputation to comment so i am writing this as answer to your comment.
You need to notify adapter using below code.
mAdapter.notifyDataSetChanged();

RecyclerView won't display my database content

I have a database of Users and I'm trying to use a RecyclerView to display every User entry I have. From my logs, I can tell that my RecyclerView isn't even being interacted with. Here is the class where I call it:
public class WelcomePage extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_page);
FragmentManager manager = getFragmentManager();
RecyclerFragment mRecyclerFragment = new RecyclerFragment();
if(mRecyclerFragment == null) {
manager.beginTransaction()
.add(R.id.recycler, mRecyclerFragment)
.commit();
}
}
}
This is my holder class:
public class RecyclerHolder extends RecyclerView.ViewHolder{
private static final String TAG = "RecyclerHolder";
private TextView mFullName;
private TextView mBirthDate;
private TextView mHomeTown;
private TextView mBio;
User mUser;
RecyclerHolder(View itemView){
super(itemView);
mFullName = (TextView)itemView.findViewById(R.id.text_view_name);
mBirthDate = (TextView)itemView.findViewById(R.id.text_view_birthday);
mHomeTown = (TextView)itemView.findViewById(R.id.text_view_hometown);
mBio = (TextView)itemView.findViewById(R.id.text_view_bio);
public void bind(User user) {
mUser = user;
mFullName.setText(user.getFullName());
mBirthDate.setText(user.getBirthDate().toString());
mHomeTown.setText(user.getHomeTown());
mBio.setText(user.getBio());
}
}
Here's my adapter class:
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerHolder> {
private ArrayList<User> mUsers;
public RecyclerAdapter(ArrayList<User> user) {
mUsers = user;
}
#Override
public RecyclerHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.view_recycler, parent, false);
RecyclerHolder holder = new RecyclerHolder(view);
return holder;
}
#Override
public void onBindViewHolder(RecyclerHolder holder, int position){
holder.bind(mUsers.get(position));
}
#Override
public int getItemCount() {
return mUsers.size();
}
}
Here's my fragment class:
public class RecyclerFragment extends Fragment {
private RecyclerView mRecyclerView;
DBCursorWrapper db;
public RecyclerFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_recycler, container, false);
mRecyclerView = (RecyclerView)view.findViewById(R.id.recycler);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
RecyclerAdapter adapter = new RecyclerAdapter(db.getUserList());
mRecyclerView.setAdapter(adapter);
return view;
}
}
Here is the XML for my holder:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/view_recycler">
<TextView
android:id="#+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
/>
</LinearLayout>
Here is my XML for my fragment:
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.csc214.just4kas.project02.RecyclerFragment">
</android.support.v7.widget.RecyclerView>
Here is my XML for where I call my RecyclerView:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/frame_layout_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.csc214.just4kas.project02.WelcomePage">
</FrameLayout>
The getUserList() has been tested individually and works perfectly!
Any help would be super appreciated! I just want a RecyclerView of all the contents in my database!! Thanks!
I think you may be using the wrong layout when you replace add it to the main activity. try (R.id.frame_layout_recycler_view) instead or R.id.recycler.
Or there might be a issue when use the database in this context.

Why does Recycler view gives null pointer exception?

I am using RecyclerView in a fragment, it is generate a NullPointerException and I cannot understand the reason.
Here is my fragment activity:
public class Recharges extends Fragment {
public RecyclerView recyclerView;
private List<GetRecharge> rechargeList = new ArrayList<>();
public RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
ImageView image1, image2;
#Nullable #Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Toolbar myToolbar = (Toolbar) getActivity().findViewById(R.id.my_toolbar);
((AppCompatActivity) getActivity()).setSupportActionBar(myToolbar);
View rootView = inflater.inflate(R.layout.recharges, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview1);
recyclerView.setHasFixedSize(true);
final FragmentActivity c = getActivity();
layoutManager = new LinearLayoutManager(c);
recyclerView.setLayoutManager(layoutManager);
adapter = new Adapterrecharge(rechargeList);
recyclerView.setAdapter(adapter);
prepareRechargeData();
return rootView;
}
private void prepareRechargeData() {
GetRecharge recharge = new GetRecharge("Mad Max: Fury Road" );
rechargeList.add(recharge);
adapter.notifyDataSetChanged();
}
}
Here the adapter class:
public class Adapterrecharge extends RecyclerView.Adapter<Adapterrecharge.MyViewHolder> {
private List<GetRecharge> rechargeList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
ImageView image;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
}
}
public Adapterrecharge(List<GetRecharge> rechargeList) {
this.rechargeList = rechargeList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.rechargelist, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
GetRecharge recharge = rechargeList.get(position);
holder.title.setText(recharge.getTitle());
}
#Override
public int getItemCount() {
return rechargeList.size();
}
}
I seem to be inflating the correct layout but still getting the error.
here is the logcat error
java.lang.NullPointerException
at com.example.aadesh.walletuncle.Adapterrecharge.onBindViewHolder(Adapterrecharge.java:53)
at com.example.aadesh.walletuncle.Adapterrecharge.onBindViewHolder(Adapterrecharge.java:21)
here is the recyclerview item layout.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/text"/>
here is the main layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light">
<TextView
android:text="Recharge"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textColor="#ffffff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView4"
android:layout_weight="1" />
</android.support.v7.widget.Toolbar>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
android:id="#+id/recyclerview1">
</android.support.v7.widget.RecyclerView>
there are couple of problems
you are populating prepareRechargeData() list data after you have set your adapter - so your list rechargelist doesn't have any data
in your onCreateViewHolder() your are using wrong layout R.layout.rechargelist
in your view Holder you are giving wrong id for textview R.id.title
try this:
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Toolbar myToolbar = (Toolbar) getActivity().findViewById(R.id.my_toolbar);
((AppCompatActivity) getActivity()).setSupportActionBar(myToolbar);
View rootView = inflater.inflate(R.layout.recharges, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview1);
recyclerView.setHasFixedSize(true);
final FragmentActivity c = getActivity();
layoutManager = new LinearLayoutManager(c);
recyclerView.setLayoutManager(layoutManager);
/*recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter((RecyclerView.Adapter) adapter);*/
prepareRechargeData();
adapter = new Adapterrecharge(rechargeList);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
return rootView;
}
Change your adapter to:
public class Adapterrecharge extends RecyclerView.Adapter<Adapterrecharge.MyViewHolder> {
private List<GetRecharge> rechargeList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
ImageView image;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.text);
}
}
public Adapterrecharge(List<GetRecharge> rechargeList) {
this.rechargeList = rechargeList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recyclerview_item_layout, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
GetRecharge recharge = rechargeList.get(position);
holder.title.setText(recharge.getTitle());
}
#Override
public int getItemCount() {
return rechargeList.size();
}
}
You are miss matching id of Textview.
Instead of
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/text"/>
</LinearLayout>
Use this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/title"/>
</LinearLayout>
As you are using wrong id of Textview in MyViewHolder class.
The problem is due to mismatch ids. ID of TextView in xml ("text") and the one inflated in ViewHolder class ("title") are different.
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/text"/>
Adapter class
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
}

Categories

Resources