How to arrange the data on RecycleView in android? - java

I would like to use RecycleView for displaying my array of data.
This is my Adapater class which is setting data on view.
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.MyViewHolder>{
private Context context;
private List<Pojo> dataList;
public DataAdapter(Context context, List<Pojo> dataList) {
this.context = context;
this.dataList = dataList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_main,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.categoryTV.setText(dataList.get(position).getGameName());
}
#Override
public int getItemCount() {
return dataList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
public TextView categoryTV;
public MyViewHolder(View itemView) {
super(itemView);
categoryTV = (TextView) itemView.findViewById(R.id.text);
}
}
}
This is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:id="#+id/rellayout"
tools:context="com.acknotech.kiran.retrofit_second.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/text"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
This is MainActivity..
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private DataAdapter dataAdapter;
private List<Pojo> dataArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews(){
recyclerView=(RecyclerView) findViewById(R.id.my_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
loadJSON();
}
private void loadJSON(){
dataArrayList = new ArrayList<>();
Retrofit retrofit=new Retrofit.Builder().baseUrl("my url").addConverterFactory(GsonConverterFactory.create()).build();
AllGamesAPI requestInterface=retrofit.create(AllGamesAPI.class);
Call<List<Pojo>> call= requestInterface.getJSON();
call.enqueue(new Callback<List<Pojo>>() {
#Override
public void onResponse(Call<List<Pojo>> call, Response<List<Pojo>> response) {
dataArrayList = response.body();
dataAdapter=new DataAdapter(getApplicationContext(),dataArrayList);
recyclerView.setAdapter(dataAdapter);
}
#Override
public void onFailure(Call<List<Pojo>> call, Throwable t) {
Log.e("Error",t.getMessage());
}
});
}
}
When i try to execute it always printing only one item at a time but in dataList i have 11 items.
How to use RecyclerView to get all items in a page?
Thanks & Regards

You shouldn't inflate the activities layout in onCreateViewHolder, but instead inflate a layout for only one item (e.g. android.R.layout.simple_list_item_1, or a custom one). This layout should not use match_parent for the height of items.

Related

