ProgressDialog within an Adapter FireStore - java

Problem:
I have a screen where it shows the schedules of a certain user.
But at the same time I need to check if any of the schedules is already occupied, and color your background a darker color.
Print 1: RecyclerView screen with schedules.
Print 2: It is the same screen, but after checking the available schedules.
Note: If we are on the Wi-Fi network, charging is fast, but if it is a mobile internet network, it is very slow.
I need some way, to add a ProgressDialog inside my Adapter, exactly in the moment where the check of the schedules is done.
On here:
/*Checar Horario disponivel*/
final FirebaseFirestore mDB = FirebaseFirestore.getInstance();
CollectionReference mDBHorarios = mDB.collection("Empresas").document(empresa).collection("Agendamentos");
mDBHorarios.whereEqualTo("profissional_id", ref.getId_Prof()).whereEqualTo("agenda_hora", ref.getHora())
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
Agendamentos doc = document.toObject(Agendamentos.class);
String horaAgenda = doc.getAgenda_hora();
/*Cor do fundo*/
if ( horaAgenda.equals(ref.getHora()) ){
fundoHora.setBackgroundColor(Color.parseColor("#E0E0E0"));
statusHoraAgenda = true;
}
}
} else {
}
}
});
Note: It may be that this is not a great way. I accept suggests if there is a better way to do this query in a RecyclerView.
Code Full - Adapter:
public class HorariosProfissionalAdapter extends FirestoreAdapter<HorariosProfissionalAdapter.ViewHolder>{
public interface OnHorariosProfissionaisListner {
void onHorarioProfissionaisSelected(DocumentSnapshot horariosProfissional);
}
private OnHorariosProfissionaisListner mListner;
public HorariosProfissionalAdapter(Query query, OnHorariosProfissionaisListner listner){
super(query);
mListner = listner;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
return new ViewHolder(inflater.inflate(R.layout.card_horarios_profissional, parent, false));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(getSnapshot(position), mListner);
}
static class ViewHolder extends RecyclerView.ViewHolder {
private Boolean statusHoraAgenda = false;
#BindView(R.id.tvHoraProf)
TextView hora;
#BindView(R.id.fundoHorario)
LinearLayout fundoHora;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
public void bind(final DocumentSnapshot snapshot,
final OnHorariosProfissionaisListner listener) {
final HorariosProfissionais ref = snapshot.toObject(HorariosProfissionais.class);
String empresa = ref.getId_Emp();
/*Checar Horario disponivel*/
final FirebaseFirestore mDB = FirebaseFirestore.getInstance();
CollectionReference mDBHorarios = mDB.collection("Empresas").document(empresa).collection("Agendamentos");
mDBHorarios.whereEqualTo("profissional_id", ref.getId_Prof()).whereEqualTo("agenda_hora", ref.getHora())
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
Agendamentos doc = document.toObject(Agendamentos.class);
String horaAgenda = doc.getAgenda_hora();
/*Cor do fundo*/
if ( horaAgenda.equals(ref.getHora()) ){
fundoHora.setBackgroundColor(Color.parseColor("#E0E0E0"));
statusHoraAgenda = true;
}
}
} else {
}
}
});
hora.setText(ref.getHora());
// Click listener
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null && !statusHoraAgenda) {
listener.onHorarioProfissionaisSelected(snapshot);
}
}
});
}
}
}
Code Full - Activity:
public class Agenda_profissionais extends AppCompatActivity implements HorariosProfissionalAdapter.OnHorariosProfissionaisListner {
private String mId_Empresa = null;
private String mId_Profissional = null;
private String mNome_Profissional = null;
private RecyclerView mCardHorarios;
private HorariosProfissionalAdapter mAdapter;
private FirebaseFirestore mFirestore;
private Query mQuery;
private ProgressDialog mProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_agenda_profissionais);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Horario");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
/* CONFIGURAÇÃO TOOLBAR*/
Bundle extra = getIntent().getExtras();
if ( extra != null ){
mId_Empresa = extra.getString("id_empresa");
mId_Profissional = extra.getString("id_profissional");
mNome_Profissional = extra.getString("nome_profissional");
}
/*Firebase*/
mFirestore = FirebaseFirestore.getInstance();
mQuery = mFirestore.collection("Empresas").document(mId_Empresa).collection("Profissionais").document(mId_Profissional).collection("Horarios");
mCardHorarios = (RecyclerView) findViewById(R.id.cardListaHorariosProf);
mAdapter = new HorariosProfissionalAdapter(mQuery, this){
#Override
protected void onDataChanged() {
if (getItemCount() == 0) {
mCardHorarios.setVisibility(View.GONE);
//mTxtVazio.setVisibility(View.VISIBLE);
} else {
mCardHorarios.setVisibility(View.VISIBLE);
}
}
};
mCardHorarios.setLayoutManager(new LinearLayoutManager(this));
mCardHorarios.setAdapter(mAdapter);
}
#Override
public void onStart() {
super.onStart();
// Start listening for Firestore updates
if (mAdapter != null) {
mAdapter.startListening();
}
}
#Override
public void onStop() {
super.onStop();
if (mAdapter != null) {
mAdapter.stopListening();
}
}
#Override
public void onHorarioProfissionaisSelected(DocumentSnapshot horario) {
HorariosProfissionais idHorario = horario.toObject(HorariosProfissionais.class);
Toast.makeText(Agenda_profissionais.this, "Horario selecionado: " +idHorario.getHora(), Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_agendamento, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
finish();
}
}

