Firebase Children Count to listview - android

Good Day,
I'm Trying to count the number of children based on votes.
This is my Firebase structure.
Candidate Table
and
Votes table
I successfully recovered the candidates from candidates table to listview, but I can't recover the number of votes they got on the votes table.
This is my xml for the listview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/count_ssc_president_last_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="40sp"
android:textColor="#color/colorBlack"/>
<TextView
android:id="#+id/count_ssc_president_first_middle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="20sp"/>
<TextView
android:id="#+id/count_ssc_president_partylist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/count_ssc_president_count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="TextView"
android:textSize="20sp"
android:textColor="#color/colorBlack"/>
</LinearLayout>
This is my xml for the Main java class
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Voter_SSC_President">
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="14dp"
android:text="#string/choose_ssc_president"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView2" />
<ListView
android:id="#+id/listCountSSCPresident"
android:layout_width="309dp"
android:layout_height="338dp"
android:layout_marginBottom="32dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="34dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView4" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="277dp"
android:layout_height="111dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toTopOf="#+id/textView4"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_ssc_logo" />
</android.support.constraint.ConstraintLayout>
This is my adapter
private Activity context;
private List<SSC_Presidents> CountSSC_PresidentsList;
DatabaseReference userReference;
long num;
private LayoutInflater inflater;
public CountSSCPresLists(Activity context, List<SSC_Presidents> CountSSC_PresidentsList )
{
super(context, R.layout.listview_count_ssc_president, CountSSC_PresidentsList);
this.context = context;
this.CountSSC_PresidentsList = CountSSC_PresidentsList;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.listview_count_ssc_president, null, false);
TextView textViewLast_name = (TextView) listViewItem.findViewById(R.id.count_ssc_president_last_name);
TextView textViewFirst_middle_name = (TextView) listViewItem.findViewById(R.id.count_ssc_president_first_middle);
TextView textViewPartylist = (TextView) listViewItem.findViewById(R.id.count_ssc_president_partylist);
TextView textViewCount = (TextView) listViewItem.findViewById(R.id.count_ssc_president_count);
SSC_Presidents sscPresidents = CountSSC_PresidentsList.get(position);
/*
userReference = FirebaseDatabase.getInstance().getReference("vote");
userReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
num = dataSnapshot.getChildrenCount();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
textViewCount.setText((int) num);*/
textViewLast_name.setText(sscPresidents.getLast_name());
textViewFirst_middle_name.setText(sscPresidents.getFirst_name()+", "+sscPresidents.getMiddle_name());
textViewPartylist.setText(sscPresidents.getPartylist_id());
return listViewItem;
The block-comment is my try to generate the vote number based on the candidate-id
This is my main java class
String stud_no;
DatabaseReference databaseReferenceCountSSCPres;
ListView listViewCountSSCPresident;
List<SSC_Presidents> sscCountPresList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin__count__ssc__president);
databaseReferenceCountSSCPres = FirebaseDatabase.getInstance().getReference("candidate");
stud_no = LoginScreen.TBPstud_no1();
listViewCountSSCPresident = findViewById(R.id.listCountSSCPresident);
sscCountPresList = new ArrayList<>();
}
#Override
protected void onStart() {
super.onStart();
Query CountSSCPresident = databaseReferenceCountSSCPres.orderByChild("council_id_position_id_school_year").equalTo("SSC_PRES_201819");
CountSSCPresident.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
sscCountPresList.clear();
for (DataSnapshot CountSSCPresSnapshot : dataSnapshot.getChildren())
{
SSC_Presidents CountSSCPres = CountSSCPresSnapshot.getValue(SSC_Presidents.class);
sscCountPresList.add(CountSSCPres);
}
CountSSCPresLists adapter = new CountSSCPresLists(Admin_Count_SSC_President.this, sscCountPresList);
listViewCountSSCPresident.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
This is the result
Result
I want to put the count in the TextView in the Result.
Thank you.
PS. When I remove the block comment on the adapter the screen for the result crashes.
EDIT:
The suggestion worked but only on the last candidate.
I also used query now.
userReference = FirebaseDatabase.getInstance().getReference("vote");
Query CountSSCPresident = userReference.orderByChild("candidate_id").equalTo(sscPresidents.getCandidate_id());
CountSSCPresident.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
num = dataSnapshot.getChildrenCount();
textViewCount.setText(String.valueOf((int)num));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The result

textViewCount.setText((int) num);
You need to cast num to a string. Try this:
textViewCount.setText(String.valueOf((int)num));
EDIT: Also place it inside the listener:
userReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
num = dataSnapshot.getChildrenCount();
textViewCount.setText(String.valueOf((int)num));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Related

Recyclerview not call any Adapter method: onCreateViewHolder, onBindViewHolder

Here are my codes for MyAdapter, ActivityMain, MinActivity, and User
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
Context context;
ArrayList<User> list;
public MyAdapter(Context context, ArrayList<User> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.item, parent, false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
// here is the problem that I don't know how to fix][1]
// I'm tryin to pass data from firebase to Recyclerview
// error I'm getting here is:
// [Cannot resolve method 'getFirstName' in 'User'
// Cannot resolve method 'getLastName' in 'User'
// Cannot resolve method 'getAge' in 'User']
User user = list.get(position);
holder.FirstName.setText(user.getFirstName());
holder.LastName.setText(user.getLastName());
holder.Age.setText(user.getAge());
}
#Override
public int getItemCount() {
return list.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView FirstName, LastName, Age;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
FirstName = itemView.findViewById(R.id.tvFirstName);
LastName = itemView.findViewById(R.id.tvLastName);
Age = itemView.findViewById(R.id.tvAge);
}
}
}
This is MainActivity code
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
DatabaseReference database;
MyAdapter myAdapter;
ArrayList<User> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_Main);
recyclerView = findViewById(R.id.userList);
database = FirebaseDatabase.getInstance().getReference("User");
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<>();
myAdapter = new MyAdapter(this,list);
recyclerView.setAdapter(myAdapter);
database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
User user = dataSnapshot.getValue(User.class);
list.add(user);
}
myAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
This is User codes which I generated with getter
public class User {
String FirstName, LastName, Age;
public String getFirstName() {
return FirstName;
}
public String getLastName() {
return LastName;
}
public String getAge() {
return Age;
}
{
}
}
This is my layout file
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardElevation="8dp"
app:cardCornerRadius="8dp"
android:layout_margin="16dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="First Name :"
android:textColor="#color/black"
android:textSize="26sp"
android:textStyle="bold"/>
<TextView
android:id="#+id/tvFirstName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:text="Arya"
android:textColor="#color/black"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/last_name"
android:textColor="#color/black"
android:textSize="26sp"
android:textStyle="bold"/>
<TextView
android:id="#+id/tvLastName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:text="#string/stark"
android:textColor="#color/black"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/age"
android:textColor="#color/black"
android:textSize="26sp"
android:textStyle="bold"/>
<TextView
android:id="#+id/tvAge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:text="18"
android:textColor="#color/black"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
When I hit RUN it gives me this error:
I'm new to coding.
you can change your code like this
holder.FirstName.setText(list.getFirstName().get(position));
holder.LastName.setText(list.getLastName().get(position));
holder.Age.setText(list.getAge().get(position);
and you should change this code position
myAdapter = new MyAdapter(this,list);
recyclerView.setAdapter(myAdapter);
into under this code
database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
User user = dataSnapshot.getValue(User.class);
list.add(user);
}
myAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
hope it can solve your problem :)

