I want to display "No upcoming Appointments" when my recyclerview is empty and display recyclerview when it's not empty. I have tried various codes to check whether my recyclerview is empty or not, but none worked.
Here is my code
public class appointments extends Fragment {
private RecyclerView recyclerView;
private DatabaseReference ref;
private ArrayList<BookedUserInfo> arrayList;
private FirebaseRecyclerOptions<BookedUserInfo> options;
private FirebaseAuth mAuth;
private String uid;
private FirebaseRecyclerAdapter<BookedUserInfo, FireBaseViewHolderUpcomingAppointment> adapter;
private String shopname;
private ProgressDialog progressDialog;
private TextView emptyview;
private int x=0;
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View RootView = inflater.inflate(R.layout.appointment_navigation,container,false);
//find view by ID
recyclerView = (RecyclerView) RootView.findViewById(R.id.recycleupcomingappointment);
emptyview = (TextView) RootView.findViewById(R.id.empty_view);
//Auth instance
mAuth = FirebaseAuth.getInstance();
FirebaseUser currentuser = mAuth.getCurrentUser();
uid = currentuser.getUid();
//initialize progress dialog
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading");
progressDialog.show();
//database refrence
ref = FirebaseDatabase.getInstance().getReference().child("USER").child(uid).child("UpcomingAppointment");
ref.keepSynced(true);
//recycler view
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(llm);
//array list
arrayList = new ArrayList<BookedUserInfo>();
options = new FirebaseRecyclerOptions.Builder<BookedUserInfo>().setQuery(ref,BookedUserInfo.class).build();
//adapter
adapter = new FirebaseRecyclerAdapter<BookedUserInfo, FireBaseViewHolderUpcomingAppointment>(options) {
#Override
protected void onBindViewHolder(#NonNull final FireBaseViewHolderUpcomingAppointment holder, int position, #NonNull final BookedUserInfo model) {
final String datedata = model.getDate();
final String timedata = model.getTime();
final int bookingiddata = model.getBookingid();
Date initDate = null;
try {
initDate = new SimpleDateFormat("dd-MM-yyyy").parse(datedata);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat formatter = new SimpleDateFormat("EEE, d MMM yyyy");
final String parsedDate = formatter.format(initDate);
holder.time.setText(timedata);
holder.date.setText(parsedDate);
holder.id.setText(String.valueOf(bookingiddata));
final String shopuid = model.getShopuid();
DatabaseReference myRef =FirebaseDatabase.getInstance().getReference().child("SHOP").child(shopuid);
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
shopname = dataSnapshot.child("shopname").getValue().toString();
holder.name.setText(shopname);
progressDialog.dismiss();
}
#Override
public void onCancelled(DatabaseError error) {
progressDialog.dismiss();
// Failed to read value
}
});
progressDialog.dismiss();
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), AppointmentBill.class);
intent.putExtra("bookingid",String.valueOf(bookingiddata));
intent.putExtra("timetext",timedata);
intent.putExtra("datetext",datedata);
intent.putExtra("uidtext",shopuid);
intent.putExtra("appointmentinfotext",model.getAppointmentinfo());
startActivity(intent);
}
});
}
#NonNull
#Override
public FireBaseViewHolderUpcomingAppointment onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new FireBaseViewHolderUpcomingAppointment(LayoutInflater.from(getActivity()).inflate(R.layout.cardview_appointment,parent,false));
}
};
recyclerView.setAdapter(adapter);
//check total items
if(adapter.getItemCount() == 0)
{
recyclerView.setVisibility(View.GONE);
emptyview.setVisibility(View.VISIBLE);
}
else
{
recyclerView.setVisibility(View.VISIBLE);
emptyview.setVisibility(View.GONE);
}
progressDialog.dismiss();
return RootView;
}
XML code
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/relativelayoutview"
android:layout_below="#id/upcomingappointments">
<TextView
android:id="#+id/empty_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="30dp"
android:visibility="gone"
android:background="#E7E7E7"
android:paddingBottom="30dp"
android:text="---------No Upcoming Appointments---------"
android:gravity="center">
</TextView>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycleupcomingappointment"
android:layout_width="match_parent"
android:background="#E7E7E7"
android:layout_height="match_parent">
</androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
I'm using google firebase(realtime database) to get appointment details. Please suggest me a solution for this problem.
I also tried this but failed so I instead used snapshot.getchilderncount In my firebase database reference and checked if childrencount =0 or not
Create a value event listener For your apointment database reference and in it say if(snapshot.getChildrenCount==0) { ///your logic }
Try to move this logic inside onDataChange callback method:
//check total items
if(adapter.getItemCount() == 0)
{
recyclerView.setVisibility(View.GONE);
emptyview.setVisibility(View.VISIBLE);
}
else
{
recyclerView.setVisibility(View.VISIBLE);
emptyview.setVisibility(View.GONE);
}
this is a sample recyclerView app
Adapter.java
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
List<?> list; //i don`t know your model or type date then i write (?)
public Adapter(List<?> list) {
this.list = list;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.your_layout,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
//you write your code when bind your view hoder
YourMode model = list.get(position);
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(#NonNull View itemView) {
super(itemView);
//for get your view or widget your use **itemView.findViewById()**
}
}
}
and this code for get Item count :
public class MyFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.your_fragment_layout, container,false);
Adapter adapter = Adapter(yourList);
if (adapter.getItemCount() == 0){
}else {
}
return view;
}
}
Related
I'm loading some data into a RecyclerView from Firebase Realtime Database. This RecyclerView is in a fragment and I want to open a new activity when an item is clicked. But when i add the onClickListener to an item from the adapter, my click doesn't even recognized by the app. I'm not sure what I'm doing wrong here because this method worked fine for a RecyclerView when it is inside of a normal activity.
This is a project for my university and I should submit it tomorrow. So I can really use some help.
This is the my data Adapter class,
public class Adapter_NoLimit extends RecyclerView.Adapter<Adapter_NoLimit.LViewHolder> {
Context context;
ArrayList<Helper> list_nl;
public Adapter_NoLimit(Context context, ArrayList<Helper> list_nl) {
this.context = context;
this.list_nl = list_nl;
}
#NonNull
#Override
public Adapter_NoLimit.LViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.itemlist, parent, false);
return new LViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull Adapter_NoLimit.LViewHolder holder, int position) {
//final Helper temp = list_nl.get(position);
String fname_txt = list_nl.get(position).getFname();
String catg_txt = list_nl.get(position).getSpin();
String prof_img = list_nl.get(position).getProfile_url();
holder.setUsers(fname_txt, catg_txt, prof_img);
holder.f_name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AppCompatActivity activity = (AppCompatActivity) v.getContext();
Intent i = new Intent(activity, UserProfile_VV.class);
i.putExtra("full name", fname_txt);
activity.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return list_nl.size();
}
public class LViewHolder extends RecyclerView.ViewHolder{
private TextView f_name, catG;
private ImageView profile_pic;
public LViewHolder(#NonNull View itemView) {
super(itemView);
f_name = itemView.findViewById(R.id.username_view);
catG = itemView.findViewById(R.id.category_view);
profile_pic = itemView.findViewById(R.id.userimage);
}
public void setUsers(String fname_txt, String catg_txt, String prof_img) {
f_name.setText(fname_txt);
catG.setText(catg_txt);
Picasso.get().load(prof_img).fit().into(profile_pic);
}
}
}
This is one of fragments,
public class Beauty_Frag extends Fragment {
RecyclerView recyclerView;
DatabaseReference reference, user_ref;
ArrayList<Helper> list;
Adapter adapter;
FirebaseAuth auth;
String uid;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_beauty, container, false);
recyclerView = v.findViewById(R.id.beauty_recycler_frag);
reference = FirebaseDatabase.getInstance().getReference();
user_ref = reference.child("users");
auth = FirebaseAuth.getInstance();
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
//searchField = findViewById(R.id.search_field);
list = new ArrayList<>();
adapter = new Adapter(getContext(), list);
recyclerView.setAdapter(adapter);
user_ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull /*#org.jetbrains.annotations.NotNull*/ DataSnapshot snapshot) {
for (DataSnapshot key : snapshot.getChildren()) {
if( key.child("spin").getValue().toString().equals("Beauty")) {
Helper helper = key.getValue(Helper.class);
list.add(helper);
adapter.notifyDataSetChanged();
}
}
}
#Override
public void onCancelled(#NonNull /*#org.jetbrains.annotations.NotNull*/ DatabaseError error) {
}
});
return v;
}
}
You are very welcome if you have any solution.
Use below code for onClicklistner:
holder.f_name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, UserProfile_VV.class);
i.putExtra("full name", fname_txt);
context.startActivity(i);
}
});
I have "E/RecyclerView: No adapter attached; skipping layout" error message.
I have recycleView inside fragment so I must have done something wrong on fragment1.java.
here is the code. I set adapter on the code as you can see, but I am getting this error. Any help would be appreciated. Thank you.
public class Fragment1 extends Fragment {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ArrayList<Bible> arrayList;
private FirebaseDatabase database;
private DatabaseReference databaseReference;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment1, container, false);
recyclerView = rootView.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
//GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
arrayList = new ArrayList<>();
database = FirebaseDatabase.getInstance();
databaseReference = database.getReference("Bible");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
arrayList.clear();
for(DataSnapshot snapshot: dataSnapshot.getChildren()){
Bible bible = snapshot.getValue(Bible.class);
arrayList.add(bible);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.e("fragment1", String.valueOf(databaseError.toException()));//에러문 출력
}
});
adapter = new BibleAdapter(arrayList, getContext());
recyclerView.setAdapter(adapter);
return rootView;
}
}
public class BibleAdapter extends RecyclerView.Adapter {
private ArrayList<Bible> arrayList;
private Context context;
private OnVerseItemClickListener listener;
public BibleAdapter(ArrayList<Bible> arrayList, Context context) {
this.arrayList = arrayList;
this.context = context;
}
public void setOnItemClickListener(OnVerseItemClickListener listener){
this.listener = listener;
}
#NonNull
#Override
public BibleAdapter.BibleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.verse_item, parent, false);
BibleViewHolder holder = new BibleViewHolder(view, listener);
return holder;
}
#Override
public void onBindViewHolder(#NonNull BibleAdapter.BibleViewHolder holder, int position) {
Glide.with(holder.imageView)
.load(arrayList.get(position).getImage())
.into(holder.imageView);
holder.bibleType.setText(arrayList.get(position).getBibleType());
holder.keysentance.setText(arrayList.get(position).getKeysentance());
holder.verse.setText(arrayList.get(position).getVerse());
}
#Override
public int getItemCount() {
return (arrayList!=null? arrayList.size():0);
}
public class BibleViewHolder extends RecyclerView.ViewHolder{
ImageView imageView;
TextView bibleType;
TextView verse;
TextView keysentance;
public BibleViewHolder(#NonNull View itemView, final OnVerseItemClickListener listener) {
super(itemView);
this.imageView = itemView.findViewById(R.id.imageView);
this.bibleType = itemView.findViewById(R.id.bibleType);
this.keysentance = itemView.findViewById(R.id.keysentance);
this.verse = itemView.findViewById(R.id.verse);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
if(listener != null){
listener.onItemClick(BibleViewHolder.this, v, position);
}
}
});
}
}
}
in your code you have create adapter with empty arrayList, but never after that you update the list.
in adapter create swapData() method and call it when you have to refresh data or have refreshed data, in your case you will get it in onDataChange().
And also define adapter before adding listener:
adapter = new BibleAdapter(arrayList, getContext());
recyclerView.setAdapter(adapter);
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
arrayList.clear();
for(DataSnapshot snapshot: dataSnapshot.getChildren()){
Bible bible = snapshot.getValue(Bible.class);
arrayList.add(bible);
}
adapter.swapData(arrayList);
//adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.e("fragment1", String.valueOf(databaseError.toException()));//에러문 출력
}
});
in adapter class create method as:
public void swapData(ArrayList<Bible> filtersList) {
if (filtersList != null) {
this.arrayList.clear();
this.arrayList.addAll(filtersList);
notifyDataSetChanged();
}
}
I know there is other questions like this with answers but they don't help me...
So I have a Fragment, in this one I use Volley to get a JSON from a Web API. What I want to do is to "refresh" my recycler view with the data I get in my response.
I have tried to add a method in my adapter. But nothing append when I try to change my adapter in my Volley.onresponse() method.
There is my Fragment :
public class TicketsIncidentsFragment extends Fragment implements Response.ErrorListener, Response.Listener<String> {
RequestQueue queue;
StringRequest stringRequest;
ListView listView;
private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
String url;
private TicketsIncidentsViewModel ticketsIncidentsViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
ticketsIncidentsViewModel =
ViewModelProviders.of(this).get(TicketsIncidentsViewModel.class);
View root = inflater.inflate(R.layout.fragment_ticketsincidents, container, false);
return root;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
RecyclerView recyclerView = (RecyclerView)getView().findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
layoutManager= new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
MyAdapterTI myAdapterTI=new MyAdapterTI();
recyclerView.setAdapter(myAdapterTI);
queue = Volley.newRequestQueue(getActivity().getApplicationContext());
url = "http://myip/select/ticketsI";
stringRequest = new StringRequest(GET, url, TicketsIncidentsFragment.this, TicketsIncidentsFragment.this);
queue.add(stringRequest);
}
#Override
public void onErrorResponse(VolleyError error) {
}
#Override
public void onResponse(String response) {
RecyclerView recyclerView = (RecyclerView)getView().findViewById(R.id.recyclerview);
Gson gsonTicketsIncidents = new Gson();
ResponseJson responseJson = new ResponseJson();
responseJson = (ResponseJson) gsonTicketsIncidents.fromJson(response, ResponseJson.class);
List<Object> listTicketsIncidents = responseJson.getResponse();
try {
JSONArray tis = new JSONArray(listTicketsIncidents.toArray());
ArrayList<String> date = new ArrayList<String>();
ArrayList<String> nomUser = new ArrayList<String>();
for (int i = 0 ; i< tis.length(); i++) {
JSONObject ticketIncident = tis.getJSONObject(i);
nomUser.add(ticketIncident.get("NOMUSER").toString());
date.add(ticketIncident.get("DateSAISIE").toString());
}
MyAdapterTI myAdapterTI=new MyAdapterTI();
myAdapterTI.getList(nomUser, date);
recyclerView.setAdapter(myAdapterTI);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
There is my adapter :
public class MyAdapterTI extends RecyclerView.Adapter<MyAdapterTI.MyViewHolder> {
private List<Pair<String, String>> TI;
public void getList(ArrayList<String> nomUser, ArrayList<String> date){
for(int i =0; i<nomUser.size();i++){
TI = Arrays.asList( Pair.create(nomUser.get(i), date.get(i)));
}
}
#NonNull
#Override
public MyAdapterTI.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.list_cell_ti, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyAdapterTI.MyViewHolder holder, int position) {
Pair<String, String> pair = TI.get(position);
holder.display(pair);
}
#Override
public int getItemCount() {
return 0;
}
public class MyViewHolder extends RecyclerView.ViewHolder{
private TextView nomUser;
private TextView date;
private Pair<String, String> currentPair;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
nomUser=(TextView)itemView.findViewById(R.id.nomuser);
date=(TextView)itemView.findViewById(R.id.date);
itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
}
});
}
public void display(Pair<String, String> pair) {
currentPair=pair;
nomUser.setText(pair.first);
date.setText(pair.second);
}
}
}
And there is the layout :
<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_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/listview_TI"
android:layout_width="97dp"
android:layout_height="34dp"
android:layout_marginTop="24dp"
android:visibility="invisible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.917"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.976" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview"
android:layout_width="409dp"
android:layout_height="680dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.039" />
</androidx.constraintlayout.widget.ConstraintLayout>
Thank's for you're help
UPDATE :
Now my MyAdapter.getList() looks like this :
public void getList(ArrayList<String> nomUser, ArrayList<String> date){
for(int i =1; i<nomUser.size();i++){
TI.add(Pair.create(nomUser.get(i), date.get(i)));
}
notifyDataSetChanged();
}
But nothing change yet.
Last UPDATE :
The problem has been solved.
It's a ridiculous mistake I've made in my Adapter.
I used to return 0 but the solution is this :
#Override
public int getItemCount() {
return TI.size();
}
just change
#Override
public int getItemCount() {
return 0;
}
to
#Override
public int getItemCount() {
if(TI == null)
return 0;
else
return TI.size;
}
private List<Pair<String, String>> TI = new ArrayList();
public void getList(ArrayList<String> nomUser, ArrayList<String> date){
for(int i =0; i<nomUser.size();i++){
TI.add(Pair.create(nomUser.get(i), date.get(i)));
}
notifyDataSetChanged();
}
layoutManager= new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
MyAdapterTI myAdapterTI=new MyAdapterTI(getActivity().getApplicationContext(),ThisIsYourList);
recyclerView.setAdapter(myAdapterTI);
Don't do this in response
MyAdapterTI myAdapterTI=new MyAdapterTI();
recyclerView.setAdapter(myAdapterTI);
myAdapterTI make this global variable
Only update your list and then
myAdapterTI.notifyDataSetChanged();
Or in your adapter, you can do
this.notifyDataSetChanged(); ////in getList
Here is my fragment
public class TransactionsFragment extends Fragment {
private FirebaseAuth mAuth;
private DatabaseReference mDBref;
FirebaseUser Fuser;
private String UID;
private RecyclerView recyclerView;
private RecyclerView.Adapter trpAdapter;
private List<TransGetterSetter> DataList;
String trans_id;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_transactions, container, false);
DataList = new ArrayList<>();
recyclerView = (RecyclerView) v.findViewById(R.id.RVList);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
TransactionRVAdapter trvAdapter = new TransactionRVAdapter(DataList, getContext());
recyclerView.setAdapter(trvAdapter);
mAuth = FirebaseAuth.getInstance();
mDBref = FirebaseDatabase.getInstance().getReference();
Fuser = mAuth.getInstance().getCurrentUser();
UID = Fuser.getUid();
mDBref.child("transactions").child(UID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot chidSnap : dataSnapshot.getChildren()) {
trans_id = chidSnap.getKey();
DataList.add(new TransGetterSetter("" + trans_id));
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
trvAdapter.notifyDataSetChanged();
return v;
}
}
If i toast "trans_id" string im getting expected result.
Here is My Adapter class
public class TransactionRVAdapter extends RecyclerView.Adapter<TransactionRVAdapter.rvViewHolder> {
Context mContext;
List<TransGetterSetter> DataList = new ArrayList<>();
public class rvViewHolder extends RecyclerView.ViewHolder{
private TextView TransId;
public rvViewHolder(#NonNull View itemView) {
super(itemView);
TransId = (TextView) itemView.findViewById(R.id.TransIdTxt);
}
}
public TransactionRVAdapter( List<TransGetterSetter> DataList,Context mContext){
this.DataList = DataList;
this.mContext = mContext;
}
#NonNull
#Override
public rvViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.fragment_transactions_item, viewGroup, false);
return new rvViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull rvViewHolder rvViewHolder, int i) {
rvViewHolder.TransId.setText(DataList.get(i).getTrans_id());
}
#Override
public int getItemCount() {
return DataList.size();
}
}
Here is my GetterSetter class
public class TransGetterSetter {
private String trans_id;
public TransGetterSetter() {
}
public TransGetterSetter(String trans_id) {
this.trans_id = trans_id;
}
public String getTrans_id() {
return trans_id;
}
public void setTrans_id(String trans_id) {
this.trans_id = trans_id;
}
}
Im able to get Data from firebase, but when i try to add it to recycler view it dosen't show any data. Recycler view is showing empty. I checked my code many time but haven't found solution.
You should call :
trvAdapter.notifyDataSetChanged();
After the for loop inside the (onDataChange) event listener.
Try to called ..
DataList.add(new TransGetterSetter("" + trans_id));
after this line called ..
trvAdapter.notifyDataSetChanged();
I'm trying to add a load more.
I tried to apply what I'd search and it doesn't work.
here's my code.
LatestGradeFragment
public class LatestGradeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener{
List<ListGradeData> sectionList;
RecyclerView recyclerView;
SwipeRefreshLayout mSwipeRefreshLayout;
public static LatestGradeFragment newInstance() {
return new LatestGradeFragment();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_latest_grade, container, false);
//RecyclerView+CardView for section
recyclerView = (RecyclerView) rootView.findViewById(R.id.display_recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
sectionList = new ArrayList<>();
mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipeRefreshSection);
mSwipeRefreshLayout.setOnRefreshListener(this);
mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary,
android.R.color.holo_green_dark,
android.R.color.holo_orange_dark,
android.R.color.holo_blue_dark);
mSwipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
mSwipeRefreshLayout.setRefreshing(true);
// Fetching data from server
loadSection();
}
});
return rootView;
}
#Override
public void onRefresh() {
loadSection();
}
private void loadSection() {
mSwipeRefreshLayout.setRefreshing(true);
StringRequest stringRequest = new StringRequest(Request.Method.GET, Constants.USER_GRADE,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
if(sectionList!=null) {
sectionList.clear();
}
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject sections = array.getJSONObject(i);
//adding the product to product list
sectionList.add(new ListGradeData(
sections.getInt("id"),
sections.getString("section"),
sections.getString("level"),
sections.getString("schoolyear")
));
}
//creating adapter object and setting it to recyclerview
LatestGradeAdapter adapter = new LatestGradeAdapter(getActivity(), sectionList);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
// Stopping swipe refresh
mSwipeRefreshLayout.setRefreshing(false);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Stopping swipe refresh
mSwipeRefreshLayout.setRefreshing(false);
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(getActivity().getApplicationContext()).add(stringRequest);
}
#Override
public String toString() {
return "LatestGradeFragment";
}
}`
and here's my LatestGradeAdapter:
public class LatestGradeAdapter extends RecyclerView.Adapter<LatestGradeAdapter.RecyclerViewHolder> {
private Context mCtx;
private List<ListGradeData> sectionList;
`public LatestGradeAdapter(Context mCtx, List<ListGradeData> sectionList) {
this.mCtx = mCtx;
this.sectionList = sectionList;
}
#NonNull
#Override
public RecyclerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.section_data_list, parent, false);
return new LatestGradeAdapter.RecyclerViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewHolder holder, int position) {
final ListGradeData sections = sectionList.get(position);
//BIND DATA
holder.textViewSection.setText(sections.getSection());
holder.textViewLevel.setText(sections.getLevel());
holder.textViewSchoolYear.setText(sections.getSchoolyear());
}
#Override
public int getItemCount() {
return sectionList.size();
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
//Variables for list
TextView textViewSection, textViewLevel, textViewSchoolYear;
//Variables for head section
TextView textHeaderSection, textHeaderLevel, textHeaderSchoolYear;
public RecyclerViewHolder(final View itemView) {
super(itemView);
textViewSection = (TextView) itemView.findViewById(R.id.textSection);
textViewLevel = (TextView) itemView.findViewById(R.id.textLevel);
textViewSchoolYear = (TextView) itemView.findViewById(R.id.textYear);
}
}
}`
Add this code in your LatestGradeFragment.class
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
int lastVisiblePosition = layoutManager.findLastVisibleItemPosition();
if (lastVisiblePosition == recyclerView.getChildCount()) {
progrssBar.setVisibility(View.VISIBLE);
loadMore(); //This methos is used for load next set of items.
}
}
});
public void loadMore(){
//load next set of items to adapter
adapter.notifyDataSetChanged();
progrssBar.setVisibility(View.GONE);
}
Create your fragment_latest_grade like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/progressBar" />
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true"
android:visibility="gone" />
</RelativeLayout>