Move object from a RecyclerView to another RecyclerView - java

I'm currently making a booking app for some football fields. I have two recycler views: active bookings and cancelled bookings. I also have a custom recycler view adapter. Both of the recycler views use the same adapter.
What I want to do: if I click on a button inside my active bookings recycler view, I want to remove the booking from the active bookings and put it into my cancelled bookings. I'm gonna leave my custom adapter with the mention that I use Firebase in order to get my booking status (active or cancelled).
public class RecyclerViewAdapterRezervare extends RecyclerView.Adapter<RecyclerViewAdapterRezervare.RecycleViewHolder> {
private List<Rezervare> rezervari;
private Context context;
private LayoutInflater inflater;
private String numeUtilizator;
private String status;
private Rezervare rezervare = new Rezervare();
private DatabaseReference reff;
public RecyclerViewAdapterRezervare(List<Rezervare> rezervari, Context context, String numeUtilizator) {
this.rezervari = rezervari;
this.context = context;
this.numeUtilizator = numeUtilizator;
this.inflater = LayoutInflater.from(context);
}
#NonNull
#Override
public RecycleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.rezervari_layout, parent, false);
return new RecycleViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecycleViewHolder holder, int position) {
rezervare = rezervari.get(position);
reff = FirebaseDatabase.getInstance().getReference();
List<String> listaOre = rezervare.getOre();
Map<String, Object> mapOre = new HashMap<>();
for(String ora : listaOre){
mapOre.put(ora, false);
}
// this will return the status ("activa" is the booking is active, or "anulata" is it's cancelled)
getStatus(rezervare, new StatusCallback() {
#Override
public void onCallback(String value) {
status = value;
holder.btn_anuleaza.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v("status", status);
new AlertDialog.Builder(view.getContext()).setTitle("Anulare rezervare").setMessage("Sunteti sigur ca doriti anularea rezervarii?")
.setPositiveButton(R.string.da, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// if the cancel button is clicked, i update my database so the status of the booking will be "anulata" - cancelled reff.child("Users").child(numeUtilizator).child("rezervari").child(rezervare.getData()).child(rezervare.getNumeTeren()).child("status").setValue("anulata");
reff.child("Rezervari").child(rezervare.getData()).child("Fotbal").child(rezervare.getNumeTeren()).updateChildren(mapOre);
rezervare.setEsteAnulata(false);
Toast.makeText(view.getContext(), "Anulare cu succes!", Toast.LENGTH_LONG).show();
}
}).setNegativeButton(R.string.nu, null).show();
}
});
}
});
}
#Override
public int getItemCount() {
return rezervari.size();
}
// i have updated my code with the delete and insert a booking
public void stergeRezervare(int position){
rezervari.remove(position);
notifyDataSetChanged();
}
public void adaugaRezervare(Rezervare rezervare){
rezervari.add(rezervare);
notifyDataSetChanged();
}
This is the function that gets me the bookings from firebase
i have 3 separate lists for active bookings, cancelled and past bookings.
public interface RezervariListCallback {
void onCallback(List<Rezervare> rezervariActuale, List<Rezervare> rezervariTrecute, List<Rezervare> rezervariAnulate);
}
public void getRezervari(String nume, RezervariListCallback myCallback){
reff.child("Users").child(nume).child("rezervari").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot data : snapshot.getChildren()){
String dataRezervare = data.getKey();
dateRezervari.add(dataRezervare);
reff.child("Users").child(nume).child("rezervari").child(dataRezervare).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot data : snapshot.getChildren()){
String numeTeren = data.getKey();
reff.child("Users").child(nume).child("rezervari").child(dataRezervare).child(numeTeren).child("ore").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
List<String> ore = new ArrayList<>();
for(DataSnapshot data : snapshot.getChildren()){
String ora = data.getKey();
ore.add(ora);
}
getAdresa(nume, dataRezervare, numeTeren, new AdresaCallback() {
#Override
public void onCallbackAdresa(String value) {
Rezervare rezervare = new Rezervare(numeTeren, ore, dataRezervare, value);
String dataAzi = getDataAzi();
reff.child("Users").child(nume).child("rezervari").child(dataRezervare).child(numeTeren).child("status").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String status = (String) snapshot.getValue();
if(comparaData(dataAzi, rezervare.getData())){
if(status.equals("activa")){
rezervariActive.add(rezervare);
} else {
rezervariAnulate.add(rezervare);
}
} else {
rezervariTrecute.add(rezervare);
}
myCallback.onCallback(rezervariActive, rezervariTrecute, rezervariAnulate);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
and this is where i set the adapters
public void updateRezervari(View view, RecyclerView activeBookingsRecycler, RecyclerView pastBookingsRecycler, RecyclerView cancelledBookingsRecycler){
AsyncTask.execute(new Runnable() {
#Override
public void run() {
getRezervari(numeUtilizator, new RezervariListCallback() {
#Override
public void onCallback(List<Rezervare> rezervariActuale, List<Rezervare> rezervariTrecute, List<Rezervare> rezervariAnulate) {
if(rezervariActuale.size()>0){
tvFaraRezervariActive.setEnabled(false);
tvFaraRezervariAnulate.setEnabled(false);
tvFaraRezervariTrecute.setEnabled(false);
}
Log.v("rezAc", rezervariActuale.toString());
Log.v("rezTr", rezervariTrecute.toString());
RecyclerViewAdapterRezervare adapter = new RecyclerViewAdapterRezervare(rezervariActuale, view.getContext(), numeUtilizator);
activeBookingsRecycler.setAdapter(adapter);
adapter = new RecyclerViewAdapterRezervare(rezervariTrecute, view.getContext(), numeUtilizator);
pastBookingsRecycler.setAdapter(adapter);
adapter = new RecyclerViewAdapterRezervare(rezervariAnulate, view.getContext(), numeUtilizator);
cancelledBookingsRecycler.setAdapter(adapter);
}
});
}
});
}
Can you give me a few tips on how to move from one recycler view to another? Thank you!

Since you are using Firebase to fetch status of a booking, you can update the status to cancelled in your firebase database and then you will get a callback from your firebase listener where you can update your arraylists and call notifyDataSetChanged().

Related

Android Firebase query return Null

I'm working on a project where there's an activity which contains 3 spinners( Nested). I need the 2nd spinner to have the data based on the selected item of the 1st spinner and the data is retrieved from Firebase
The 1st spinner is going to have all "Gouv" values , the 2nd one is going to have the "Deleg" values where "Gouv" value is equal to the selected item "Gouv" of the 1st spinner .
Here is the code that i tried and i keep get in the log Null .
public class RechCode extends AppCompatActivity {
DatabaseReference spinnerRef;
Query spinnerRefG;
Spinner spinnerG;
Spinner spinnerD;
Spinner spinnerL;
ArrayAdapter<String> adapterG;
ArrayAdapter<String> adapterL;
ArrayAdapter<String> adapterD;
ArrayList<String> spinnerDList;
ArrayList<String> spinnerGList;
ArrayList<String> spinnerLOList;
Query spinnerRefD;
private String ChoixG;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rech_code);
spinnerG = findViewById(R.id.SpinnerGouv);
spinnerD = findViewById(R.id.SpinnerDeleg);
spinnerL = findViewById(R.id.SpinnerLoc);
spinnerRef = FirebaseDatabase.getInstance().getReference().child("CodePostale");
//Query queryD = spinnerG.("state", "CA");
spinnerGList = new ArrayList<>();
spinnerDList = new ArrayList<>();
spinnerLOList = new ArrayList<>();
adapterD= new ArrayAdapter<String>( RechCode.this, android.R. layout. simple_spinner_dropdown_item,spinnerDList);
adapterL= new ArrayAdapter<String>( RechCode.this, android.R. layout. simple_spinner_dropdown_item,spinnerLOList);
adapterG= new ArrayAdapter<String>( RechCode.this, android.R. layout. simple_spinner_dropdown_item,spinnerGList);
spinnerG.setAdapter(adapterG);
spinnerD.setAdapter(adapterD);
spinnerL.setAdapter(adapterL);
ShowdataGouv();
spinnerRefG= FirebaseDatabase.getInstance().getReference("CodePostale").child("Deleg").orderByChild("Gouv").equalTo(ChoixG);
ShowdataDeleg();
spinnerG.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
ChoixG = spinnerGList.get(i);
Toast.makeText(getApplicationContext(), "Gouvernorat:" + ChoixG, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {}
});
Button retour = (Button) findViewById(R.id.return_btn);
retour.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RetourMenu();
}
});
}
private void ShowdataLoc(String text) {
spinnerRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot1) {
for (DataSnapshot item:snapshot1.getChildren()){
spinnerLOList.add(item.child("Loc").getValue().toString());
}
adapterD.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void ShowdataDeleg() {
spinnerRefG.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot2) {
for (DataSnapshot item:snapshot2.getChildren()){
spinnerDList.add(item.child("Deleg").getValue().toString());
}
Log.d("Value","BBBBBBBB"+ snapshot2);
adapterD.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void ShowdataGouv() {
spinnerRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot3) {
for (DataSnapshot item:snapshot3.getChildren()){
spinnerGList.add(item.child("Gouv").getValue().toString());
Log.d("Value","AAAAAAAAA"+ snapshot3);
}
adapterG.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void RetourMenu() {
Intent intent = new Intent(getApplicationContext(), Menus.class);
startActivity(intent);
}
}
The problem is in the way you construct the query here:
spinnerRefG= FirebaseDatabase.getInstance()
.getReference("CodePostale")
.child("Deleg")
.orderByChild("Gouv")
.equalTo(ChoixG);
You're asking to load child nodes of /CodePostale/Deleg that have a Gouv property with a value of ChoixG. But if we check the screenshot of the data, there is no /CodePostale/Deleg, so no data is returned.
What you want instead is to check the child nodes of /CodePostale and return the ones where their Deleg/Gouv property has a value of ChoixG, which you can do with:
spinnerRefG= FirebaseDatabase.getInstance()
.getReference("CodePostale")
.orderByChild("Deleg/Gouv")
.equalTo(ChoixG);

How do I sort recylerView items of recent conversation by time?

I'm basically building a chatting app, the home page shows RecyclerView items of users who are friends. My HomeActivity passes users of the User class to the adapter. The adapter takes each user info and current user info to look up the "chats" firebase database for the last message and last message time to show on the homepage items.
Homepage Items
As my User class doesn't have any field "last message time" I cannot compare one user to another for their last message time.
Now how do I compare the recycler view items to bring the latest message to the top?
User.Java
public class User {
private String userId, name, username, email, profileImage, token;
}
Message.Java
public class Message {
private String messageId, message, senderId, imageUrl;
private long timestamp;
private int feeling = -1;
}
Firebase database structure
chats -
CurrentUserID+ReceiverID
- lastMsg
- lastMsgTime
- messages
messageId
- message
- timestamp
HomeActivity.java
ArrayList<User> users; //declared above onCreate method
users = new ArrayList<>(); //onCreate method
homeAdapter = new HomeAdapter(this, users);
binding.homeRecyclerView.setAdapter(homeAdapter);
database.getReference().child("users").addValueEventListener(new ValueEventListener() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
users.clear();
for (DataSnapshot snapshot1 : snapshot.getChildren()){
User user = snapshot1.getValue(User.class);
if(!user.getUserId().equals(mAuth.getUid())){
database.getReference().child("users")
.child(mAuth.getUid())
.child("friendList")
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot snapshot2 : snapshot.getChildren()){
String check = String.valueOf(snapshot2.getValue());
if(check.equals(user.getUserId())){
Log.d("YESCheck", user.getUsername());
users.add(user);
}
}
Collections.sort(users, new Comparator<User>() {
#Override
public int compare(User user, User t1) {
return user.getName().compareToIgnoreCase(t1.getName());
}
});
homeAdapter.notifyDataSetChanged();
progressDialog.dismiss();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
HomeAdapter.java
public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.HomeViewHolder> {
FirebaseAuth mAuth;
FirebaseDatabase database;
Context context;
ArrayList<User> users;
String senderName;
public HomeAdapter(Context context, ArrayList<User> users) {
this.context = context;
this.users = users;
}
#NonNull
#Override
public HomeViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.activity_home_item, parent, false);
return new HomeViewHolder(view);
}
public void onBindViewHolder(#NonNull HomeViewHolder holder, int position) {
//HomeViewHolder viewHolder = (HomeViewHolder) holder;
User user = users.get(position);
mAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
String senderId = mAuth.getUid();
String senderRoom = senderId + user.getUserId();
holder.binding.friendName.setText(user.getName());
Picasso.get().load(user.getProfileImage()).into(holder.binding.friendProfilePic);
holder.binding.friend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, ChattingActivity.class);
intent.putExtra("userName", user.getName());
intent.putExtra("profilePic", user.getProfileImage());
intent.putExtra("userId", user.getUserId());
intent.putExtra("token", user.getToken());
//intent.putExtra("senderName", senderName);
context.startActivity(intent);
}
});
database.getReference().child("chats")
.child(senderRoom).addValueEventListener(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
String lastMsg = snapshot.child("lastMsg").getValue(String.class);
long time = snapshot.child("lastMsgTime").getValue(Long.class);
#SuppressLint("SimpleDateFormat")
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm a");
holder.binding.friendLastMsg.setText(lastMsg);
holder.binding.friendLastMsgTime.setText(dateFormat.format(new Date(time)));
}
else {
holder.binding.friendLastMsg.setText("Tap to chat");
holder.binding.friendLastMsgTime.setText("");
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public int getItemCount() {
return users.size();
}
#SuppressWarnings("InnerClassMayBeStatic")
protected class HomeViewHolder extends RecyclerView.ViewHolder {
ActivityHomeItemBinding binding;
public HomeViewHolder(#NonNull View view) {
super(view);
binding = ActivityHomeItemBinding.bind(view);
}
}
}