Is there any way to create a preview of url in android studio?

I have an app which loads users profile URls by firebase recycler adapter. I am wondering how to create preview links just like when we share a link in whatsapp and a preview is generated. The preview will contain an image, a header and small description. Thanks in advance. Below is my code
DashboardActivity
fAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
dRef = FirebaseDatabase.getInstance().getReference("Users");
// This will display the click counts for current online user
user = FirebaseAuth.getInstance().getCurrentUser();
UID = user.getUid();
dRef.child(UID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
remainingClicks = String.valueOf(snapshot.child("clicksRemain").getValue(Integer.class));
showGigCount = String.valueOf(snapshot.child("showGigCount").getValue(Integer.class));
clicks.setText(remainingClicks);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
recyclerView = findViewById(R.id.dashboardRCV);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
LoadData();
}
private void LoadData() {
options = new FirebaseRecyclerOptions.Builder<ModelClass>()
.setQuery(dRef, ModelClass.class)
.build();
adapter = new FirebaseRecyclerAdapter<ModelClass, MyViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull MyViewHolder holder, int position, #NonNull ModelClass model) {
//This will hide the gig if its showGigCount becomes 0
Query query = dRef.orderByChild("showGigCount").equalTo(0);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
holder.geglink.setVisibility(View.GONE);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
};
query.addListenerForSingleValueEvent(valueEventListener);
if (finalClicksCount == 0){
holder.geglink.setText(model.getGig());
}else if (dRef.child("showGigCount").equals(0)){
holder.geglink.setVisibility(View.GONE);
}else{
holder.geglink.setText(model.getGig());
}
holder.geglink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(model.getGig()));
startActivity(browserIntent);
finalClicksCount = Integer.parseInt(remainingClicks);
remaingGigShow = Integer.parseInt(showGigCount);
if (finalClicksCount >= 1) {
finalClicksCount--;
remaingGigShow ++;
clicks.setText(String.valueOf(finalClicksCount));
UserClicksCounts();
UserShowGigCounts();
} else if (finalClicksCount == 0){
zeroClicks.setVisibility(View.VISIBLE);
}
}
});
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_layout, parent, false);
return new MyViewHolder(view);
}
};
adapter.startListening();
recyclerView.setAdapter(adapter);
Single Row xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="5dp"
app:cardCornerRadius="5dp"
app:cardUseCompatPadding="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/rcvGigLink"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="#font/montserrat"
android:gravity="center_horizontal"
android:text="https://www.fiverr.com/share/NwPBXR"
android:textAlignment="center"
android:textColor="#color/black"
android:textSize="14sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/rcvAbout" />
<TextView
android:id="#+id/rcvName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="#font/montserrat"
android:gravity="center_horizontal"
android:text="Zeeshan"
android:textAlignment="center"
android:textColor="#color/black"
android:textSize="14sp"
android:visibility="gone"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/rcvAbout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="#font/montserrat"
android:gravity="center_horizontal"
android:text="I am a user"
android:textAlignment="center"
android:textColor="#color/black"
android:textSize="14sp"
android:visibility="gone"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/rcvName" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
You can use this
Link Preview Library
Just use the view directly
<io.github.ponnamkarthik.richlinkpreview.RichLinkView
android:id="#+id/richLinkView"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</io.github.ponnamkarthik.richlinkpreview.RichLinkView>