Android RecyclerView - How to get items selected in Fragment class which calls CustomAdapter. I know how to use get(getAbsoluteAdapterPosition()

Below recycler view code is working fine and I can Toast message what recycler view position was selected in RecycleAdapter class. But I want to know how can I get what recycler position selected in HomeFragment class?. I tried to get position by setting onclick listener to Imageview and Textview but gives error as reference to Null. Basically I want to use get(getAbsoluteAdapterPosition() in HomeFragment class to know what item selected and navigate to another Fragment. get(getAbsoluteAdapterPosition() is working as expected inside RecycleAdapter.class
binding.recyclerview.setOnClickListener is not working in HomeFragment.class. no error but no when I click on recycler views this is not shooted.
txt.setOnClickListener is giving error as null refernce which makes sense. because this is inflated in Adapter class but trying to refer in HomeFragement class. So how can I get what selected in homefragment.class. Thanks in advance
HomeFragment.class
'''
public class HomeFragment extends Fragment {
HomeFragmentBinding binding;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.id.home_fragment, container, false);
return v;
}
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
%% some code here %%
recycleAdapter = new RecycleAdapter(list);
binding.recyclerview.setAdapter(recycleAdapter);
TextView txt = (TextView) binding.getRoot().findViewById(R.id.recycler_text);
txt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "Clicked on Image", Toast.LENGTH_SHORT).show();
}
});
binding.recyclerview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "RecyclerView clicked", Toast.LENGTH_SHORT).show();
Log.d("RecyclerViewclicked", " --- ");
}
});
'''
RecycleAdapter.class
'''
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.MyViewHolder>{
RecyclerRowItemsBinding binding;
List<IconsModel> iconsList;
public RecycleAdapter(List<IconsModel> iconslist) {
this.iconsList = iconslist;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflator = LayoutInflater.from(parent.getContext());
View v = inflator.inflate(R.layout.recycler_row_items, parent, false);
MyViewHolder myviewholder = new MyViewHolder(v);
return myviewholder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
IconsModel iconModel = iconsList.get(position);
holder.imageView.setImageResource(iconModel.getImageid());
holder.recyclertext.setText(iconModel.getIconName());
}
#Override
public int getItemCount() {
//return 20;
return iconsList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
ImageView imageView;
TextView recyclertext;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.recycler_image);
recyclertext = itemView.findViewById(R.id.recycler_text);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
IconsModel iconModel = iconsList.get(getAbsoluteAdapterPosition());
Toast.makeText(***itemView.getContext(), "Clicked on "+iconModel.getIconName()***, Toast.LENGTH_SHORT).show();
}
});
}
}
;
}
'''
home_fragment.xml
<androidx.constraintlayout.widget.ConstraintLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="1dp"
tools:layout_editor_absoluteY="1dp"
app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"/>
</androidx.constraintlayout.widget.ConstraintLayout>
'''
recycler_row.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_gravity="center"
android:layout_margin="5dp"
android:orientation="horizontal"
app:cardCornerRadius="5dp"
app:cardElevation="5dp"
app:cardBackgroundColor="#color/home_bg_cardview">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground"
android:backgroundTint="#color/home_bg_cardview"
android:weightSum="2">
<ImageView
android:id="#+id/recycler_image"
android:layout_width="0dp"
android:layout_height="120dp"
android:layout_weight="0.5"
app:srcCompat="?android:attr/actionModeWebSearchDrawable"
tools:ignore="ContentDescription" />
<TextView
android:id="#+id/recycler_text"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginBottom="29dp"
android:layout_weight="1.5"
android:gravity="center"
android:text="Browse Items"
android:textAlignment="center"
android:textSize="24sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
If you want to get the click event of recyclerview item in HomeFragment ,
Interface It's a good choice
//RecycleAdapter
private RecyclerViewListener recyclerViewListener
public void setRecyclerViewListener(RecyclerViewListener recyclerViewListener){
this.RecyclerViewListener recyclerViewListener ;
}
public Interface RecyclerViewListener{
void onClick(View view);
}
class MyViewHolder extends RecyclerView.ViewHolder{
ImageView imageView;
TextView recyclertext;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
recyclertext = itemView.findViewById(R.id.recycler_text);
recyclertext .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(recyclerViewListener !=null)recyclerViewListener.onClick(v)
}
});
}
//HomeFragment
recycleAdapter.setRecyclerViewListener(new RecyclerViewListener{
#Override
public void onClick(View v) {
//todo
}
})
Create Interface Class in your Project
public interface ItemClick {
public void onClick(IconsModel IconsModel,int pos);
}
Interface class call your recyclerAdapter
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.MyViewHolder> {
Context context;
List<IconsModel> iconsList;
ItemClick click;
public TokensListAdapter(Context context, List<IconsModel> iconsList, ItemClick click) {
this.context = context;
this.tokensModelList = tokensModelList;
this.click = click;
}
#NonNull
#Override
public TokensListAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.R.layout.recycler_row_items,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull TokensListAdapter.ViewHolder holder, int position) {
IconsModel iconModel = iconsList.get(position);
holder.imageView.setImageResource(iconModel.getImageid());
holder.recyclertext.setText(iconModel.getIconName());
holder.itemView.setOnClickListener(v -> {
click.onClick(iconModel,position);
});
}
#Override
public int getItemCount() {
return iconsList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView recyclertext;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.recycler_image);
recyclertext = itemView.findViewById(R.id.recycler_text);
}
}
}
Interface Class implement Your Fragment
public class HomeFragment extends Fragment implements ItemClick {
//adapter assign
recycleAdapter = new RecycleAdapter(getContext,list,this);
override method import your fragment
#Override
public void onClick(ItemCLick click, int pos) {
Toast.makeText(getContext(), "Clicked" + pos, Toast.LENGTH_SHORT).show();
}

Nested RecyclerViews

I'm creating a calendar app, with each month being displayed using a RecylcerView. Inside each day of each month, there is another RecyclerView to display events on that day. I'm using the custuomLinearLayoutManager from https://stackoverflow.com/a/38513905/13199395, and I've looked at many examples. My code for the nesting is very similar to them but for some reason is not working. Any help as to why is not working would be much appreciated.
The month view:
<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:orientation="vertical"
tools:context=".MonthViewActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/calView"
android:layout_width="match_parent"
android:layout_height="581dp"
android:layout_gravity="bottom" />
</FrameLayout>
The view for each day:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/dayView"
android:layout_width="145px"
android:layout_height="265px"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/eventDayView"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
and the view for the inner recyclerView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/showEvents"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/eventName"
android:layout_width="145px"
android:layout_height="wrap_content" />
</LinearLayout>
The adapter for the main recyclerview:
public class MonthViewAdapter extends RecyclerView.Adapter<MonthViewAdapter.ViewHolder> {
Context context;
ArrayList<Day> days;
CustomLinearLayoutManager l;
public MonthViewAdapter(Context context, ArrayList<Day> arrayList) {
this.context = context;
this.days = arrayList;
}
#NonNull
#Override
public MonthViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.content_events, parent, false);
return new ViewHolder(view, this.mOnDayClickListener);
}
#Override
public void onBindViewHolder(MonthViewAdapter.ViewHolder holder, int position) {
l = new CustomLinearLayoutManager(context, LinearLayout.VERTICAL, false);
ViewGroup.LayoutParams params=holder.r.getLayoutParams();
params.height=100;
holder.r.setLayoutParams(params);
holder.r.setLayoutManager(l);
EventViewAdapter adapter = new EventViewAdapter(context, days.get(position).getEvents(), this.mOnDayClickListener);
holder.r.setAdapter(adapter);
holder.t.setText(days.get(position).getMonthDayNumber());
}
#Override
public int getItemCount() {
return days.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
RecyclerView r;
TextView t;
FrameLayout f;
LinearLayout l;
public ViewHolder(View itemView) {
super(itemView);
l = itemView.findViewById(R.id.dayView);
t = itemView.findViewById(R.id.dayNum);
r = itemView.findViewById(R.id.eventDayView);
}
}
}
The adapter for the inner RecyclerView:
public class EventViewAdapter extends RecyclerView.Adapter<EventViewAdapter.ViewHolder> {
Context context;
ArrayList<Event> events;
public EventViewAdapter (Context context, ArrayList<Event> arrayList) {
this.context = context;
this.events = arrayList;
}
#Override
public EventViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.content_single_event, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(EventViewAdapter.ViewHolder holder, int position) {
Log.d("event", Integer.toString(events.size()));
holder.eventName.setText(events.get(position).getName());
}
#Override
public int getItemCount() {
return events.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView eventName;
LinearLayout linearLayout;
public ViewHolder(View itemView) {
super(itemView);
eventName = itemView.findViewById(R.id.eventName);
linearLayout = itemView.findViewById(R.id.showEvents);
}
}
}
The custom linear layout manager: https://stackoverflow.com/a/38513905/13199395
And the activity
public class MonthViewActivity extends AppCompatActivity{
RecyclerView month;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_month_view);
month.setHasFixedSize(true);
month.addItemDecoration(new DividerItemDecoration(this,
DividerItemDecoration.HORIZONTAL));
month.addItemDecoration(new DividerItemDecoration(this,
DividerItemDecoration.VERTICAL));
GridLayoutManager g = new GridLayoutManager(this, 7);
month.setLayoutManager(g);
ArrayList<Day> day = new ArrayList<>();
LocalDate dd = LocalDate.now();
Day d1 = new Day(dd);
Day d2 = new Day(dd.plusDays(1));
Day d3 = new Day(dd.plusDays(2));
d1.addEvent(new Event("a"));
day.add(d1);
adapter = new MonthViewAdapter(this, day, this);
month.setAdapter(adapter);
}
}
Each element of the list that I pass into the month view adapter has a list of events that are then passed into the event adapter. However, each day in the grid only shows one of the events, it does not show all of the events in the event list on each day. Why is this happening and how can I fix it? I am getting an error (java.lang.IndexOutOfBoundsException: Invalid item position) on
View view = recycler.getViewForPosition(position);
in the custom layout manager, but the program does not crash.

How to get data from cloud firestore and display it with recycler view

I have a cloud firestore database with a collection named Bus and three documents inside it as it is shown in the image
database picture
I have followed what is written in this link
How to display data from Firestore in a RecyclerView with Android?
three recycler views are being created and displayed but with empty data
also when I add a fourth document to Bus four recycler views are being created and displayed but with empty data
can you tell me how to fix my code?
model:
public class Bus {
public Bus(String driverName, int busNo, String contactNo) {
this.driverName = driverName;
this.busNo = busNo;
this.contactNo = contactNo;
}
public Bus(){ }
public String getDriverName() {
return driverName;
}
public void setDriverName(String driverName) {
this.driverName = driverName;
}
public int getBusNo() {
return busNo;
}
public void setBusNo(int busNo) {
this.busNo = busNo;
}
public String getContactNo() {
return contactNo;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
String driverName, contactNo;
int busNo ;
}
activity code :
public class ViewBusDetailes extends AppCompatActivity {
LinearLayoutManager linearLayoutManager;
FirestoreRecyclerAdapter<Bus, BusViewHolder> adapter;
class BusViewHolder extends RecyclerView.ViewHolder {
private View view;
BusViewHolder(View itemView) {
super(itemView);
view = itemView;
}
void setDetiles(String contactNoText , String driverNameText, int busNoText) {
TextView driverName;
TextView busNo;
TextView contactNo;
driverName = itemView.findViewById(R.id.driverNameDriverListView);
contactNo = itemView.findViewById(R.id.driverContactDriverListView);
busNo = itemView.findViewById(R.id.busNumber);
driverName.setText(driverNameText);
busNo.setText(String.valueOf(busNoText));
contactNo.setText(contactNoText);
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_bus_details__layout);
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
Query query = rootRef.collection("Bus");
FirestoreRecyclerOptions<Bus> options = new FirestoreRecyclerOptions.Builder<Bus>()
.setQuery(query, Bus.class)
.build();
adapter = new FirestoreRecyclerAdapter<Bus, BusViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull BusViewHolder holder, int position, #NonNull Bus model) {
holder.setDetiles(model.getContactNo() , model.getDriverName() ,model.getBusNo());
}
#NonNull
#Override
public BusViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.bus_list_view, parent, false);
return new BusViewHolder(view);
}
};
recyclerView.setAdapter(adapter);
}
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
if (adapter != null) {
adapter.stopListening();
}
}
}
bus_list_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="360dp"
android:layout_height="72dp"
android:background="?android:attr/selectableItemBackground"
android:orientation="horizontal"
android:padding="16dp">
<TextView
android:id="#+id/busNumber"
android:layout_width="40dp"
android:layout_height="40dp"
android:textSize="20sp"
android:gravity="center"
android:fontFamily="sans-serif"
android:textStyle="normal"
android:textColor="#ffffff"
android:background="#drawable/circle"
/>
<LinearLayout
android:layout_width="287dp"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/driverNameDriverListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:textSize="17sp"
android:fontFamily="sans-serif"
android:textStyle="normal"
android:textColor="#de000000"
android:lineSpacingExtra="8sp"
android:text="Anwar"
/>
<TextView
android:id="#+id/driverContactDriverListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:layout_marginLeft="17dp"
android:fontFamily="sans-serif"
android:textStyle="normal"
android:textColor="#de000000"
android:lineSpacingExtra="6sp"
android:text="Dude can you solve this problem plea..."
/>
</LinearLayout>
</LinearLayout>
activity_view_bus_detiels.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
tools:context=".activity.ViewBusDetailes"
android:id="#+id/container">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
Do it like this
public class Bus {
private String driverName;
private int busNo;
private String contactNo;
public String getDriverName() {
return driverName;
}
public int getBusNo() {
return busNo;
}
public String getContactNo() {
return contactNo;
}
}
activity code :
public class ViewBusDetailes extends AppCompatActivity {
LinearLayoutManager linearLayoutManager;
FirestoreRecyclerAdapter adapter;
class BusViewHolder extends RecyclerView.ViewHolder {
TextView driverName;
TextView busNo;
TextView contactNo;
BusViewHolder(View itemView) {
super(itemView);
driverName = itemView.findViewById(R.id.driverNameDriverListView);
contactNo = itemView.findViewById(R.id.driverContactDriverListView);
busNo = itemView.findViewById(R.id.busNumber);
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_bus_details__layout);
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
Query query = rootRef.collection("Bus");
FirestoreRecyclerOptions<Bus> options = new FirestoreRecyclerOptions.Builder<Bus>()
.setQuery(query, Bus.class)
.build();
adapter = new FirestoreRecyclerAdapter<Bus, BusViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull BusViewHolder holder, int position, #NonNull Bus model) {
holder.driverName.setText(model.getDriverName());
holder.busNo.setText(String.valueOf(model.getBusNo()));
holder.contactNo.setText(model.getContactNo());
}
#NonNull
#Override
public BusViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(ViewBusDetailes.this).inflate(R.layout.bus_list_view, parent, false);
return new BusViewHolder(view);
}
};
recyclerView.setAdapter(adapter);
}
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
if (adapter != null) {
adapter.stopListening();
}
}
}
Also, add this dependency if you haven't.
implementation 'com.firebaseui:firebase-ui-firestore:4.3.2'
Also, edit your Firebase Firestore rules from Firestore settings in the firebase console.
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
Check if it works.

Firestore recycler adapter not fetching document names

I'm trying fetch all documents using FirestoreRecyclerAdapter here if there are 7 documents the RecyclerView items successfully populates with 7 items but here problem is the items which are having a text view are not getting populated with document names. Please take a look at my source code:
FriendsResponse Class:
#IgnoreExtraProperties
public class FriendsResponse {
FirebaseFirestore db;
public String getTable1() {
return Table1;
}
public void setTable1(String table1) {
Table1 = table1;
}
private String Table1;
public FriendsResponse() {
}
public FriendsResponse(String Table1) {
this.Table1 = Table1;
}
}
TableList Fragment where recyclerview is initialized:
public class TableListFragment extends Fragment{
private FirebaseFirestore db;
private FirestoreRecyclerAdapter adapter;
String documentnm;
RecyclerView recyclerView;
FloatingActionButton addt;
private StaggeredGridLayoutManager _sGridLayoutManager;
public static TableListFragment newInstance() {
TableListFragment fragment = new TableListFragment();
return fragment;
}
public TableListFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tablelist, container, false);
recyclerView = view.findViewById(R.id.rectab);
addt=view.findViewById(R.id.addtab);
init();
getFriendList();
addt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return view;
}
private void init(){
_sGridLayoutManager = new StaggeredGridLayoutManager(3,
StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(_sGridLayoutManager);
db = FirebaseFirestore.getInstance();
}
private void getFriendList(){
Query query = db.collection("Order");
FirestoreRecyclerOptions<FriendsResponse> response = new FirestoreRecyclerOptions.Builder<FriendsResponse>()
.setQuery(query, FriendsResponse.class)
.build();
adapter = new FirestoreRecyclerAdapter<FriendsResponse, FriendsHolder>(response) {
#Override
public void onBindViewHolder(FriendsHolder holder, int position, FriendsResponse model) {
holder.exname.setText(model.getTable1());
holder.itemView.setOnClickListener(v -> {
Snackbar.make(recyclerView, model.getTable1(), Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
});
}
#Override
public FriendsHolder onCreateViewHolder(ViewGroup group, int i) {
View view = LayoutInflater.from(group.getContext())
.inflate(R.layout.list_item, group, false);
return new FriendsHolder(view);
}
#Override
public void onError(FirebaseFirestoreException e) {
Log.e("error", e.getMessage());
}
};
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
}
public class FriendsHolder extends RecyclerView.ViewHolder {
TextView exname;
public FriendsHolder(View itemView) {
super(itemView);
exname= itemView.findViewById(R.id.topicname);
}
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
}
This is the code of list_item:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView android:id="#+id/cardvw"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="6dp"
card_view:cardElevation="3dp"
card_view:cardUseCompatPadding="true"
xmlns:android="http://schemas.android.com/apk/res/android" xmlns:card_view="http://schemas.android.com/apk/res-auto">
<LinearLayout android:orientation="vertical" android:padding="5dp" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/topiclogo"
android:layout_width="match_parent"
android:layout_gravity="center"
android:src="#drawable/table"
android:layout_height="wrap_content"
/>
<TextView android:textSize="15sp"
android:textStyle="bold"
android:textAlignment="center"
android:textColor="#ffffa200"
android:id="#+id/topicname"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v7.widget.CardView>
As I understand, you want to set the id of the document to that TextView. So because those names are actually documents ids, you should use the following lines of code inside onBindViewHolder() method:
String id = getSnapshots().getSnapshot(position).getId();
holder.exname.setText(id);
The POJO class that you are using is useful when getting the properties of the documents, not to get the document ids.

OnCreateViewHolder is not being called for the FirebaseRecyclerAdapter<>

I tried to debug my program and noticed that execution is not going inside FirebaseRecyclerAdapter recyclerAdapter=new FirebaseRecyclerAdapter(
options). I have tried all the possible solutions stackoverflow offered but nothing seems to solve my problem.I m attaching my MainActivity.java, activity_main.xml and if u need any other attachment then just tell me,
thank you
MainActivity.java
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private DatabaseReference myref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView=(RecyclerView)findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(false);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
myref= FirebaseDatabase.getInstance().getReference().child("/blog");
FirebaseRecyclerOptions<Blog> options =
new FirebaseRecyclerOptions.Builder<Blog>()
.setQuery(myref, Blog.class)
.build();
FirebaseRecyclerAdapter<Blog,BlogViewHolder> recyclerAdapter=new FirebaseRecyclerAdapter<Blog,BlogViewHolder>(
options) {
//this is not being executed
#Override
public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.individual_row, parent, false);
return new BlogViewHolder(view);
}
#Override
public void onBindViewHolder(BlogViewHolder holder, int position, Blog model) {
holder.setTitle(model.getTitle());
holder.setDescription(model.getDescription());
holder.setImage(model.getImage());
}
};
recyclerView.setAdapter(recyclerAdapter);
}
public static class BlogViewHolder extends RecyclerView.ViewHolder {
View mView;
TextView textView_title;
TextView textView_decription;
ImageView imageView;
public BlogViewHolder(View itemView) {
super(itemView);
mView=itemView;
textView_title = (TextView)itemView.findViewById(R.id.title);
textView_decription = (TextView) itemView.findViewById(R.id.description);
imageView=(ImageView)itemView.findViewById(R.id.image);
}
public void setTitle(String title)
{
textView_title.setText(title+"");
}
public void setDescription(String description)
{
textView_decription.setText(description);
}
public void setImage(String image)
{
Picasso.with(mView.getContext())
.load(image)
.into(imageView);
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
Sorry for being late, i hope you had my same error, what you are missing is this:
#Override
public void onStart() {
super.onStart();
recyclerAdapter.startListening();
}
#Override
public void onStop() {
super.onStop();
recyclerAdapter.stopListening();
}
i just lost 2 hours wondering what i was doing wrong and...well it was something like this.
Hope it helps.

Categories