Solution
public void bind(final DocumentSnapshot snapshot,
final OnHorariosProfissionaisListner listener) {
final HorariosProfissionais ref = snapshot.toObject(HorariosProfissionais.class);
String empresa = ref.getId_Emp();
mProgress = new ProgressDialog(itemView.getContext());
mProgress.setMessage("testando....");
mProgress.show();
/*Checar Horario disponivel*/
final FirebaseFirestore mDB = FirebaseFirestore.getInstance();
CollectionReference mDBHorarios = mDB.collection("Empresas").document(empresa).collection("Agendamentos");
mDBHorarios.whereEqualTo("profissional_id", ref.getId_Prof()).whereEqualTo("agenda_hora", ref.getHora())
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
Agendamentos doc = document.toObject(Agendamentos.class);
String horaAgenda = doc.getAgenda_hora();
/*Cor do fundo*/
if ( horaAgenda.equals(ref.getHora()) ){
fundoHora.setBackgroundColor(Color.parseColor("#E0E0E0"));
statusHoraAgenda = true;
}
}
mProgress.dismiss();
} else {
}
}
});

Related

Deletion of Node is not working in Firebase Realtime Database in Android Java

I am making an application in which products are inserted into the database and I am inserting the 1 product once. it is working fine. But when I delete a specific node/ product from Database. deletion code is also working fine but at the same time product is again adding into the database.
Main Fragment Code;
public class Products_fragment extends Fragment {
FloatingActionButton fab_addproduct;
RecyclerView recyclerView;
EditText searchview;
BottomSheetDialog bottomSheetDialog;
FirebaseDatabase firebaseDatabase;
ArrayList<Product_model> DatabaseProductlist;
FirebaseAuth auth;
CircularDotsLoader ProgressBar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_products_fragment, container, false);
setviews(view);
setInitilization();
setclicks();
setadapter();
return view;
}
private void setInitilization() {
DatabaseProductlist = new ArrayList<>();
}
private void setadapter() {
FirebaseDatabase database = FirebaseDatabase.getInstance();
FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
assert currentFirebaseUser != null;
String UID = currentFirebaseUser.getUid();
DatabaseReference reference = database.getReference("Users").child(UID).child("Products");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
ProgressBar.setVisibility(View.GONE);
DatabaseProductlist.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Product_model model = dataSnapshot.getValue(Product_model.class);
DatabaseProductlist.add(model);
}
Product_Adapter product_adapter = new Product_Adapter(DatabaseProductlist);
recyclerView.setAdapter(product_adapter);
product_adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
ToastUtility.showErrorToast(getContext(), error.getMessage());
}
});
}
private void setclicks() {
fab_addproduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bottomSheetDialog = new BottomSheetDialog(getContext(), R.style.AppBottomSheetDialogTheme);
bottomSheetDialog.setContentView(R.layout.productadd_bottom_sheet);
TextInputEditText product_id = bottomSheetDialog.findViewById(R.id.product_id);
TextInputEditText product_name = bottomSheetDialog.findViewById(R.id.product_name);
TextInputEditText product_quantity = bottomSheetDialog.findViewById(R.id.product_quantity);
MaterialButton add_btn = bottomSheetDialog.findViewById(R.id.add_btn);
TextInputEditText product_price = bottomSheetDialog.findViewById(R.id.product_price);
add_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Objects.requireNonNull(product_name.getText()).toString().isEmpty() || product_id.getText().toString().isEmpty() || product_price.getText().toString().isEmpty() || product_quantity.getText().toString().isEmpty()) {
ToastUtility.showErrorToast(getContext(), "Please Fill all Fields");
} else {
Product_model model = new Product_model(Integer.parseInt(product_id.getText().toString()), Integer.parseInt(product_quantity.getText().toString()), Integer.parseInt(product_price.getText().toString()), product_name.getText().toString());
firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference reference = firebaseDatabase.getReference("Users");
FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
assert currentFirebaseUser != null;
String UID = currentFirebaseUser.getUid();
reference.child(UID).child("Products").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.child(product_name.getText().toString().trim()).exists()) {
ToastUtility.showErrorToast(getContext(),"Product Already Exists!");
}
else{
reference.child(UID).child("Products").child(product_name.getText().toString().trim()).setValue(model).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
ToastUtility.showSuccessToast(getContext(),"Successfully Added");
setadapter();
}
else{
ToastUtility.showErrorToast(getContext(), Objects.requireNonNull(task.getException()).getMessage());
}
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
ToastUtility.showErrorToast(getContext(),error.getMessage());
}
});
}
}
});
bottomSheetDialog.show();
}
});
}
private void setviews(View view) {
recyclerView = view.findViewById(R.id.recyclerView);
fab_addproduct = view.findViewById(R.id.fab_addproduct);
searchview = view.findViewById(R.id.searchview);
ProgressBar = view.findViewById(R.id.progressbar);
}
}
Adapter Code:
public class Product_Adapter extends RecyclerView.Adapter<Product_Adapter.myviewholder> {
ArrayList<Product_model> dataholder;
public Product_Adapter(ArrayList<Product_model> dataholder) {
this.dataholder = dataholder;
}
#NonNull
#Override
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.singlerow_product, parent, false);
return new myviewholder(view); }
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull myviewholder holder, int position) {
holder.idtv.setText("" + dataholder.get(position).getId());
holder.pnametv.setText("" + dataholder.get(position).getProduct_name());
holder.pqtytv.setText("" + dataholder.get(position).getProduct_quantity());
holder.ppritv.setText("" + dataholder.get(position).getProduct_price());
holder.delimg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseDatabase db = FirebaseDatabase.getInstance();
FirebaseUser curUser = FirebaseAuth.getInstance().getCurrentUser();
assert curUser != null;
String UID = curUser.getUid();
String productname = dataholder.get(holder.getAdapterPosition()).getProduct_name();
DatabaseReference reference = db.getReference("Users").child(UID).child("Products");
reference.child(productname).setValue(null).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
ToastUtility.showSuccessToast(view.getContext(),"Suucessfully Deleted");
notifyItemRemoved(holder.getAdapterPosition());
}
else
{
ToastUtility.showErrorToast(view.getContext(),"Product is not deleting ");
}
}
});
}
});
}
#Override
public int getItemCount() {
return dataholder.size();
}
static class myviewholder extends RecyclerView.ViewHolder{
TextView idtv, pnametv, pqtytv, ppritv, delimg, edit_img;
public myviewholder(#NonNull View itemView) {
super(itemView);
idtv = itemView.findViewById(R.id.idtv);
pnametv = itemView.findViewById(R.id.pnametv);
pqtytv = itemView.findViewById(R.id.pqtytv);
ppritv = itemView.findViewById(R.id.ppritv);
delimg = itemView.findViewById(R.id.delimg);
edit_img = itemView.findViewById(R.id.edit_img);
}
}
}
When you click delete, shouldn't you remove your item from the list before notifying data changed:
//this code belongs to the part where you click the delete
.........
reference.child(productname).setValue(null).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
ToastUtility.showSuccessToast(view.getContext(),"Suucessfully Deleted");
//here remove the item from your list
dataholder.remove(holder.getAdapterPosition());
//then notify the adapter
notifyItemRemoved(holder.getAdapterPosition());
}