How to get the UID of a user and set a value to from my FireRecyclerAdapter with a button?

I'm trying to set a value of '1' or '0' to my list of users on a node named 'Blocked Users' in Firebase. However, I'm only retrieving the UID of the account that is logged in on the app I'm currently using instead of the ones on the list:
{
"Blocked Users" : {
"HnREoOYynjVfPlTQKCt5744SzAt1" : 1
},
"User Location" : {
"latitude" :
"longitude" :
},
"Users" : {
"RCX2HZXIwlSmMHFgDytf1DgZBgi2" : {
"Alert Level" :
"Emergency Type" :
"address" : ,
"emergencyNum" :
"name" :
"phoneNum" :
}
}
}
I'm trying to get the UID in 'Users', the ones on the RecyclerView, not the current user in the app. Here's how I'm doing so far:
My adapter:
#Override
protected void onBindViewHolder(#NonNull myViewHolder holder, int position, #NonNull MainData model) {
holder.name.setText(model.getName());
holder.address.setText(model.getAddress());
holder.phoneNum.setText(model.getPhoneNum());
}
String uid = FirebaseAuth.getInstance().getUid();
Context context;
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item,parent,false);
return new myViewHolder(view);
}
public MainAdapter(#NonNull FirebaseRecyclerOptions<MainData> mainDataFirebaseRecyclerOptions) {
super(mainDataFirebaseRecyclerOptions);
}
class myViewHolder extends RecyclerView.ViewHolder {
CircleImageView image;
TextView name, address, phoneNum;
ToggleButton toggleButton;
public myViewHolder(#NonNull View itemView) {
super(itemView);
image = (CircleImageView) itemView.findViewById(R.id.img1);
name = (TextView) itemView.findViewById(R.id.nameText);
address = (TextView) itemView.findViewById(R.id.addressText);
phoneNum = (TextView) itemView.findViewById(R.id.numberText);
itemView.findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
blockUser();
}
});
itemView.findViewById(R.id.button4).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
unblockUser();
}
});
}
}
private void blockUser() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Blocked Users").child(uid);
reference.setValue(1)
.addOnCompleteListener((OnCompleteListener<Void>) unused -> {
Toast.makeText(context, "User Blocked", Toast.LENGTH_SHORT).show();
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(context, "Failed"+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
private void unblockUser(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Blocked Users").child(uid);
reference.setValue(0)
.addOnCompleteListener((OnCompleteListener<Void>) unused -> {
Toast.makeText(context, "User Unblocked", Toast.LENGTH_SHORT).show();
})
.addOnFailureListener(e -> Toast.makeText(context, "Failed"+e.getMessage(),Toast.LENGTH_SHORT).show());
}
}
RecyclerView Activity:
public class Report extends AppCompatActivity {
RecyclerView recyclerView;
MainAdapter mainAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_report);
recyclerView = (RecyclerView) findViewById(R.id.userList);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
FirebaseRecyclerOptions<MainData> mainDataFirebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<MainData>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("Users"), MainData.class)
.build();
mainAdapter = new MainAdapter(mainDataFirebaseRecyclerOptions);
recyclerView.setAdapter(mainAdapter);
}
#Override
protected void onStart() {
super.onStart();
mainAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
mainAdapter.stopListening();
}
The layout for the RecyclerView:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardCornerRadius="6dp"
android:layout_margin="16dp"
android:elevation="6dp"
app:cardUseCompatPadding="true">
<RelativeLayout
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:padding="15dp">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/img1"
android:layout_width="80dp"
android:layout_height="80dp"
android:src="#mipmap/ic_launcher"
app:civ_border_color="#FF000000"
app:civ_border_width="2dp" />
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="#+id/nameText"
android:text="Name"
android:textStyle="bold"
android:textSize="15sp"
android:textColor="#000"
android:layout_toRightOf="#+id/img1"
android:layout_marginLeft="10dp"
/>
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="#+id/addressText"
android:text="Address"
android:textStyle="bold"
android:textSize="15sp"
android:textColor="#000"
android:layout_toRightOf="#+id/img1"
android:layout_marginLeft="10dp"
android:layout_below="#+id/nameText"
/>
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="#+id/numberText"
android:text="Emergency Number"
android:textStyle="bold"
android:textSize="15sp"
android:textColor="#000"
android:layout_toRightOf="#+id/img1"
android:layout_marginLeft="10dp"
android:layout_below="#+id/addressText"
/>
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="-76dp"
android:layout_toRightOf="#+id/numberText"
android:backgroundTint="#color/design_default_color_error"
android:text="Revoke Access"
android:textSize="10sp" />
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button3"
android:layout_marginLeft="-76dp"
android:layout_marginTop="0dp"
android:layout_toRightOf="#+id/numberText"
android:backgroundTint="#android:color/holo_green_dark"
android:text="Grant Access"
android:textSize="10sp" />
</RelativeLayout>
I want to know if what I am doing so far is the correct way of making this possible or not.