Firebase database set objects in favorite list

I have a problem clearing list in fragments. I need to clear the list when happening update in fragment. I already put it in different places but it does not help me.
When an update happens in fragment it shows the same list but that list also add elements from the previous list. If I put list.clear(); in the moment when it rakes arguments from firebase it did not give me needed effect, when I put it in onCreate() method then app gives me error.
public class Favourite extends Fragment {
private RecyclerView recyclerView;
private ArrayList<TourReader1> artistList;
private ToursAdapter1 adapter1;
private DatabaseReference reference,reference2;
String uid;
public Favourite() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
//Get current user id
uid = user.getUid();
//Connect to specific point in database Tours
reference = FirebaseDatabase.getInstance().getReference("Tours");
//Create add to method valuelistener or reference which is specific point in database
reference2 = FirebaseDatabase.getInstance().getReference("user").child(uid);
reference.addValueEventListener(valueEventListener);
reference.keepSynced(true);
}
ValueEventListener valueEventListener = (new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot1) {
//get all information from specific point of database
for (DataSnapshot datasnapshot : snapshot1.getChildren()) {
//get current name of starting point from where we recive information from database
String firstname = datasnapshot.getKey();
//valuelistener for another point from database
reference2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dSnapshot2:snapshot.getChildren()){
String seconame = dSnapshot2.getKey();
Boolean control = dSnapshot2.child("like").getValue(Boolean.class);
if(control != null&&firstname.equals(seconame) &&control.equals(true)) {
TourReader1 artist = datasnapshot.getValue(TourReader1.class);
artistList.add(artist);
}
}
adapter1.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
artistList = new ArrayList<>();
View rootview = inflater.inflate(R.layout.favourite, container, false);
recyclerView = rootview.findViewById(R.id.list);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
adapter1 = new ToursAdapter1(getContext(), artistList);
recyclerView.setAdapter(adapter1);
GridLayoutManager mGridLayoutManager = new GridLayoutManager(getContext(), 2);
recyclerView.setLayoutManager(mGridLayoutManager);
return rootview;
}
}
You should clear the artistList using artistList.clear() before your for loop in onDataChangeas this list is having the data from the last callback triggered.
Ok, I found the answer myself, I clear my list in the adapter by tourlist.clear() and remove userpoints.keepSynced(true); when like icon is false.
holder.sparkButton.setEventListener(new SparkEventListener() {
#Override
public void onEvent(ImageView button, boolean buttonState) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String uid = user.getUid();
DatabaseReference userpoints = FirebaseDatabase.getInstance().getReference("user").child(uid);
ToursLike registerDatabase = new ToursLike(true);
if(buttonState){
userpoints.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(tour.Name)) {
userpoints.child(tour.Name).setValue(registerDatabase);
userpoints.keepSynced(true);
tourList.clear();
}
else{
userpoints.child(tour.Name).child("like").setValue(true);
userpoints.keepSynced(true);
tourList.clear();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
else{
userpoints.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userpoints.child(tour.Name).child("like").setValue(false);
tourList.clear();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onEventAnimationEnd(ImageView button, boolean buttonState) {
}
#Override
public void onEventAnimationStart(ImageView button, boolean buttonState) {
}
});
}

Recyclerview's Onscroll is not working while fetching data from firebase

I want to add onScroll Listener, but recyclerview's addonScrollListner() method is not doing anything, I want to fetch next ten items on every recyclerview's scroll.
At first time the data is fetching fine, but when i am scrolling recyclerview then nothing is happening, i am not able to find out why is this happening.
It is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = findViewById(R.id.adView_con);
progressBar = findViewById(R.id.contentprogressbar);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
recyclerView = findViewById(R.id.listview);
mSwipeRefreshLayout = findViewById(R.id.swipeContainer);
textView = findViewById(R.id.emptylist);
backbtncontent = findViewById(R.id.backbtncntent);
backbtncontent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ContentActivity.this, HomeActivity.class);
startActivity(i);
}
});
classname = getIntent().getStringExtra("classname");
if (classname.equals("A")) {
content = getIntent().getStringExtra("jokecontent");
} else if (classname.equals("B")) {
content = getIntent().getStringExtra("shayaricontent");
}
getLastKeyFromFirebase();
final LinearLayoutManager layoutManager= new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), layoutManager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);
arrayAdapter = new NewAdapterContent(contentname,this);
recyclerView.setAdapter(arrayAdapter);
getUsers();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
total_item = layoutManager.getItemCount();
last_visible_item = layoutManager.findLastCompletelyVisibleItemPosition();
if(!isLoading && total_item<=((last_visible_item+ITEM_LOAD_COUNT))){
getUsers();
isLoading = true;
}
}
});
}
private void getUsers()
{
if (!isMaxData) {
Query query;
if (classname.equals("A")) {
if (TextUtils.isEmpty(last_nodes)) //wait content to aa n raehre
query = FirebaseDatabase.getInstance().getReference("ContentJokes")
.orderByChild("subcategory")
.equalTo(content)
.limitToFirst(ITEM_LOAD_COUNT);
else
query = FirebaseDatabase.getInstance().getReference("ContentJokes")
.orderByChild("subcategory")
//.equalTo(content)
.startAt(last_nodes)
.limitToFirst(ITEM_LOAD_COUNT);
//1 sec wait cll ari kisi ki
query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if (!dataSnapshot.exists()) {
//hello ?
isLoading = false;
isMaxData = true;
// progressBar.setVisibility(View.GONE);
Toast.makeText(ContentActivity.this, "There is no jokes present under this category", Toast.LENGTH_SHORT).show();
} else {
String contentdisplay = dataSnapshot.child("content").getValue(String.class);
String key = dataSnapshot.child("content").getKey();
ContentModel contentModel = new ContentModel(contentdisplay, key);
contentname.add(0, contentModel);
arrayAdapter.notifyDataSetChanged();
progressBar.setVisibility(View.GONE);
arrayAdapter.notifyItemInserted(0);
last_nodes = contentname.get(contentname.size() - 1).getId();
if (!last_nodes.equals(last_key)) {
} else
last_nodes = last_key;
isLoading = false;
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
} else if(classname.equals("B")){
if (TextUtils.isEmpty(last_nodes)) //wait content to aa n raehre
query = FirebaseDatabase.getInstance().getReference("ContentShayari")
.orderByChild("subcategory")
.equalTo(content)
.limitToFirst(ITEM_LOAD_COUNT);
else
query = FirebaseDatabase.getInstance().getReference("ContentShayari")
.orderByChild("subcategory")
.equalTo(content)
.startAt(last_nodes)
.limitToFirst(ITEM_LOAD_COUNT);
query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if (!dataSnapshot.exists()) {
isLoading = false;
isMaxData = true;
// progressBar.setVisibility(View.GONE);
Toast.makeText(ContentActivity.this, "There is no jokes present under this category", Toast.LENGTH_SHORT).show();
} else {
String contentdisplay = dataSnapshot.child("content").getValue(String.class);
String key = dataSnapshot.child("content").getKey();
ContentModel contentModel = new ContentModel(contentdisplay, key);
contentname.add(0, contentModel);
arrayAdapter.notifyDataSetChanged();
// progressBar.setVisibility(View.GONE);
arrayAdapter.notifyItemInserted(0);
last_nodes = contentname.get(contentname.size() - 1).getId();
if (!last_nodes.equals(last_key)) {
} else
last_nodes = last_key;
isLoading = false;
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
}
private void getLastKeyFromFirebase() {
Query getLastKey;
if (classname.equals("A")) {
getLastKey = FirebaseDatabase.getInstance().getReference()
.child("ContentJokes")
.orderByChild("subcategory").equalTo(content)
.limitToLast(1);
getLastKey.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot lastKey : dataSnapshot.getChildren()) {
last_key = lastKey.getKey();
Toast.makeText(ContentActivity.this, String.valueOf(last_key), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(ContentActivity.this, "cannot get last key", Toast.LENGTH_SHORT).show();
}
});
} else if (classname.equals("B")) {
getLastKey = FirebaseDatabase.getInstance().getReference()
.child("ContentShayari")
.orderByChild("subcategory").equalTo(content)
.limitToLast(1);
getLastKey.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot lastKey : dataSnapshot.getChildren()) {
last_key = lastKey.getKey();
Toast.makeText(ContentActivity.this, String.valueOf(last_key), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(ContentActivity.this, "cannot get last key", Toast.LENGTH_SHORT).show();
}
});
}
}
RecyclerAdapter Code:
public class NewAdapterContent extends RecyclerView.Adapter<NewAdapterContent.ViewHolder> {
ArrayList<ContentModel>contentModels;
Context context;
public NewAdapterContent(ArrayList<ContentModel>contentModels, Context context) {
this.contentModels = contentModels;
this.context = context;
}
public void addAll(ArrayList<ContentModel>contentModels){
int initSize = contentModels.size();
contentModels.addAll(contentModels);
notifyItemRangeChanged(initSize, contentModels.size());
}
public String getLastItemId(){
return contentModels.get(contentModels.size()-1).getId();
}
#NonNull
#Override
public NewAdapterContent.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull NewAdapterContent.ViewHolder holder, int position) {
holder.textView.setText(contentModels.get(position).getContent());
}
#Override
public int getItemCount() {
return contentModels.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView textView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.contentText);
}
}
}
Anytime of help would be appreciated. Please help.
Try it which is very easy to use that was worked for me by using the custom RecyclerView.OnScrollListener named EndlessRecyclerViewScrollListener -
EndlessRecyclerViewScrollListener scrollListener = new
EndlessRecyclerViewScrollListener(layoutManager) {
#Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
if(!isLoading){
getUsers();
isLoading = true;
}
}
};
recyclerView.addOnScrollListener(scrollListener);