RecyclerView showing data after closing and coming back to activity

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

RecyclerView shows the same item many times in my app

I've created a match system in my Android program that also includes a chat section which has 2 fragments. The first fragment shows your chats, the second one shows your matches by using RecyclerView and UsersAdapter. However, in the second (match) fragment, people who you matched with are shown many times. For example, the same person is seen many times as you can see here.
My code is below.
UserFragment:
public class UsersFragment extends Fragment {
private RecyclerView recyclerView;
private UsersAdapter usersAdapter;
private List<User> mUsers;
FirebaseFirestore usersfragmentstore;
FirebaseAuth readauth;
DocumentReference readref;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
usersfragmentstore = FirebaseFirestore.getInstance();
readauth = FirebaseAuth.getInstance();
View view = inflater.inflate(R.layout.fragment_users, container, false);
readref = usersfragmentstore.collection("users").document(readauth.getCurrentUser().getUid());
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mUsers = new ArrayList<>();
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("users");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
readref.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
DocumentSnapshot shot = task.getResult();
List<String> matchedid2 = new ArrayList<>();
matchedid2 = (List<String>) shot.get("matchlist");
if (matchedid2.contains(snapshot.getKey())) {
User user = snapshot.getValue(User.class);
mUsers.add(user);
usersAdapter = new UsersAdapter(getContext(), mUsers, false);
recyclerView.setAdapter(usersAdapter);
}
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return view;
}
}
UserAdapter:
public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.ViewHolder> {
private Context mContext;
private List<User> mUsers;
private boolean ischat;
String theLastMessage;
public UsersAdapter(Context mContext, List<User> mUsers, boolean ischat) {
this.mUsers = mUsers;
this.mContext = mContext;
this.ischat = ischat;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.user_item_chat, parent, false);
return new UsersAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
User user = mUsers.get(position);
holder.username.setText(user.getName());
if (user.getImageURL().equals("default")) {
holder.profile_image.setImageResource(R.drawable.profilepicture);
} else {
Glide.with(mContext).load(user.getImageURL()).into(holder.profile_image);
}
if (ischat) {
lastMessage(user.getId(), holder.last_msg);
} else {
holder.last_msg.setVisibility(View.GONE);
}
if (ischat) {
if (user.getStatus().equals("online")) {
holder.img_on.setVisibility(View.VISIBLE);
holder.img_off.setVisibility(View.GONE);
} else {
holder.img_on.setVisibility(View.GONE);
holder.img_off.setVisibility(View.VISIBLE);
}
} else {
holder.img_on.setVisibility(View.GONE);
holder.img_off.setVisibility(View.GONE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, MessageActivity.class);
intent.putExtra("userid", user.getId());
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mUsers.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView username;
public ImageView profile_image;
private ImageView img_on;
private ImageView img_off;
private TextView last_msg;
public ViewHolder(#NonNull View itemView) {
super(itemView);
username = itemView.findViewById(R.id.chatusername);
profile_image = itemView.findViewById(R.id.profile_image);
img_on = itemView.findViewById(R.id.img_on);
img_off = itemView.findViewById(R.id.img_off);
last_msg = itemView.findViewById(R.id.last_msg);
}
}
private void lastMessage(final String userid, final TextView last_msg) {
theLastMessage = "defalut";
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Chats");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Chat chat = snapshot.getValue(Chat.class);
if (firebaseUser != null && chat != null) {
if (chat.getReceiver().equals(firebaseUser.getUid()) && chat.getSender().equals(userid) || chat.getReceiver().equals(userid) && chat.getSender().equals(firebaseUser.getUid())) {
theLastMessage = chat.getMessage();
}
}
}
switch (theLastMessage) {
case "default":
last_msg.setText("No message");
break;
default:
last_msg.setText(theLastMessage);
break;
}
theLastMessage = "default";
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
What am I missing?
befor adding new data first clear list by mUsers.clear(); as below
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
readref.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
DocumentSnapshot shot = task.getResult();
List<String> matchedid2 = new ArrayList<>();
matchedid2 = (List<String>) shot.get("matchlist");
if (matchedid2.contains(snapshot.getKey())) {
mUsers.clear();
User user = snapshot.getValue(User.class);
mUsers.add(user);
usersAdapter = new UsersAdapter(getContext(), mUsers, false);
recyclerView.setAdapter(usersAdapter);
}
}
});
}

