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);
Related
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().
I am using RecyclerView to show data that is fetching from firebase Realtime Database. When I am opening recycler view activity it is showing nothing but when I go to previous activity come again then it is showing.
THIS IS THE ACTIVITY IN WHICH DATA HAS TO BE SHOWN-
public class BrakesItemActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private FloatingActionButton floatingActionButton;
private FirebaseDatabase database;
private DatabaseReference BrakestransactionDb, brakesDb;
private FirebaseRecyclerOptions<Transaction> options;
private FirebaseRecyclerAdapter<Transaction, TransactionViewHolder> adapter;
int sumofbrakescost = 0;
String sumofbrakescostvalue;
BottomAppBar bottomAppBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_last2);
bottomAppBar = findViewById(R.id.bottom_app_bar);
recyclerView = findViewById(R.id.recycler_view);
floatingActionButton = findViewById(R.id.floating_button);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
setSupportActionBar(bottomAppBar);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(BrakesItemActivity.this, BInputActivity.class);
startActivity(intent);
}
});
database = FirebaseDatabase.getInstance();
BrakestransactionDb = database.getReference().child("Brakes Items Transaction");
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(BrakesItemActivity.this));
BrakestransactionDb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Map<String, Object> map = (Map<String, Object>) ds.getValue();
Object totalcost = map.get("totalcoststring");
int totalcostvalue = Integer.parseInt(String.valueOf(totalcost));
sumofbrakescost += totalcostvalue;
sumofbrakescostvalue = String.valueOf(sumofbrakescost);
}
brakesDb = database.getReference().child("Department").child("Brakes").child("Cost");
brakesDb.setValue(sumofbrakescostvalue);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
showTask();
}
private void showTask() {
options = new FirebaseRecyclerOptions.Builder<Transaction>().setQuery(BrakestransactionDb, Transaction.class).build();
adapter = new FirebaseRecyclerAdapter<Transaction, TransactionViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull TransactionViewHolder holder, int position, #NonNull Transaction model) {
holder.item_name_card.setText(model.getNameofitemstring());
holder.bought_by_card.setText(model.getBoughtbystring());
holder.bought_from_card.setText(model.getBoughtfromstring());
holder.date_card.setText(model.getDatestring());
holder.time_card.setText(model.getTimestring());
holder.cost_of_one_item_card.setText(model.getCostofoneitemstring());
holder.number_of_items_card.setText(model.getNumberofitemstring());
holder.total_cost_card.setText(model.getTotalcoststring());
}
#NonNull
#Override
public TransactionViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.transaction_row, parent, false);
return new TransactionViewHolder(itemView);
}
};
recyclerView.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
#Override
public boolean onContextItemSelected(#NonNull MenuItem item) {
if (item.getTitle().equals("Delete")) {
deleteTransaction(adapter.getRef(item.getOrder()).getKey());
}
return super.onContextItemSelected(item);
}
private void deleteTransaction(String key) {
BrakestransactionDb.child(key).removeValue();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.bottommenu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.delete_all) {
BrakestransactionDb.removeValue();
}
if (item.getItemId() == R.id.home_button) {
Intent intent = new Intent(this, NavActivity.class);
finish();
startActivity(intent);
if (item.getItemId() == R.id.back_item_activity) {
Intent intent1 = new Intent(this, Department.class);
finish();
startActivity(intent1);
}
}
return super.onOptionsItemSelected(item);
}
}
THIS IS THE MODEL CLASS I MADE-
package com.example.android.zfr.Model;
public class Transaction {
private String nameofitemstring,boughtbystring,boughtfromstring,costofoneitemstring,datestring,
timestring,totalcoststring,numberofitemstring;
public String getNameofitemstring() { return nameofitemstring; }
public void setNameofitemstring(String nameofitemstring) { this.nameofitemstring = nameofitemstring; }
public String getBoughtbystring() {return boughtbystring; }
public void setBoughtbystring(String bought string) {
this.boughtbystring = boughtbystring;
}
public String getBoughtfromstring() { return boughtfromstring; }
public void setBoughtfromstring(String boughtfromstring) { this.boughtfromstring = boughtfromstring; }
public String getCostofoneitemstring() {
return costofoneitemstring;
}
public void setCostofoneitemstring(String costofoneitemstring) { this.costofoneitemstring = costofoneitemstring; }
public String getDatestring() { return datestring; }
public void setDatestring(String datestring) { this.datestring = datestring; }
public String getTimestring() { return timestring; }
public void setTimestring(String timestring) { this.timestring = timestring; }
public String getTotalcoststring() { return totalcoststring; }
public void setTotalcoststring(String totalcoststring) { this.totalcoststring = totalcoststring; }
public String getNumberofitemstring() { return numberofitemstring; }
public void setNumberofitemstring(String numberofitemstring) { this.numberofitemstring = numberofitemstring; }
public Transaction() { }
public Transaction(String nameofitemstring,String boughtbystring,String boughtfromstring,String costofoneitemstring, String timestring,
String datestring ,String totalcoststring , String numberofitemstring ){
this.nameofitemstring=nameofitemstring;
this.boughtbystring=boughtbystring;
this.boughtfromstring=boughtfromstring;
this.costofoneitemstring=costofoneitemstring;
this.datestring=datestring;
this.timestring=timestring;
this.numberofitemstring=numberofitemstring;
this.totalcoststring=totalcoststring;
}
}
THIS THE VIEWHOLDER CLASS-
package com.example.android.zfr.ViewHolder;
import android.view.ContextMenu;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.android.zfr.R;
import com.facebook.shimmer.ShimmerFrameLayout;
public class TransactionViewHolder extends RecyclerView.ViewHolder implements
View.OnCreateContextMenuListener{
public TextView item_name_card,bought_by_card,bought_from_card,date_card,
time_card,cost_of_one_item_card,number_of_items_card,total_cost_card;
public TransactionViewHolder(#NonNull View itemView) {
super(itemView);
item_name_card=itemView.findViewById(R.id.item_name_card);
bought_by_card=itemView.findViewById(R.id.bought_by_card);
bought_from_card=itemView.findViewById(R.id.bought_from_card);
date_card=itemView.findViewById(R.id.date_card);
time_card=itemView.findViewById(R.id.time_card);
cost_of_one_item_card=itemView.findViewById(R.id.cost_of_one_item_card);
number_of_items_card=itemView.findViewById(R.id.number_of_items_card);
total_cost_card=itemView.findViewById(R.id.total_cost_card);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{ menu.add(0,0,getAdapterPosition(),"Delete"); }
}
Please help.
you need to realize that Firebase is Asynchronous, meaning that your showTask() gets called even before your database is able to send you the data. To avoid this issue, you need to put your showTask() inside your addValueEventListener. Try this:
BrakestransactionDb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Map<String, Object> map = (Map<String, Object>) ds.getValue();
Object totalcost = map.get("totalcoststring");
int totalcostvalue = Integer.parseInt(String.valueOf(totalcost));
sumofbrakescost += totalcostvalue;
sumofbrakescostvalue = String.valueOf(sumofbrakescost);
}
brakesDb = database.getReference().child("Department").child("Brakes").child("Cost");
brakesDb.setValue(sumofbrakescostvalue);
showTask();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
It worked by putting
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(BrakesItemActivity.this));
in onDatachange method like this:
BrakestransactionDb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Map<String, Object> map = (Map<String, Object>) ds.getValue();
Object totalcost = map.get("totalcoststring");
int totalcostvalue = Integer.parseInt(String.valueOf(totalcost));
sumofbrakescost += totalcostvalue;
sumofbrakescostvalue = String.valueOf(sumofbrakescost);
}
brakesDb = database.getReference().child("Department").child("Brakes").child("Cost");
brakesDb.setValue(sumofbrakescostvalue);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(BrakesItemActivity.this));
}
Thats the Fragment containing the recyclerView which leads to activity with Chat
public class FragmentBusinessHome extends Fragment {
/* For to do adapter */
private List<String> namesToDo;
private List<String> uids;
private List<String> servicesNames;
private AdapterToDo adapterToDo;
private RecyclerView toDoRecyclerView;
/* For checking requests adapter */
private List<String> userUids;
private List<String> serviceNames;
private List<String> userNames;
private AdapterPendingRequests adapterPendingRequests;
private RecyclerView pendingRequestsRecyclerView;
private FirebaseAuth mAuth;
public FragmentBusinessHome(){
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_business_home, container, false);
mAuth = FirebaseAuth.getInstance();
namesToDo = new ArrayList<>();
uids = new ArrayList<>();
servicesNames = new ArrayList<>();
userUids = new ArrayList<>();
serviceNames = new ArrayList<>();
userNames = new ArrayList<>();
toDoRecyclerView = view.findViewById(R.id.toDoRecyclerView);
pendingRequestsRecyclerView = view.findViewById(R.id.requestsToApproveRecyclerView);
LinearLayoutManager layoutManagerActive = new LinearLayoutManager(getActivity());
layoutManagerActive.setStackFromEnd(true);
layoutManagerActive.setReverseLayout(true);
toDoRecyclerView.setLayoutManager(layoutManagerActive);
LinearLayoutManager layoutManagerPendingRequests = new LinearLayoutManager(getActivity());
layoutManagerPendingRequests.setStackFromEnd(true);
layoutManagerPendingRequests.setReverseLayout(true);
pendingRequestsRecyclerView.setLayoutManager(layoutManagerPendingRequests);
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference checkRequests = FirebaseDatabase.getInstance().getReference("Providers").child(uid).child("Gigs");
checkRequests.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
if (ds.getValue(String.class).equals("active")) {
DatabaseReference getRequests = FirebaseDatabase.getInstance().getReference("Services").child(ds.getKey()).child(uid).child("Gigs").child("pending");
getRequests.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
serviceNames.clear(); userNames.clear(); userUids.clear();
for (DataSnapshot data : dataSnapshot.getChildren()) {
String userName = data.child("names").getValue(String.class);
String serviceName = ds.getKey();
String userUid = data.getKey();
userNames.add(userName);
serviceNames.add(serviceName);
userUids.add(userUid);
adapterPendingRequests = new AdapterPendingRequests(getActivity(), userUids, userNames, serviceNames, mAuth.getCurrentUser().getUid());
adapterPendingRequests.notifyDataSetChanged();
pendingRequestsRecyclerView.setAdapter(adapterPendingRequests);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
DatabaseReference getActive = FirebaseDatabase.getInstance().getReference("Services").child(ds.getKey()).child(uid).child("Gigs").child("active");
getActive.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userUids.clear(); namesToDo.clear(); servicesNames.clear();
for(DataSnapshot datas : dataSnapshot.getChildren()){
String userUid = datas.getKey();
String userName = datas.child("names").getValue(String.class);
String serviceName = ds.getKey();
userUids.add(userUid);
namesToDo.add(userName);
servicesNames.add(serviceName);
Log.d("TAG", userUids.toString());
adapterToDo = new AdapterToDo(getActivity(), namesToDo, userUids, servicesNames);
adapterToDo.notifyDataSetChanged();
toDoRecyclerView.setAdapter(adapterToDo);
if(!userUids.isEmpty()){
LinearLayout toDoLayout = view.findViewById(R.id.toDoLayout);
toDoLayout.setVisibility(View.VISIBLE);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return view;
}
}
Thats fragment's activity
private ImageButton moreBtn, chatsBtn;
private BottomNavigationView bottomNavigationView;
private FirebaseAuth mAuth;
private FirebaseUser mUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business_home);
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, new FragmentBusinessHome()).commit();
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser();
bottomNavigationView = findViewById(R.id.bottomNavigationView);
bottomNavigationView.setOnNavigationItemSelectedListener(navigationListener);
moreBtn = findViewById(R.id.moreBtn);
chatsBtn = findViewById(R.id.chatsBtn);
moreBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final PopupMenu popup = new PopupMenu(BusinessHomeActivity.this, moreBtn);
popup.getMenuInflater().inflate(R.menu.popup_toolbar_more_menu, popup.getMenu());
popup.show();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.id.sign_out_btn:
mAuth.signOut();
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
Intent to_login_activity = new Intent(BusinessHomeActivity.this, WelcomeActivity.class);
startActivity(to_login_activity);
finish();
}
}, 1000);
}
return true;
}
});
}
});
chatsBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(BusinessHomeActivity.this, "Will be available soon!", Toast.LENGTH_LONG).show();
}
});
}
private BottomNavigationView.OnNavigationItemSelectedListener navigationListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selectedFragment = null;
switch (menuItem.getItemId()){
case R.id.home:
selectedFragment = new FragmentBusinessHome();
break;
case R.id.inbox:
selectedFragment = new FragmentInbox();
break;
case R.id.profile:
selectedFragment = new FragmentProfile();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, selectedFragment).commit();
return true;
}
};
That's the adapter for the fragment
public class AdapterToDo extends RecyclerView.Adapter<AdapterToDo.MyHolder> {
Context context;
List<String> namesToDo;
List<String> uids;
List<String> servicesNames;
public AdapterToDo(Context context, List<String> namesToDo, List<String> uids, List<String> servicesNames) {
this.context = context;
this.namesToDo = namesToDo;
this.uids = uids;
this.servicesNames = servicesNames;
}
#NonNull
#Override
public AdapterToDo.MyHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.to_do_item, parent, false);
return new AdapterToDo.MyHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final AdapterToDo.MyHolder holder, final int position) {
holder.userNames.setText(namesToDo.get(position));
String currentUid = uids.get(position);
String currentOppositeName = namesToDo.get(position);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent to_chat_activity = new Intent(context, ChatActivity.class);
to_chat_activity.putExtra("oppositeUid", currentUid);
to_chat_activity.putExtra("oppositeNames", currentOppositeName);
to_chat_activity.putExtra("class", getClass().getName());
context.startActivity(to_chat_activity);
}
});
}
#Override
public int getItemCount() {
return uids.size();
}
class MyHolder extends RecyclerView.ViewHolder {
private TextView userNames;
private MyHolder(#NonNull View itemView) {
super(itemView);
userNames = itemView.findViewById(R.id.userNames);
}
}
}
That is the Activity where the fragment's adapter leads to
private String oppositeUid, oppositeNames, className;
private TextView oppositeNamesTextView;
private Button sendBtn;
private EditText message;
private FirebaseAuth mAuth;
private RecyclerView recyclerView;
private List<ModelChat> modelChatList;
private AdapterChat chatAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
mAuth = FirebaseAuth.getInstance();
Intent intent = getIntent();
oppositeUid = intent.getStringExtra("oppositeUid");
oppositeNames = intent.getStringExtra("oppositeNames");
className = intent.getStringExtra("class");
Log.d("CLASSNAME", className);
modelChatList = new ArrayList<>();
oppositeNamesTextView = findViewById(R.id.oppositeNames);
sendBtn = findViewById(R.id.sendBtn);
message = findViewById(R.id.message);
recyclerView = findViewById(R.id.chatRecyclerView);
LinearLayoutManager linearLayout = new LinearLayoutManager(this);
linearLayout.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayout);
oppositeNamesTextView.setText(oppositeNames);
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String mMessage = message.getText().toString().trim();
if(!TextUtils.isEmpty(mMessage)){
HashMap<Object, String> hashMap = new HashMap<>();
hashMap.put("sender", mAuth.getCurrentUser().getUid());
hashMap.put("receiver", oppositeUid);
hashMap.put("message", mMessage);
hashMap.put("timestamp", String.valueOf(System.currentTimeMillis()));
if(className.equals("com.example.uploy.AdapterToDo$1")){
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Providers").child(mAuth.getCurrentUser().getUid()).child("Chats").child(oppositeUid);
databaseReference.push().setValue(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
message.setText("");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ChatActivity.this, "An error occurred!", Toast.LENGTH_SHORT).show();
}
});
DatabaseReference databaseReference1 = FirebaseDatabase.getInstance().getReference("Users").child(oppositeUid).child("Chats").child(mAuth.getCurrentUser().getUid());
databaseReference1.push().setValue(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
message.setText("");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ChatActivity.this, "An error occurred!", Toast.LENGTH_SHORT).show();
}
});
}else{
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Providers").child(oppositeUid).child("Chats").child(mAuth.getCurrentUser().getUid());
databaseReference.push().setValue(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
message.setText("");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ChatActivity.this, "An error occurred!", Toast.LENGTH_SHORT).show();
}
});
DatabaseReference databaseReference1 = FirebaseDatabase.getInstance().getReference("Users").child(mAuth.getCurrentUser().getUid()).child("Chats").child(oppositeUid);
databaseReference1.push().setValue(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
message.setText("");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ChatActivity.this, "An error occurred!", Toast.LENGTH_SHORT).show();
}
});
}
}
}
});
if(className.equals("com.example.uploy.AdapterToDo$1")){
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Providers").child(mAuth.getCurrentUser().getUid()).child("Chats").child(oppositeUid);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
modelChatList.clear();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
if(snapshot.getKey().equals("details")){
continue;
}
ModelChat modelChat = snapshot.getValue(ModelChat.class);
modelChatList.add(modelChat);
chatAdapter = new AdapterChat(ChatActivity.this, modelChatList);
chatAdapter.notifyDataSetChanged();
recyclerView.setAdapter(chatAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}else{
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users").child(mAuth.getCurrentUser().getUid()).child("Chats").child(oppositeUid);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
modelChatList.clear();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
if(snapshot.getKey().equals("details")){
continue;
}
ModelChat modelChat = snapshot.getValue(ModelChat.class);
modelChatList.add(modelChat);
chatAdapter = new AdapterChat(ChatActivity.this, modelChatList);
chatAdapter.notifyDataSetChanged();
recyclerView.setAdapter(chatAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
Log.d("TAG", "PRESSED");
}
The PROBLEM is that when the fragment opens the activity (it contains messages in chat between to users, which are loaded perfectly fine) and the activity detects any change in the chats database reference it stops and loads the previous activity (where the fragment is placed). I wonder what the solution is and I would be glad if you help me.
I made a button, which when clicked changes values on the database,
the status/color of the button is based on the value on the database.
How to prevent all drawables from getting refreshed on recyclerview just because one drawable had its value changed?
Result i get:
https://media.giphy.com/media/frHERBcrLUA8x14bsh/giphy.gif
public MainAdapter(Context mContext, List<Posts> mPost)
{
Log.d(TAG, "Main Adapter Start");
this.mContext = mContext;
this.mPost = mPost;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(mContext).inflate(R.layout.all_posts_layout, viewGroup, false);
return new MainAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
final Posts post = mPost.get(position);
final String Postkey = post.getPost_uid();
final String likes = Integer.toString(post.getLikes());
holder.setUpStatus(Postkey);
LikesRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
holder.LikepostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
LikeChecker = true;
LikesRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if (LikeChecker.equals(true))
{
if (dataSnapshot.child(Postkey).hasChild(currentUserID)) {
LikesRef.child(Postkey).child(currentUserID).removeValue();
PostsRef.child(Postkey).child("likes").setValue(post.getLikes()-1);
LikeChecker = false;
} else {
LikesRef.child(Postkey).child(currentUserID).setValue(true);
DisikesRef.child(Postkey).child(currentUserID).removeValue();
StoreToHistory(Postkey);
DisikesRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(currentUserID).exists())
{
PostsRef.child(Postkey).child("likes").setValue(post.getLikes()+2);
}
else {
PostsRef.child(Postkey).child("likes").setValue(post.getLikes()+1);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
LikeChecker = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}});
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
}
#Override
public int getItemCount()
{
return mPost.size();
}
ViewHolder:
public class ViewHolder extends RecyclerView.ViewHolder {
View mView;
ImageButton LikepostButton, DislikepostButton;
int countLikes, countDislikes, countComms;
public ViewHolder(View itemView) {
super(itemView);
mView = itemView;
currentUserId = FirebaseAuth.getInstance().getCurrentUser().getUid();
LikepostButton = itemView.findViewById(R.id.like_button);
DislikepostButton = itemView.findViewById(R.id.dislike);
CommentPostButton = itemView.findViewById(R.id.comment_button);
DisplayNoOfLikes = itemView.findViewById(R.id.display_number_of_likes);
DisplayNoOfDislikes = itemView.findViewById(R.id.display_number_of_dislikes);
}
public void setUpStatus(final String PostKey)
{
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Ups");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(PostKey).hasChild(currentUserID))
{
LikepostButton.setImageResource(R.drawable.upvote);
DisplayNoOfLikes.setTextColor(Color.parseColor("#f14c00"));
}
else
{
LikepostButton.setImageResource(R.drawable.upvote_novote);
}
DisikesRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(PostKey).hasChild(currentUserID))
{
DislikepostButton.setImageResource(R.drawable.downvote_orange);
DisplayNoOfLikes.setTextColor(Color.parseColor("#df3168a7"));
}
else {
DislikepostButton.setImageResource(R.drawable.downvote_novote);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
}); }
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
I cannot get the chats to display in the recycler adapter, I have already in firebase database and as well have attached firebase recycler adapter
I have tried some of the ways of getting the recycler adapter to display the chats but unable to display my adapter
private void DisplayReceiverInformation() {
receiverName.setText(messageReceiverName);
rootReference.child("Users").child(messageReceiverID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
//retrieve from db
final String userName = dataSnapshot.child("fullName").getValue().toString();
final String profileImage = dataSnapshot.child("profileImage").getValue().toString();
//set values
receiverName.setText(userName);
Picasso.get().load(profileImage).placeholder(R.drawable.profile_image_placeholder).into(receiverProfileImage);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
\\\
//initialize the above variables
private void InitializeFields() {
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//connect chat custom bar to chat activity
ActionBar actionBar = getSupportActionBar();
Objects.requireNonNull(actionBar).setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View action_bar_view = layoutInflater.inflate(R.layout.chat_custom_toolbar, null);
actionBar.setCustomView(action_bar_view);
receiverName = findViewById(R.id.custom_profile_name);
receiverProfileImage = findViewById(R.id.custom_profile_image);
sendMessageButton = findViewById(R.id.send_message_button);
userMessageInput = findViewById(R.id.input_message);
// messageAdapter = new MessagesAdapter(ChatActivity.this,)
messageAdapter = new MessagesAdapter( messageList);
userMessagesList = (RecyclerView) findViewById(R.id.messages_list_of_users);
linearLayoutManager = new LinearLayoutManager(this);
userMessagesList.setHasFixedSize(true);
userMessagesList.setLayoutManager(linearLayoutManager);
userMessagesList.setAdapter(messageAdapter);
}
\\\
#Override
protected void onStart() {
super.onStart();
rootReference.child("Messages").child(messageSenderID).child(messageReceiverID)
.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Messages messages = dataSnapshot.getValue(Messages.class);
messageList.add(messages);
messageAdapter.notifyDataSetChanged();
}
#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) {
}
});
}
\\\
MessagesAdapter.java
package com.MwandoJrTechnologies.the_smart_parent.Chats;
public class MessagesAdapter extends RecyclerView.Adapter<MessagesAdapter.MessageViewHolder> {
private List<Messages> userMessagesList;
private FirebaseAuth mAuth;
private DatabaseReference usersDatabaseReference;
public MessagesAdapter(List<Messages> userMessagesList) {
this.userMessagesList = userMessagesList;
}
public class MessageViewHolder extends RecyclerView.ViewHolder {
public TextView senderMessageText;
public TextView receiverMessageText;
public CircleImageView receiverProfileImage;
public MessageViewHolder(#NonNull View itemView) {
super(itemView);
senderMessageText = (TextView) itemView.findViewById(R.id.sender_message_text_view);
receiverMessageText = (TextView) itemView.findViewById(R.id.receiver_message_text_view);
receiverProfileImage = (CircleImageView) itemView.findViewById(R.id.receiver_message_profile_image);
}
}
#NonNull
#Override
public MessageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.message_layout_of_users, parent, false);
mAuth = FirebaseAuth.getInstance();
return new MessageViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MessageViewHolder holder, int position) {
//get senders ID
String messageSenderID = mAuth.getCurrentUser().getUid();
Messages messages = userMessagesList.get(position);
//get ID of the receiver
String fromUserID = messages.getFrom();
//now get type of message whether text or image
String fromMessageType = messages.getType();
//retrieve receivers profile image
usersDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(fromUserID);
usersDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("profileImage")){
String receiverImage = dataSnapshot.child("profileImage").getValue().toString();
Picasso.get().load(receiverImage).placeholder(R.drawable.profile_image_placeholder)
.into(holder.receiverProfileImage);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
if (fromMessageType.equals("text")){
holder.receiverMessageText.setVisibility(View.INVISIBLE);
holder.receiverProfileImage.setVisibility(View.INVISIBLE);
//display the message to the sender and to the receiver
//for the receiver
if (fromUserID.equals(messageSenderID)) {
holder.senderMessageText.setBackgroundResource(R.drawable.sender_text_message_background);
holder.senderMessageText.setTextColor(Color.WHITE);
holder.senderMessageText.setGravity(Gravity.LEFT);
holder.senderMessageText.setText(messages.getMessage());
//for receiver
} else {
holder.senderMessageText.setVisibility(View.INVISIBLE);
holder.receiverMessageText.setVisibility(View.VISIBLE);
holder.receiverProfileImage.setVisibility(View.VISIBLE);
holder.receiverMessageText.setBackgroundResource(R.drawable.receiver_text_message_background);
holder.receiverMessageText.setTextColor(Color.WHITE);
holder.receiverMessageText.setGravity(Gravity.LEFT);
holder.receiverMessageText.setText(messages.getMessage());
}
}
}
#Override
public int getItemCount() {
return userMessagesList.size();
}
}
/// my modal class
Messages.java
package com.MwandoJrTechnologies.the_smart_parent.Chats;
//modal class to retrieve messages
public class Messages {
public String date, time, type, message, from;
public Messages(){
//empty default constructor
}
//generate constructor with parameters
public Messages(String date, String time, String type, String message, String from) {
this.date = date;
this.time = time;
this.type = type;
this.message = message;
this.from = from;
}
//generate getter and setter
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
}
The above code does not give me any result in the FirebaseRecycler adapter yet I expect it to display in the FirebaseRecycler adapter
I think the answer is below.
private void DisplayReceiverInformation() {
receiverName.setText(messageReceiverName);
rootReference.child("Users").child(messageReceiverID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
//retrieve from db
final String userName = dataSnapshot.child("fullName").getValue().toString();
final String profileImage = dataSnapshot.child("profileImage").getValue().toString();
//set values
receiverName.setText(userName);
Picasso.get().load(profileImage).placeholder(R.drawable.profile_image_placeholder).into(receiverProfileImage);
messageAdapter = new MessagesAdapter( messageList);
userMessagesList = (RecyclerView) findViewById(R.id.messages_list_of_users);
linearLayoutManager = new LinearLayoutManager(this);
userMessagesList.setHasFixedSize(true);
userMessagesList.setLayoutManager(linearLayoutManager);
userMessagesList.setAdapter(messageAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
//here the data will be null so you must display data inside onDataChange() method.
}