How do I retrieve array data from firebase database?

I retrieved data from firebase database in recylerview. But I have in post node "postimg" has a another list item.
For this I use one more listener in onBindViewHolder. But this does not seem right to me.
So how to do all this works in mainactivity and pass in adapter?
Here is my code:
#Override
public void onBindViewHolder(#NonNull final PostHolder postHolder, final int i) {
postHolder.setData(mPost.get(i));
final String PostKey=mPost.get(i).getPostid();
FirebaseAuth mAuth=FirebaseAuth.getInstance();
final String currentUserID=mAuth.getCurrentUser().getUid();
final DatabaseReference post=FirebaseDatabase.getInstance().getReference().child("Posts");
post.child(PostKey).child("postimg").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
if (dataSnapshot.exists())
{
for (DataSnapshot dataSnapshot1:dataSnapshot.getChildren())
{
String postimagelink =dataSnapshot1.getValue().toString();
postimagelist.add(postimagelink);
}
String[] urls =postimagelist.toArray(new String[postimagelist.size()]);
postHolder.mPager.setAdapter(new SlidingImage_Adapter(mContext,urls));
postHolder.indicator.setViewPager(postHolder.mPager);
final float density = mContext.getResources().getDisplayMetrics().density;
postHolder.indicator.setRadius(5 * density);
postHolder.NUM_PAGES = urls.length;
postHolder.indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
#Override
public void onPageSelected(int position) {
postHolder.currentPage = position;
}
#Override
public void onPageScrolled(int pos, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int pos) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
this my query in MainActivity.
mAdapter = new PostAdapter(MainActivity.this);
query = PostRef
.orderByChild("timestamp")
.limitToLast(mPostsPerPage);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<Post> userModels = new ArrayList<>();
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
String o=userSnapshot.getKey();
userModels.add(userSnapshot.getValue(Post.class));
//Here I want to retrieve no of "postimg"child and its value and pass in adapter//
}
mAdapter.addAll(userModels);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Categories