How to get key from firebase using RecyclerView

I can get key and show in Log.d but it don't show in RecyclerView. What's wrong with it?
HistoryActivity.java it contains my recyclerView:
public class HistoryActivity extends AppCompatActivity {
FirebaseFirestore mFirestore;
FirebaseAuth firebaseAuth;
FirebaseDatabase database;
RecyclerView mHisList;
ArrayList<PreviousLst> history;
adt_rv_HisList adtRvHisList;
TextView ptName;
TextView ptPort;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
getSupportActionBar().setSubtitle("History");
Intent it = getIntent();
String patName = it.getStringExtra("nm");
String patID = it.getStringExtra("idpat");
String portNum = it.getStringExtra("pNum");
String regisDate = it.getStringExtra("rdate");
ptName = findViewById(R.id.txName);
ptPort = findViewById(R.id.portpassValue);
ptName.setText(patName);
ptPort.setText(portNum);
history = new ArrayList<>();
setupRecyclerView();
setupFireBase();
loadDataFromDatabase(portNum);
}
private void setupFireBase() {
mFirestore = FirebaseFirestore.getInstance();
firebaseAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
}
private void setupRecyclerView() {
mHisList = findViewById(R.id.rv_prev_lst);
mHisList.setHasFixedSize(true);
mHisList.setLayoutManager(new LinearLayoutManager(this));
mHisList.setAdapter(adtRvHisList);
}
public void loadDataFromDatabase(String portNum) {
if(history.size()>0)
history.clear();
DatabaseReference myRef;
DatabaseReference passref;
switch (portNum){
case "Huang-Yai0002":
String p2 = "NETEKG-Huang-Yai0002";
myRef = database.getReference("MACHINE");
passref = myRef.child(p2).child("value");
passref.addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
String keydate = postSnapshot.getKey();
Log.d(TAG, "Child are: " + keydate );
PreviousLst previousLst = new PreviousLst(keydate);
history.add(previousLst);
}
adtRvHisList = new adt_rv_HisList(HistoryActivity.this, history);
mHisList.setAdapter(adtRvHisList);
}
#Override
public void onCancelled(DatabaseError error) {
Log.w(TAG, "Failed to read value.", error.toException());
}
});
break;
case "Huang-Yai0003":
String p3 = "NETEKG-Huang-Yai0003";
myRef = database.getReference("MACHINE");
passref = myRef.child(p3).child("value");
passref.addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
String keydate = postSnapshot.getKey();
Log.d(TAG, "Child are: " + keydate );
PreviousLst previousLst = new PreviousLst(postSnapshot.getKey());
history.add(previousLst);
}
adtRvHisList = new adt_rv_HisList(HistoryActivity.this, history);
mHisList.setAdapter(adtRvHisList);
}
#Override
public void onCancelled(DatabaseError error) {
Log.w(TAG, "Failed to read value.", error.toException());
}
});
break;
default:
Log.d(TAG, "Value is: " + portNum);
Toast.makeText(getApplicationContext(),"Error...",Toast.LENGTH_LONG).show();
break;
}
}
}
adt_rv_HisList.java Adapter:
public class adt_rv_HisList extends RecyclerView.Adapter<adtrvHisListViewHolder> {
HistoryActivity historyActivity;
ArrayList<PreviousLst> history;
public adt_rv_HisList(HistoryActivity historyActivity, ArrayList<PreviousLst> history) {
this.history = history;
this.historyActivity = historyActivity;
}
#NonNull
#Override
public adtrvHisListViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(historyActivity.getBaseContext()).inflate(R.layout.hislist_item, viewGroup, false);
return new adtrvHisListViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull adtrvHisListViewHolder holder, int position) {
holder.hdate.setText(history.get(position).getHisDate());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialogView();
}
});
}
private void dialogView() {
final Dialog dia = new Dialog(historyActivity);
dia.setContentView(R.layout.dialog_ask_view);
dia.show();
Button pvgraph = (Button)dia.findViewById(R.id.bt_pvgraph);
Button pvhr = (Button)dia.findViewById(R.id.bt_pvhrate);
Button cc = (Button)dia.findViewById(R.id.btn_cancel);
cc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dia.dismiss();
}
});
pvgraph.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dia.dismiss();
Intent it = new Intent(historyActivity, ViewgraphActivity.class);
historyActivity.startActivity(it);
}
});
pvhr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dia.dismiss();
Intent it = new Intent(historyActivity, ViewHRActivity.class);
historyActivity.startActivity(it);
}
});
}
#Override
public int getItemCount() {
return 0;
}
}
adtrvHisListViewHolder.java Contains the ViewHolder :
public class adtrvHisListViewHolder extends RecyclerView.ViewHolder {
public TextView hdate;
public adtrvHisListViewHolder(View itemView) {
super(itemView);
hdate = itemView.findViewById(R.id.his_date);
}
}
PreviousLst.java is Model class for my recyclerView:
public class PreviousLst {
String HisDate;
public PreviousLst(String HisDate){
this.HisDate = HisDate;
}
public PreviousLst(){
}
public String getHisDate() {
return HisDate;
}
public void setHisDate(String hisDate) {
HisDate = hisDate;
}
}
This is my key that I get and show in Log.d
D/ContentValues: Child are: HEART RATE
D/ContentValues: Child are:LEAD 1
Child are: LEAD 2
Child are: LEAD 3
Child are: LEAD 4
Child are: LEAD 5
Child are: LEAD 6
but it don't shoe in App.
enter image description here
#Override
public int getItemCount() {
//return 0;
replace it with history.size();
}
the added lines tells the adapter how many items, the adapter has to bind the items to the recycler view. By default it is 0, means the adapter class will never call the binView method to show the items at view side