Android setVisibility does not work on some logic

Just a little introduction of what I am doing.
I am granting different functionality based on the account type a user has sign in with.
The user's account type will be retrieved via Firebase Reference from Firebase Database. If you look at this image, there's the arrow indicated. That is where the account type will be displayed but to consider the UI, I have set the visibility of the text view to be "gone". I have validated that the database reference codes are working as when I set the visibility of the text view to be visible, and then I run the app, the text view will change accordingly to be either Administrator or Local User.
The problem lies on my setVisibility 'if else' logic. It does not work accordingy. Attached are the list of scenarios I have tested and the outcomes of it.
I have tried adding the visibility to 'gone' on my pencil icon, and use VISIBILE/INVISIBLE/GONE without the View infront of it (like what many have said as their solution on several similar posts), but when I tried that, the icon is invisible for all 8 scenarios.
As such, I am not sure what else I should do to overcome this. Any help is greatly appreciated.
Update #1: Added codes as requested
class SearchViewHolder extends RecyclerView.ViewHolder {
public TextView keyword, description, acronym, relatedkeyword1,
relatedkeyword2, relatedkeyword3, tv_rules_read_more;
public ImageView iv_rules;
public SearchViewHolder(#NonNull View itemView) {
super(itemView);
//knowledge feature
keyword = itemView.findViewById(R.id.keyword);
acronym = itemView.findViewById(R.id.acronym);
tv_rules_read_more = itemView.findViewById(R.id.tv_rules_read_more);
iv_rules = itemView.findViewById(R.id.iv_rules);
}
}
public class SearchAdapter extends RecyclerView.Adapter<SearchViewHolder>
implements SectionIndexer {
// private Context context;
private List<Knowledge> knowledge;
private ArrayList<Integer> mSectionPositions;
Activity activity;
String positionUpdated;
private FirebaseAuth firebaseAuth;
private FirebaseDatabase firebaseDatabase;
public SearchAdapter(Activity activity, List<Knowledge> knowledge, String
positionUpdated) {
//this.context = context;
this.knowledge = knowledge;
this.activity = activity;
this.positionUpdated = positionUpdated;
}
#NonNull
#Override
public SearchViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int
viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View itemView = inflater.inflate(R.layout.layout_item, parent, false);
return new SearchViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull SearchViewHolder holder, final int
position) {
holder.keyword.setText(knowledge.get(position).getKeyword());
holder.acronym.setText(knowledge.get(position).getAcronym());
holder.tv_rules_read_more.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog(position);
}
});
if (positionUpdated != null && !positionUpdated.equals("")) {
showDialog(Integer.parseInt(positionUpdated));
positionUpdated = "";
}
}
public void showDialog(final int position) {
try {
final Dialog dialog = new Dialog(activity);
dialog.setContentView(R.layout.dialog_layout_item_rules);
dialog.setCancelable(false);
final TextView acctype, keyword1, description1, acronym1,
relatedkeyword4, relatedkeyword5, relatedkeyword6;
//final TextView keyword1, description1, acronym1,
relatedkeyword4, relatedkeyword5, relatedkeyword6;
ImageView iv_rules, iv_close_dialog, iv_edit_dialog;
//rules feature
acctype = dialog.findViewById(R.id.tvAccType);
keyword1 = dialog.findViewById(R.id.keyword);
acronym1 = dialog.findViewById(R.id.acronym);
description1 = dialog.findViewById(R.id.description);
relatedkeyword4 = dialog.findViewById(R.id.relatedKeyword1);
relatedkeyword5 = dialog.findViewById(R.id.relatedKeyword2);
relatedkeyword6 = dialog.findViewById(R.id.relatedKeyword3);
iv_rules = dialog.findViewById(R.id.iv_rules);
iv_close_dialog = dialog.findViewById(R.id.iv_close_dialog);
iv_edit_dialog = dialog.findViewById(R.id.iv_edit_dialog);
/////////
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference databaseReference =
firebaseDatabase.getReference(firebaseAuth.getUid());
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
UserProfile userProfile =
dataSnapshot.getValue(UserProfile.class);
acctype.setText(userProfile.getUserDepartment());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
}
});
if (acctype.getText().toString().equals("Administrator")){
iv_edit_dialog.setVisibility(View.VISIBLE);
}else {
iv_edit_dialog.setVisibility(View.INVISIBLE);
}
////////
keyword1.setText(knowledge.get(position).getKeyword());
description1.setText(knowledge.get(position).getDescription());
acronym1.setText(knowledge.get(position).getAcronym());
relatedkeyword4.setText(knowledge.get(position).getRelatedkeyword1());
relatedkeyword5.setText(knowledge.get(position).getRelatedkeyword2());
relatedkeyword6.setText(knowledge.get(position).getRelatedkeyword3());
byte[] bytesImage = knowledge.get(position).getImage();
if (bytesImage != null && bytesImage.length > 0) {
Bitmap bitmap = BitmapFactory.decodeByteArray(bytesImage, 0,
bytesImage.length);
iv_rules.setImageBitmap(bitmap);
iv_rules.setVisibility(View.VISIBLE);
} else {
iv_rules.setVisibility(View.GONE);
}
dialog.show();
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
WindowManager.LayoutParams layoutParams = new
WindowManager.LayoutParams();
Window window = dialog.getWindow();
layoutParams.copyFrom(window.getAttributes());
layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
window.setAttributes(layoutParams);
iv_close_dialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.cancel();
}
});
iv_edit_dialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(activity,
AddNewKnowledgeActivity.class);
intent.putExtra("id",
String.valueOf(knowledge.get(position).getId()));
intent.putExtra("position", String.valueOf(position));
intent.putExtra("call_type", "update_rule");
intent.putExtra("title",
knowledge.get(position).getKeyword());
intent.putExtra("code",
knowledge.get(position).getAcronym());
intent.putExtra("description",
knowledge.get(position).getDescription());
intent.putExtra("keyword1",
knowledge.get(position).getRelatedkeyword1());
intent.putExtra("keyword2",
knowledge.get(position).getRelatedkeyword2());
intent.putExtra("keyword3",
knowledge.get(position).getRelatedkeyword3());
intent.putExtra("bytesImage",
knowledge.get(position).getImage());
dialog.cancel();
activity.startActivityForResult(intent, 101);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return knowledge.size();
}
#Override
public int getSectionForPosition(int position) {
return 0;
}
#Override
public Object[] getSections() {
List<String> sections = new ArrayList<>(26);
mSectionPositions = new ArrayList<>(26);
for (int i = 0, size = knowledge.size(); i < size; i++) {
String section =
String.valueOf(knowledge.get(i).getKeyword().charAt(0)).toUpperCase();
if (!sections.contains(section)) {
sections.add(section);
mSectionPositions.add(i);
}
}
return sections.toArray(new String[0]);
}
#Override
public int getPositionForSection(int sectionIndex) {
return mSectionPositions.get(sectionIndex);
}
}
Update 2: Added XML file
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
app:cardBackgroundColor="#f5f0f0"
app:cardCornerRadius="10dp"
app:cardElevation="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="vertical">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/iv_rules"
android:layout_width="200dp"
android:layout_height="120dp"
android:layout_centerHorizontal="true"
android:src="#color/deeppurpleColor"
android:visibility="gone" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:orientation="vertical">
<ImageView
android:id="#+id/iv_edit_dialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/_5sdp"
android:background="#android:drawable/ic_menu_edit"
android:backgroundTint="#android:color/black"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:orientation="vertical">
<ImageView
android:id="#+id/iv_close_dialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/_5sdp"
android:layout_alignParentRight="true"
android:background="#android:drawable/ic_menu_close_clear_cancel"
android:backgroundTint="#android:color/black" />
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp">
<TextView
android:id="#+id/tvAccType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Account Type"
android:visibility="gone"/>
<TextView
android:id="#+id/keyword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:gravity="center_vertical|start"
android:text="Baggage Management Interface Device (BMID)
Testing 123"
android:textAllCaps="true"
android:textColor="#000000"
android:textSize="15dp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/codeHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:gravity="center_vertical|start"
android:text="Code:"
android:textColor="#a8000000"
android:textSize="13dp"
android:textStyle="bold" />
<TextView
android:id="#+id/acronym"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:gravity="center_vertical|start"
android:text="GST"
android:textColor="#a8000000"
android:textSize="13dp"
android:textStyle="italic" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/ruleHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:gravity="center_vertical|start"
android:text="Desc:"
android:textColor="#a8000000"
android:textSize="13dp"
android:textStyle="bold" />
<TextView
android:id="#+id/description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:gravity="center_vertical|start"
android:scrollbars="vertical"
android:text="If none are set then 'GST' is set to NULL"
android:textColor="#a8000000"
android:textSize="13dp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/relatedKeyword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:gravity="center_vertical|start"
android:text="Related Keyword:"
android:textColor="#a8000000"
android:textSize="12sp"
android:textStyle="bold" />
<TextView
android:id="#+id/relatedKeyword1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:clickable="true"
android:text="Keyword 1,"
android:textColor="#a8000000"
android:textSize="12sp" />
<TextView
android:id="#+id/relatedKeyword2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:clickable="true"
android:text="Keyword 2,"
android:textColor="#a8000000"
android:textSize="12sp" />
<TextView
android:id="#+id/relatedKeyword3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:clickable="true"
android:text="Keyword 3"
android:textColor="#a8000000"
android:textSize="12sp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
Problem is solved by placing the if/else logic inside onDataChange method!
The logic did not work accordingly as my if/else logic were placed outside of the loop. The logic should work while Firebase is retrieving then displaying the values.
As such, instead of these:
DatabaseReference databaseReference =
firebaseDatabase.getReference(firebaseAuth.getUid());
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
UserProfile userProfile =
dataSnapshot.getValue(UserProfile.class);
acctype.setText(userProfile.getUserDepartment());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
}
});
//note: these are outside of the loop at first
if (acctype.getText().toString().equals("Administrator")){
iv_edit_dialog.setVisibility(View.VISIBLE);
}else {
iv_edit_dialog.setVisibility(View.INVISIBLE);
}
It should be like this instead:
DatabaseReference databaseReference = firebaseDatabase.getReference(firebaseAuth.getUid());
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
UserProfile userProfile = dataSnapshot.getValue(UserProfile.class);
acctype.setText(userProfile.getUserDepartment());
//granting different functionality based on account type
if (acctype.getText().toString().equals("Administrator")){
iv_edit_dialog.setVisibility(View.VISIBLE);
}else {
iv_edit_dialog.setVisibility(View.INVISIBLE);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I learnt my lesson the hard way! It is very important to understand the logic you want to come out with, followed by the expected work flow!
Many thanks to those who have taken their time to guide me through!

Custom adapter used in onStart() but app crashes when adding an item to ListView

public class ExerciseList extends ArrayAdapter<Exercise> {
private Activity context;
List<Exercise> exercises;
public ExerciseList(Activity context, List<Exercise> exercises) {
super(context, R.layout.layout_exercise_list, exercises);
this.context = context;
this.exercises = exercises;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.layout_exercise_list, null, true);
TextView nameTextView = listViewItem.findViewById(R.id.nameTextView);
TextView setsTextView = listViewItem.findViewById(R.id.setsTextView);
TextView repsTextView = listViewItem.findViewById(R.id.repsTextView);
TextView restTextView = listViewItem.findViewById(R.id.restTextView);
Exercise exercise = exercises.get(position);
nameTextView.setText(exercise.getName());
setsTextView.setText(String.valueOf(exercise.getSets()));
repsTextView.setText(String.valueOf(exercise.getReps()));
restTextView.setText(String.valueOf(exercise.getRestTime()));
return listViewItem;
}
}
public class WorkoutActivity extends AppCompatActivity {
EditText exerciseNameET;
EditText setsET;
EditText repsET;
EditText restTimeET;
Button addButton;
ArrayList<Exercise> exercises;
ListView exerciseList;
DatabaseReference dbExercises;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_workout);
dbExercises = FirebaseDatabase.getInstance().getReference("exercises");
exerciseNameET = findViewById(R.id.exerciseNameET);
setsET = findViewById(R.id.setsET);
repsET = findViewById(R.id.repsET);
restTimeET = findViewById(R.id.restTimeET);
addButton = findViewById(R.id.addButton);
exerciseList = findViewById(R.id.exerciseList);
exercises = new ArrayList<>();
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addExercise();
}
});
}
#Override
protected void onStart() {
super.onStart();
dbExercises.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
exercises.clear();
for(DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Exercise exercise = postSnapshot.getValue(Exercise.class);
exercises.add(exercise);
}
ExerciseList exerciseAdapter = new ExerciseList(WorkoutActivity.this, exercises);
exerciseList.setAdapter(exerciseAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void addExercise() {
String name = exerciseNameET.getText().toString();
int sets = Integer.parseInt(setsET.getText().toString());
int reps = Integer.parseInt(repsET.getText().toString());
int restTime = Integer.parseInt(restTimeET.getText().toString());
if((!TextUtils.isEmpty(name)) || (!TextUtils.isEmpty(setsET.getText().toString())) || (!TextUtils.isEmpty(repsET.getText().toString())) || (!TextUtils.isEmpty(restTimeET.getText().toString()))) {
String id = dbExercises.push().getKey();
Exercise exercise = new Exercise(id,name,sets,reps,restTime);
dbExercises.child(id).setValue(exercise);
exerciseNameET.setText("");
setsET.setText("");
repsET.setText("");
restTimeET.setText("");
} else {
Toast.makeText(this, "Invalid fields. Please complete the missing fields.", Toast.LENGTH_LONG).show();
}
}
}
I have created a custom adapter to be used for a ListView of one of my activites. This custom adapter is created in the onStart() method. I also have a separate layout file for each item in this ListView. The app uses Firebase and it successfully saves information to the database, but the app crashes when trying to display this same information on the ListView. I have followed many tutorials and my professor's lab solutions but I still do not know why my app is crashing. The XML files for the main activity is included below:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.josh2.mygains.WorkoutActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="#+id/exerciseNameET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Exercise name"
android:inputType="textPersonName" />
<EditText
android:id="#+id/setsET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Number of sets"
android:inputType="textPersonName" />
<EditText
android:id="#+id/repsET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Number of reps"
android:inputType="textPersonName" />
<EditText
android:id="#+id/restTimeET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Length of rest time"
android:inputType="textPersonName" />
<Button
android:id="#+id/addButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/exerciseList"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</ScrollView>
</LinearLayout>
The XML file for the items of the ListView is found below:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/nameTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp" />
<TextView
android:id="#+id/setsTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="15sp" />
<TextView
android:id="#+id/repsTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="15sp" />
<TextView
android:id="#+id/restTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="15sp" />
your adapter code is minefield for possible null pointer exceptions. String.valueOf(null) returns NullPointerException, so you should carefully handle any exception here.
if(exercise!=null && exercise.getSets()!=null){
setsTextView.setText(String.valueOf(exercise.getSets()));
}
apply same procedure for rest 2 setters as well.
In addition, the way you have handled your data update in the custom adapter is not standard. You should initiate your adapter in onCreate as you don't have to initialize the adapter every time the list is updated.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_workout);
dbExercises = FirebaseDatabase.getInstance().getReference("exercises");
exerciseNameET = findViewById(R.id.exerciseNameET);
setsET = findViewById(R.id.setsET);
repsET = findViewById(R.id.repsET);
restTimeET = findViewById(R.id.restTimeET);
addButton = findViewById(R.id.addButton);
exerciseList = findViewById(R.id.exerciseList);
exercises = new ArrayList<>();
ExerciseList exerciseAdapter = new ExerciseList(WorkoutActivity.this,
exercises);
exerciseList.setAdapter(exerciseAdapter);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addExercise();
}
});
}
and keep an updateExerciseList method on your custom adapter so that you can update the list in your adapter every time data is updated
public void updateExerciseList(List<Exercise> exercises) {
this.exercises = exercises;
}
simply update your data list after database is updated
#Override
protected void onStart() {
super.onStart();
dbExercises.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
exercises.clear();
for(DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Exercise exercise = postSnapshot.getValue(Exercise.class);
exercises.add(exercise);
}
exerciseAdapter.updateExerciseList(exercises);
exerciseAdapter.setNotifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

Categories

Resources