Why does Recycler view gives null pointer exception? - android

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);
}

Related

Disable Scrolling in RecyclerView

In code, RecyclerView is in ViewPager.
I wanted enable scrolling in ViewPager when RecyclerView larger than ViewPager.
Unfold All list in recyclerView, How can scroll only viewPager?
I did nestedScrollingEnabled="false" but not working and not good way.
Here is my code
fragment.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="StoreFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="20dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp">
//...
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="150dp"
android:gravity="center"
android:background="#color/colorGray">
//...
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp">
//...
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerViewMenu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textMenuMain"
android:nestedScrollingEnabled="false"/>
</RelativeLayout>
activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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_width="match_parent"
android:layout_height="match_parent"
tools:context="Activity">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Toolbar...>
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="1dp"
app:tabTextColor="#000" />
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
</androidx.viewpager.widget.ViewPager>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</RelativeLayout>
Fragment.java
public class Fragment extends Fragment {
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
List<String> list;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment, container, false);
recyclerView = viewGroup.findViewById(R.id.recyclerViewMenu);
layoutManager = new LinearLayoutManager(getContext());
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
list = new ArrayList<>();
for (int i = 0; i <= 10; i++){
list.add(i+1 + "List");
}
adapter = new MenuListAdapter(list);
recyclerView.setAdapter(adapter);
return viewGroup;
}
}
class MenuListAdapter extends RecyclerView.Adapter<MenuListAdapter.MyViewHolder> {
List<String> list ;
public MenuListAdapter(List<String> lists){
this.list = lists;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.store_menu_item, parent, false);
MyViewHolder viewHolder = new MyViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
String text = list.get(position);
holder.textMenuName.setText(text);
holder.textMenuPrice.setText("Price:00");
}
#Override
public int getItemCount() {
return this.list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView textMenuName;
TextView textMenuPrice;
Button buttonCartAdd;
public MyViewHolder(View view){
super(view);
textMenuName = (TextView) view.findViewById(R.id.textMenuName);
textMenuPrice = (TextView) view.findViewById(R.id.textMenuPrice);
buttonCartAdd = (Button) view.findViewById(R.id.buttonCartAdd);
}
}
}
Activity.java
public class Activity extends AppCompatActivity {
TabLayout tabLayout;
ViewPager viewPager;
TextView textViewNotice;
TextView textViewTitle;
String title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_store_detail);
tabLayout = findViewById(R.id.tabs);
viewPager = findViewById(R.id.pager);
textViewNotice = findViewById(R.id.textNotice);
textViewTitle = findViewById(R.id.textTitle);
textViewNotice.setSelected(true);
Intent intent = getIntent();
title = intent.getExtras().getString("Title");
textViewTitle.setText(title);
tabLayout.addTab(tabLayout.newTab().setText("정보"));
tabLayout.addTab(tabLayout.newTab().setText("리뷰"));
Activity.MyPagerAdapter adapter = new Activity.MyPagerAdapter(getSupportFragmentManager());
Fragment Fragment = new Fragment();
adapter.addItem(Fragment);
//...
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
class MyPagerAdapter extends FragmentStatePagerAdapter {
ArrayList<Fragment> items = new ArrayList<>();
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
public void addItem(Fragment item) {
items.add(item);
}
#NonNull
#Override
public Fragment getItem(int position) {
return items.get(position);
}
#Override
public int getCount() {
return items.size();
}
}
}
Try this
LinearLayoutManager layoutManager = new LinearLayoutManager(context) {
#Override
public boolean canScrollVertically() {
return false;
}
};
recyclerView.setLayoutManager(layoutManager);

Troubles with my very simple Android RecycleView test

Good day.
I have a very simple Android RecycleView test:
in build.gradle:
dependencies {
...
implementation 'com.android.support:recyclerview-v7:28.0.0'
...
}
in layout activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
in layout activity_list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="72dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:gravity="center_vertical">
<TextView
android:id="#+id/itemNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="itemNumber"/>
</FrameLayout>
in MainActivity.java:
package com.as.recyclerview_test;
import ...;
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
public static String[] myDataset = {"111", "222", "333"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyAdapter(myDataset);
mRecyclerView.setAdapter(mAdapter);
}
}
in MyAdapter.java:
package com.as.recyclerview_test;
import ...;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private String[] mDataset;
public MyAdapter(String[] myDataset) {
mDataset = myDataset;
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
public TextView itemNumber;
public MyViewHolder(TextView v) {
super(v);
itemNumber = v.findViewById(R.id.itemNumber);
}
}
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
TextView v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.activity_list_item, viewGroup, false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.itemNumber.setText(mDataset[position]);
}
#Override
public int getItemCount() {
return mDataset.length;
}
}
When I run this project I got app stop message and
FATAL EXCEPTION: main
with
java.lang.ClassCastException: android.widget.FrameLayout cannot be cast to android.widget.TextView at com.as.recyclerview_test.MyAdapter.onCreateViewHolder
I used the official [https://developer.android.com/guide/topics/ui/layout/recyclerview#java] pattern.
What's wrong in my code?
Thank you in advance...
You have error in onCreateViewHolder method. You are trying to cast FrameLayout to TextView while inflating layout. Here is correct method.
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.activity_list_item, viewGroup, false);
return new MyViewHolder(v);
}
Also you should pass View to ViewHolder constructor, not TextView.
public static class MyViewHolder extends RecyclerView.ViewHolder {
public TextView itemNumber;
public MyViewHolder(View v) {
super(v);
itemNumber = v.findViewById(R.id.itemNumber);
}
}
You could try this:
FrameLayout view = (FrameLayout)(LayoutInflater.From(viewGroup.getContext()).
.inflate(R.layout.activity_list_item, viewGroup, false));
MyViewHolder vh = new MyViewHolder(view);
return MyViewHolder;