update firebase info without redrawing listview

I'm making a voting system in an android app that uses firebase as it's backend. I'm in the process of getting the user's vote status from their history, updating the view accordingly, and responding to vote touches on the buttons. The problem I'm having is that when a user clicks on the up or down vote buttons it redraws the listview, sometimes omitting two of the options, and always moving the scrolling of the view back up to the top. Can I update the data inside of a listview without completely redrawing that listview? If so, how?
MovieActivity.java
public class MovieActivity extends AppCompatActivity {
private static final String KEY_IMDB = "KEY_IMDB";
private ImageView mPosterImageView;
private TextView mTitleTextView;
private TextView mYearTextView;
private TextView mSummaryTextView;
private ListView triggerListView;
private ArrayList<Trigger> mTriggerPrefList;
private Movie mMovie;
private LinkedList<Trigger> resultList;
DatabaseReference movieDB;
DatabaseReference userDB;
DatabaseReference thisMovieDB;
DatabaseReference triggerDB;
DatabaseReference adminDB;
FirebaseAuth mFirebaseAuth;
FirebaseUser mUser;
ArrayList<Trigger> mTriggerList;
String imdbID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie);
mPosterImageView = (ImageView) findViewById(R.id.posterImageView);
mTitleTextView = (TextView) findViewById(R.id.titleTextView);
mYearTextView = (TextView) findViewById(R.id.yearTextView);
mSummaryTextView = (TextView) findViewById(R.id.summaryTextView);
triggerListView = (ListView) findViewById(R.id.triggerListView);
mFirebaseAuth = FirebaseAuth.getInstance();
mUser = mFirebaseAuth.getCurrentUser();
movieDB = FirebaseDatabase.getInstance().getReference("movies");
userDB = FirebaseDatabase.getInstance().getReference("users");
adminDB = FirebaseDatabase.getInstance().getReference("admin");
Intent intent = getIntent();
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
imdbID = intent.getStringExtra("ID_KEY");
final String keyTitle = intent.getStringExtra("TITLE_KEY");
final String keyYear = intent.getStringExtra("YEAR_KEY");
final String keyPoster = intent.getStringExtra("POSTER_KEY");
try {
getMovieDetails(imdbID, new Runnable() {
#Override
public void run() {
CheckForTriggerValues(new Runnable() {
#Override
public void run() {
populateTriggers(new Runnable() {
#Override
public void run() {
populatePrefs(new Runnable() {
#Override
public void run() {
reOrderList(new Runnable() {
#Override
public void run() {
Movie passMovie = new Movie();
passMovie.setImdbID(imdbID);
passMovie.setPosterURL(keyPoster);
passMovie.setYear(keyYear);
passMovie.setTitle(keyTitle);
TriggerAdapter adapter = new TriggerAdapter(MovieActivity.this, resultList, passMovie, imdbID );
triggerListView.setAdapter(adapter);
}
});
}
});
}
});
}
});
}
});
} catch (JSONException e) {
e.printStackTrace();
}
thisMovieDB = movieDB.child(imdbID);
triggerDB = thisMovieDB.child("Triggers");
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY_IMDB, imdbID);
}
#Override
protected void onStart() {
super.onStart();
Intent intent = getIntent();
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
imdbID = intent.getStringExtra("ID_KEY");
}
private void getMovieDetails(String imdbID, Runnable runnable) throws JSONException {
String apiKey = OMITTED;
String theURL = "http://www.omdbapi.com/?i=" + imdbID + "&apikey=" + apiKey;
final OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(theURL).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
final String jsonData = response.body().string();
if (response.isSuccessful()) {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
Movie movie = parseMovieDetails(jsonData);
updateMovieUI(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
});
runnable.run();
}
private Movie parseMovieDetails(String jsonData) throws JSONException {
JSONObject jsonObject = new JSONObject(jsonData);
Movie movie = new Movie();
movie.setPosterURL(jsonObject.getString("Poster"));
movie.setTitle(jsonObject.getString("Title"));
movie.setYear(jsonObject.getString("Year"));
movie.setSummary(jsonObject.getString("Plot"));
mMovie = movie;
return movie;
}
private void updateMovieUI(Movie movie){
Context mContext = getApplicationContext();
mSummaryTextView.setText(movie.getSummary());
mYearTextView.setText(movie.getYear());
mTitleTextView.setText(movie.getTitle());
Picasso.with(mContext).load(movie.getPosterURL()).into(mPosterImageView);
}
private void populatePrefs(final Runnable runnable) {
mTriggerPrefList = new ArrayList<>();
mFirebaseAuth = FirebaseAuth.getInstance();
mUser = mFirebaseAuth.getCurrentUser();
movieDB = FirebaseDatabase.getInstance().getReference("movies");
userDB = FirebaseDatabase.getInstance().getReference("users");
adminDB = FirebaseDatabase.getInstance().getReference("admin");
thisMovieDB = movieDB.child(imdbID);
thisMovieDB.child("Details").setValue(mMovie);
triggerDB = thisMovieDB.child("Triggers");
userDB.child(mUser.getUid()).child("preferences").child("trigger").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot triggerSnapshot : dataSnapshot.getChildren()) {
String name = String.valueOf(triggerSnapshot.child("triggerName").getValue());
Trigger trigger = new Trigger();
trigger.setTriggerName(name);
trigger.setTriggerVotesTotal(0);
trigger.setTriggerVotesYes(0);
mTriggerPrefList.add(trigger);
}
Intent intent = getIntent();
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
imdbID = intent.getStringExtra("ID_KEY");
runnable.run();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void populateTriggers(final Runnable runnable) {
mTriggerList = new ArrayList<>();
mFirebaseAuth = FirebaseAuth.getInstance();
mUser = mFirebaseAuth.getCurrentUser();
movieDB = FirebaseDatabase.getInstance().getReference("movies");
userDB = FirebaseDatabase.getInstance().getReference("users");
adminDB = FirebaseDatabase.getInstance().getReference("admin");
thisMovieDB = movieDB.child(imdbID);
thisMovieDB.child("Details").setValue(mMovie);
triggerDB = thisMovieDB.child("Triggers");
triggerDB.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mTriggerList.clear();
for (DataSnapshot triggerSnapshot : dataSnapshot.getChildren()) {
Trigger trigger = triggerSnapshot.getValue(Trigger.class);
mTriggerList.add(trigger);
}
runnable.run();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void reOrderList(Runnable runnable) {
resultList = new LinkedList<>();
for (Trigger triggerA : mTriggerList) {
boolean found = false;
for (Trigger triggerB : mTriggerPrefList) {
if (triggerB.getTriggerName().equals(triggerA.getTriggerName())) {
found = true;
}
}
if (found) {
resultList.add(triggerA);
}
}
mTriggerList.removeAll(resultList);
resultList.addAll(mTriggerList);
runnable.run();
}
private void CheckForTriggerValues(final Runnable runnable) {
adminDB.child("triggerList").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
GenericTypeIndicator<Map<String, Object>> genericTypeIndicator = new GenericTypeIndicator<Map<String, Object>>() {};
final Map<String, Object> triggerList = dataSnapshot.getValue(genericTypeIndicator);
triggerDB.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (Map.Entry<String, Object> entry : triggerList.entrySet())
{
if (dataSnapshot.hasChild(entry.getKey())){
}
else {
Trigger trigger1 = new Trigger(entry.getKey(), 0, 0);
triggerDB.child(trigger1.getTriggerName()).setValue(trigger1);
}
}
runnable.run();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
int isTrue(Boolean boolDown, Boolean boolUp) {
int x = 0;
if (boolUp) {
x = 1;
}
if (boolDown) {
x = -1;
}
return x;
}
}
TriggerAdapter.java
package me.paxana.cwnet.Adapters;
import android.app.Activity;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Typeface;
import android.os.Build;
import android.provider.ContactsContract;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import com.andremion.counterfab.CounterFab;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.MutableData;
import com.google.firebase.database.Transaction;
import com.google.firebase.database.ValueEventListener;
import java.util.List;
import me.paxana.cwnet.Model.Movie;
import me.paxana.cwnet.Model.Trigger;
import me.paxana.cwnet.R;
import me.paxana.cwnet.ui.AdminPanelActivity;
import me.paxana.cwnet.ui.MovieActivity;
/**
* Created by paxie on 10/11/17.
*/
public class TriggerAdapter extends BaseAdapter {
private Context mContext;
private List<Trigger> mTriggers;
private Movie mMovie;
private String mImdbID;
private String mTitle;
private String mYear;
private String mPosterURL;
private DatabaseReference movieDB;
private DatabaseReference userDB;
private DatabaseReference triggerDB;
private DatabaseReference adminDB;
public TriggerAdapter(Context context, List<Trigger> triggerList, Movie movie, String imdbID){
mContext = context;
this.mTriggers = triggerList;
mMovie = movie;
mImdbID = imdbID;
mTitle = movie.getTitle();
mYear = movie.getYear();
mPosterURL = movie.getPosterURL();
};
public TriggerAdapter(Context context, List<Trigger> triggerList) {
mContext = context;
this.mTriggers = triggerList;
}
#Override
public int getCount() {
return this.mTriggers.size();
}
#Override
public Object getItem(int i) {
return mTriggers.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, final ViewGroup viewGroup) {
final ViewHolder holder;
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser user = firebaseAuth.getCurrentUser();
movieDB = FirebaseDatabase.getInstance().getReference("movies");
userDB = FirebaseDatabase.getInstance().getReference("users");
adminDB = FirebaseDatabase.getInstance().getReference("admin");
final String mUserId = user.getUid();
final Trigger trigger = mTriggers.get(i);
if (view == null) {
view = LayoutInflater.from(mContext).inflate(R.layout.trigger_list_item, null);
holder = new ViewHolder();
holder.triggerName = view.findViewById(R.id.triggerName);
holder.upButton = view.findViewById(R.id.mTriggerButtonUp);
holder.downButton = view.findViewById(R.id.mTriggerButtonDown);
holder.total = view.findViewById(R.id.triggerCounter);
view.setTag(holder);
}
else {
holder = (ViewHolder) view.getTag();
}
holder.triggerName.setText(trigger.getTriggerName());
if (mContext instanceof AdminPanelActivity) {
holder.upButton.setVisibility(View.INVISIBLE);
holder.downButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
adminDB.child("triggerList").child(trigger.getTriggerName()).removeValue();
int i = mTriggers.indexOf(trigger);
mTriggers.remove(i);
TriggerAdapter.this.notifyDataSetChanged();
}
});
}
if (mContext instanceof MovieActivity) {
userDB.child(mUserId).child("changes").child(mImdbID).child("triggers").child(trigger.getTriggerName()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
int userVote = dataSnapshot.getValue(Integer.class);
if (userVote == 0) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
holder.upButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.colorAccent, null));
holder.downButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.colorAccent, null));
}
else {
holder.upButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.colorAccent));
holder.downButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.colorAccent));
}
neitherButtonIsSelected(holder, trigger, mUserId);
}
if (userVote == 1) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
holder.upButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.votebuttons, null));
holder.downButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.colorAccent, null));
}
else {
holder.upButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.votebuttons));
holder.downButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.colorAccent));
}
upButtonIsSelected(holder, trigger, mUserId);
}
if (userVote == -1) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
holder.upButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.colorAccent, null));
holder.downButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.votebuttons, null));
}
else {
holder.upButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.colorAccent));
holder.downButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.votebuttons));
}
downButtonIsSelected(holder, trigger, mUserId);
}
}
else {
userDB.child(mUserId).child("changes").child(mImdbID).child("triggers").child(trigger.getTriggerName()).setValue(0);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
holder.total.setText(String.valueOf(trigger.getTriggerVotesYes()));
holder.upButton.setCount(trigger.getTriggerVotesYes());
if (trigger.getTriggerVotesTotal() != 0){
holder.total.setText(String.valueOf(trigger.getTriggerVotesTotal()));
int downButtonCount = (trigger.getTriggerVotesTotal() - trigger.getTriggerVotesYes());
holder.downButton.setCount(downButtonCount);
}
return view;
}
private static class ViewHolder {
TextView triggerName;
CounterFab upButton;
CounterFab downButton;
TextView total;
}
private void neitherButtonIsSelected(final ViewHolder holder, final Trigger trigger, final String mUserId) {
holder.upButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
triggerDB = movieDB.child(mImdbID).child("Triggers").child(trigger.getTriggerName());
triggerDB.child("triggerVotesYes").runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
int count = mutableData.getValue(Integer.class);
mutableData.setValue(count + 1);
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
}
});
triggerDB.child("triggerVotesTotal").runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
int count = mutableData.getValue(Integer.class);
mutableData.setValue(count + 1);
userDB.child(mUserId).child("changes").child(mImdbID).child("triggers").child(trigger.getTriggerName()).setValue(1);
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
}
});
userDB.child(mUserId).child("changes").child(mImdbID).child("triggers").child(trigger.getTriggerName()).setValue(1);
}
});
holder.downButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
triggerDB.child("triggerVotesTotal").runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
int count = mutableData.getValue(Integer.class);
mutableData.setValue(count + 1);
userDB.child(mUserId).child("changes").child(mImdbID).child("triggers").child(trigger.getTriggerName()).setValue(1);
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
}
});
userDB.child(mUserId).child("changes").child(mImdbID).child("triggers").child(trigger.getTriggerName()).setValue(1);
}
});
}
private void upButtonIsSelected(final ViewHolder holder, final Trigger trigger, final String mUserId) {
holder.upButton.setOnClickListener(null);
holder.downButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
triggerDB = movieDB.child(mImdbID).child("Triggers").child(trigger.getTriggerName());
triggerDB.child("triggerVotesYes").runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
int count = mutableData.getValue(Integer.class);
mutableData.setValue(count - 1);
userDB.child(mUserId).child("changes").child(mImdbID).child("triggers").child(trigger.getTriggerName()).setValue(-1);
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
holder.downButton.getBackground().setAlpha(127);
}
});
}
});
}
private void downButtonIsSelected(final ViewHolder holder, final Trigger trigger, final String mUserId) {
holder.downButton.setOnClickListener(null);
holder.upButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
triggerDB = movieDB.child(mImdbID).child("Triggers").child(trigger.getTriggerName());
triggerDB.child("triggerVotesYes").runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
int count = mutableData.getValue(Integer.class);
mutableData.setValue(count + 1);
userDB.child(mUserId).child("changes").child(mImdbID).child("triggers").child(trigger.getTriggerName()).setValue(1);
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
holder.downButton.getBackground().setAlpha(127);
}
});
}
});
}
}
Following things might help you.
Use android:stackFromBottom="true" in the xml of your ListView
Instead of using mTriggerList.clear(); when updating, do not clear it and add the item to list only if the item does not already exist in the list.
Eg.
for(Trigger trigger: triggerSnapShot...){
if (!mTriggerList.contains(trigger)){
mTriggerList.add(trigger);
}
}
You may need to override the equals method in the Trigger class in order to make the method contains work properly.

Categories