error RecyclerView: No adapter attached; skipping layout when running program

I have tried answer at stackoverflow that relate to my problem. I wanna to show a data from firebase in imageview and textview. But there's error RecyclerView: No adapter attached; skipping layout. This is my coding :
MenuManajemenKendaraanFragment.java
public class MenuManajemenKendaraanFragment extends Fragment {
private RecyclerView recyclerView;
private MenuManajemenKendaraanAdapter adapter;
private DatabaseReference mDatabase;
//private ProgressDialog progressDialog;
private List<DataKendaraan> dataKendaraan;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getActivity().setTitle("Manajemen Kendaraan");
View v = inflater.inflate(R.layout.fragment_menu_manajemen_kendaraan, container, false);
FloatingActionButton fab_tambah_kendaraan = (FloatingActionButton) v.findViewById(R.id.fab);
mDatabase = FirebaseDatabase.getInstance().getReference();
recyclerView = (RecyclerView) v.findViewById(R.id.listViewKendaraan);
recyclerView.setHasFixedSize(true);
final FragmentActivity c = getActivity();
LinearLayoutManager layoutManager = new LinearLayoutManager(c);
recyclerView.setLayoutManager(layoutManager);
dataKendaraan = new ArrayList<>();
mDatabase = FirebaseDatabase.getInstance().getReference(Constants.DATABASE_PATH_UPLOADS);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//dismissing the progress dialog
//iterating through all the values in database
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
DataKendaraan upload = postSnapshot.getValue(DataKendaraan.class);
dataKendaraan.add(upload);
}
adapter = new MenuManajemenKendaraanAdapter(getActivity(), dataKendaraan);
//adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
fragment_menu_manajemen_kendaraan.xml
<FrameLayout 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_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:clipToPadding="false"
android:padding="5dp"
android:scrollbars="vertical"
android:id="#+id/listViewKendaraan">
</android.support.v7.widget.RecyclerView>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:clickable="true"
app:fabSize="normal"
android:src="#drawable/ic_add_fab"
android:layout_gravity="end|bottom"/>
</FrameLayout>
MenuManajemenKendraanAdapter.java
public class MenuManajemenKendaraanAdapter extends RecyclerView.Adapter<MenuManajemenKendaraanAdapter.ViewHolder> {
private Context context;
private List<DataKendaraan> dataKendaraan;
public MenuManajemenKendaraanAdapter(Context context, List<DataKendaraan> dataKendaraan) {
this.dataKendaraan = dataKendaraan;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.adapter_menu_manajemen_kendaraan, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
DataKendaraan data = dataKendaraan.get(position);
holder.tipeKendaraan.setText(data.getTipeKendaraan());
Glide.with(context).load(data.getUriFotoKendaraan()).into(holder.fotoKendaraan);
}
#Override
public int getItemCount() {
return dataKendaraan.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView tipeKendaraan;
public ImageView fotoKendaraan;
public ViewHolder(View itemView) {
super(itemView);
tipeKendaraan = (TextView)itemView.findViewById(R.id.tipe_kendaraan);
}
}
adapter_menu_manajemen_kendaraan.xml
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="90dp"
android:layout_margin="5dp">
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<ImageView
android:id="#+id/imageViewFotoKendaraan"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:layout_marginRight="10dp"/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="5">
<TextView
android:text="Tipe Kendaraan"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-black"
android:textColor="#color/colorAccent"
android:paddingBottom="2dp"
android:id="#+id/tipe_kendaraan"
android:textSize="16sp"/>
</LinearLayout>
</LinearLayout>
Thank you so much for your help.
View v = LayoutInflater.from(context) .inflate(R.layout.adapter_menu_manajemen_kendaraan, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;

blank Recyclerview inside Fragment

I am using fragment and recyclerview together. I also have database and I want to query results coming from the database and display the results inside the activity.
However every time I try to run the application and switch to the part to get and view the results, I don't seem to get anything. No results at all just blank. I don't know why it's not showing up.
This is my full code
Sample class
public class Sample extends Fragment {
private View rootView;
public Sample() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
rootView = inflater.inflate(sample, container, false);
RecyclerView mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView_sample);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.setHasFixedSize(true);
DatabaseHandler db= new DatabaseHandler(getActivity());
List<SampleModel> list = db.getResults();
SampleAdapter sampleAdapter = new SampleAdapter(list);
mRecyclerView.setAdapter(sampleAdapter);
return rootView;
}
}
Adapter Class
public class SampleAdapter extends RecyclerView.Adapter <SampleAdapter.ViewHolder> {
private List<SampleModel> list;
private Context mContext;
public SampleAdapter (List<SampleModel> list) {
list = list;
}
#Override
public SampleAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.sample_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(SampleAdapter.ViewHolder holder, int position) {
SampleModel sample = list.get(holder.getAdapterPosition());
holder.title.setText(sample.getTitle())
}
#Override
public int getItemCount() {
return (list != null? list.size():0);
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public ViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title);
}
}
}
XML
sample.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<include layout="#layout/sample_recyclerview" />
</android.support.design.widget.CoordinatorLayout>
sample_recyclerview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView_sample"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clipToPadding="false"/>
</RelativeLayout>
sample_item.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:focusable="true"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"
card_view:cardBackgroundColor="#808080">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffffff" />
</LinearLayout>
</android.support.v7.widget.CardView>
In your SampleAdapter change
list = list;
to
this.list = list;
Your Adapter constructor is wrong. You are not passing the dataSource to your adapter. Change it to
public SampleAdapter (List<SampleModel> list) {
this.list = list;
}
Furthermore you have to notify the adapter that you changed your dataSource. You do that by calling the method notifyDataSetChanged
SampleAdapter sampleAdapter = new SampleAdapter(list);
mRecyclerView.setAdapter(sampleAdapter);
sampleAdapter.notifyDataSetChanged();
RecyclerViews will return nothing if the size is not rightly returned(e.g using : return 0;)
change your code from :
public int getItemCount() {
return (list != null? list.size():0);
To:
public int getItemCount() {
return list.size();

Unable to display string-array to custom Recycler View?

As I see many tutorials on website, most of they define the String data in java like String[] data={"value","value2',"value3"}; but its not the correct way in real time application i guess. In my app I will be using other languages too so I need to define in the xml. No matter i call them using below code:
onCreateView
String[] eArray=getActivity().getResources().getStringArray(R.array.english_names);
and call them like
names.add(new Name(eArray));
but when i hover mouse on eArray it shows error like Name (java.lang.String) in Name cannot be applied to (java.lang.String[])
and I know I must pass other value to array but how? I change error line and it keeps showing other and other. I google many tuts site but all of them are defining string pragmatically.
I made a custom recyclerview, Below is a code of it
cardview.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="8dp"
app:cardUseCompatPadding="true"
app:cardBackgroundColor="#android:color/transparent"
android:elevation="0dp">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25sp"
android:paddingLeft="10dp"
android:textColor="#4928ef"
android:textStyle="italic"/>
</android.support.v7.widget.CardView>
recyclerview.xml
<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/linearlayout"
android:background="#drawable/big_img_boy_wp">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rv">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
cardview.java
public class cardView extends Fragment {
TextView textView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.card_view,container,false);
textView= (TextView) view.findViewById(R.id.textView);
// Typeface typeface=Typeface.createFromAsset(getActivity().getAssets(),"fonts/Cavorting.otf");
// textView.setTypeface(typeface);
return view;
}
}
Name.java
public class Name {
String textView;
Name(String textView){
this.textView=textView;
}
}
recycler.java
public class Recycler extends Fragment {
private List<Name> names;
RecyclerView rv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.recyclerview,container,false);
rv= (RecyclerView) view.findViewById(R.id.rv);
String[] eArray=getActivity().getResources().getStringArray(R.array.english_names);
LinearLayoutManager llm=new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
rv.setHasFixedSize(true);
initializeData();
initializeAdapter();
return view;
}
private void initializeAdapter() {
rvadapter adapter=new rvadapter(names);
rv.setAdapter(adapter);
}
public void initializeData() {
names=new ArrayList<>();
names.add(new Name("Anish"));
names.add(new Name(eArray));
}
}
rvadapter.java
public class rvadapter extends RecyclerView.Adapter<rvadapter.NameViewHolder> {
public static class NameViewHolder extends RecyclerView.ViewHolder{
CardView cv;
TextView textView;
public NameViewHolder(View itemView) {
super(itemView);
cv= (CardView) itemView.findViewById(R.id.cardview);
textView= (TextView) itemView.findViewById(R.id.textView);
}
}
List<Name> names;
public rvadapter(List<Name> names) {
this.names=names;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public NameViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view,parent,false);
NameViewHolder nvh=new NameViewHolder(v);
return nvh;
}
#Override
public void onBindViewHolder(NameViewHolder holder, int position) {
holder.textView.setText(names.get(position).textView);
}
#Override
public int getItemCount() {
return names.size();
}
}
Please also take a look at my cardview.java where i put commented, that font also doesn't change. I put font inside assets then font folder. This is my second question in stackoverflow but my first question was as not answered correctly, if you can please take a look at that toClick here to to look by another problem too. Thanks in Advance!!
for (int i = 0; i < eArray.length; i++) {
names.add(new Name(eArray[i]));
}

Categories

Resources