Firebase Database Child Count - android

I am developing an Android App which receives data from Firebase Realtime Database. Here is a Snapshot of my Database.
I want to get the number of children under the Comments field.
Here is my code:
public static class PostsViewHolder extends RecyclerView.ViewHolder
{
View mView;
ImageButton commentPostButton;
TextView DisplayNoOfInterest;
int countComments;
String currentUserId;
DatabaseReference CommentsRef;
public PostsViewHolder(View itemView)
{
super(itemView);
mView = itemView;
commentPostButton = (ImageButton)
mView.findViewById(R.id.commentPost);
DisplayNoOfInterest = (TextView) mView.findViewById(R.id.interest);
CommentsRef = FirebaseDatabase.getInstance().getReference();
currentUserId = FirebaseAuth.getInstance().getCurrentUser().getUid();
}
public void setCommentStatus() {
CommentsRef.child("Posts").child("Comments").addValueEventListener(new ValueEventListener())
{
#Override
public void onDataChange(DataSnapshot dataSnapshot){
if(dataSnapshot.exists()){
countComments = (int) dataSnapshot.getChildrenCount();
int cc = Integer.toString(countComments)
DisplayNoOfInterest.setText(cc);
}
}
}
}

Try this
FirebaseDatabase.getInstance().getReference().child("Posts").child(yourPostId).child("Comments").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists())
{
DisplayNoOfInterest.setText(""+dataSnapshot.getChildrenCount());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I hope that can help you!
Thank You.

Your reference is wrong. You need to pass the postID before trying to get comments, because the comments node is under each postID.
After referencing the right node, then you can call : dataSnapshot.getChildrenCount()
Example:
CommentsRef.child("Posts").child(POSTID).child("Comments").addValueEventListener(new ValueEventListener()){
#Override
public void onDataChange(DataSnapshot dataSnapshot){
if(dataSnapshot.exists()){
countComments = (int) dataSnapshot.getChildrenCount();
}
DisplayNoOfInterest.setText(Integer.toString(countComments));
}
}

Related

Firebase adapter is not updating the data according to my needs

My app have some users stored in firebase realtime database, each user have have a node "showGigCount" which should update if someone clicks on that user.
The problem:
If User 1 click on the data of User 2 then the showGigCount for User 1 will be incremented by 1 and showGigCount of User 2 will be decremented by 1. As you can see in the code I can successfully update the value of showGigCount for User 1 but the value of User 2 is not changing. Any suggestions would be highly appreciated. Below is my code. Thank You all
DashboardActivity
fAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
dRef = FirebaseDatabase.getInstance().getReference("Users");
if(fAuth.getCurrentUser() != null){
UID = FirebaseAuth.getInstance().getCurrentUser().getUid();
}
dRef.child(UID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
remainingClicks = Integer.parseInt(String.valueOf(snapshot.child("clicksRemain").getValue()));
showGigCount = Integer.parseInt(String.valueOf(snapshot.child("showGigCount").getValue()));
String username = String.valueOf(snapshot.child("name").getValue());
clicks.setText(String.valueOf(remainingClicks));
userName.setText(username);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
recyclerView = findViewById(R.id.dashboardRCV);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
LoadData();
}
private void LoadData() {
// This will display the data of a user if his showGigCount is greater than 0.
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = db.child("Users");
Query queryByShowGigCount = usersRef.orderByChild("showGigCount").startAt(1);
options = new FirebaseRecyclerOptions.Builder<ModelClass>()
.setQuery(queryByShowGigCount, ModelClass.class)
.build();
adapter = new FirebaseRecyclerAdapter<ModelClass, MyViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull MyViewHolder holder, int position, #NonNull ModelClass model) {
holder.previewLink.setURL(model.getGig(), new URLEmbeddedView.OnLoadURLListener() {
#Override
public void onLoadURLCompleted(URLEmbeddedData data) {
holder.previewLink.title(data.getTitle());
holder.previewLink.description(data.getDescription());
holder.previewLink.host(data.getHost());
holder.previewLink.thumbnail(data.getThumbnailURL());
holder.previewLink.favor(data.getFavorURL());
}
});
String user_clicked = getRef(position).getKey();
if (user_clicked.equals(UID)){
holder.previewLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("if1 working", "it's showing the data");
Toast.makeText(DashboardActivity.this, "Opening your link is not allowed", Toast.LENGTH_LONG).show();
}
});
}else if (!user_clicked.equals(UID)){
holder.previewLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Online User", "Online user clicking");
if (remainingClicks >= 1) { // This code increment the showGigCount of User 1 by 1.
remainingClicks--;
showGigCount ++;
clicks.setText(String.valueOf(remainingClicks));
UserClicksCounts();
UserShowGigCounts();
// I wrote this code so that showGigCount of User 2 will be decreased by 1 but it's not working
dRef.child(String.valueOf(user_clicked)).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
showGigCount--;
UserGigCountDecrease();
Log.d("CLicked User", "showGigCount decreased");
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
} else if (remainingClicks == 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);
}
void UserClicksCounts(){
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Users").child(UID);
myRef.child("clicksRemain").setValue(remainingClicks);
}
// This will count how many times the gig will be shown to the user
void UserShowGigCounts(){
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Users").child(UID);
myRef.child("showGigCount").setValue(showGigCount);
void UserGigCountDecrease(){
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Users").child(user_clicked);
myRef.child("showGigCount").setValue(showGigCount);
}
MyViewHolder Class
public MyViewHolder(#NonNull #NotNull View itemView) {
super(itemView);
previewLink = itemView.findViewById(R.id.uev);
geglink = (TextView) itemView.findViewById(R.id.rcvGigLink);
userName = (TextView) itemView.findViewById(R.id.rcvName);
userAbout = (TextView) itemView.findViewById(R.id.rcvAbout);
v = itemView;
}
To solve this I added these lines in the OnCLickListener
> user_clicked = getRef(position).getKey();
> assert user_clicked != null;
> dRef.child(user_clicked).child("showGigCount").setValue(model.getShowGigCount()-1);
It's now successfully decrementing the showGigCount of User 2.
I also removed the following lines of code
dRef.child(String.valueOf(user_clicked)).addValueEventListener(new
ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
showGigCount--;
UserGigCountDecrease();
Log.d("CLicked User", "showGigCount decreased");
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});

Why does the recyclerview data loads only when the button is clicked the second time

I am developing an app based on placement. I have used firebase realtime database for this. I am matching company name from the "Job Post" db and "Applied Candidate" db, so that only applied candidates detail for that particular company will be displayed. Everything is working fine but the issue is the recyclerview's data loads only when the button is clicked the second time.
public class AppliedCandidateActivity extends AppCompatActivity {
Toolbar toolbarAppliedcandidate;
RecyclerView rvAppliedCandidate;
List<appliedData> ls;
String compNameposted;
AppCandidateAdapter adapter;
DatabaseReference dbJobPost,dbAppliedCandidate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.applied_candidate);
toolbarAppliedcandidate = findViewById(R.id.toolbarAppliedcandidate);
rvAppliedCandidate = findViewById(R.id.rvAppliedCandidate);
setSupportActionBar(toolbarAppliedcandidate);
getSupportActionBar().setTitle("Applied Candidate");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
rvAppliedCandidate.setHasFixedSize(true);
rvAppliedCandidate.setLayoutManager(new LinearLayoutManager(this));
ls = new ArrayList<>();
adapter = new AppCandidateAdapter(getApplicationContext(),ls);
rvAppliedCandidate.setAdapter(adapter);
getCompany();
matchCompanyName();
}
void getCompany()
{
//To retrieve company name
dbJobPost = FirebaseDatabase.getInstance().getReference("Job Post").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
dbJobPost.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren())
{
PostJobData postJobData = ds.getValue(PostJobData.class);
compNameposted = postJobData.getCompName().toString();
//Toast.makeText(getApplicationContext(),postJobData.getCompName(),Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
void matchCompanyName()
{
//To retrieve data of applied candidate for particular company
dbAppliedCandidate = FirebaseDatabase.getInstance().getReference("Applied Candidate");
dbAppliedCandidate.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds: snapshot.getChildren())
{
for (DataSnapshot ds1 : ds.getChildren())
{
appliedData data = ds1.getValue(appliedData.class);
String compName = data.getCompName().toString();
//Toast.makeText(getApplicationContext(),compName,Toast.LENGTH_LONG).show();
if(compName.equals(compNameposted))
{
ls.add(data);
}
else if(ls.isEmpty()== true){
Toasty.info(AppliedCandidateActivity.this,"No One Applied Yet!!",Toast.LENGTH_LONG,true).show();
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
public class AppCandidateAdapter extends RecyclerView.Adapter<AppCandidateAdapter.AppCandidateViewHolder>{
List<appliedData> appliedDataList;
Context context;
public AppCandidateAdapter(Context mcontext,List list){
this.context = mcontext;
this.appliedDataList = list;
}
#NonNull
#Override
public AppCandidateViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.applied_candidate_compside,parent,false);
return new AppCandidateViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull AppCandidateViewHolder holder, int position) {
appliedData data = appliedDataList.get(position);
holder.tvCandidateName.setText(data.getName());
holder.tvCandidateAppliedPost.setText(data.getPosition());
holder.tvCandidateQual.setText(data.getQualification());
holder.tvCandidateSkills.setText(data.getSkills());
}
#Override
public int getItemCount() {
return appliedDataList.size();
}
class AppCandidateViewHolder extends RecyclerView.ViewHolder{
TextView tvCandidateName,tvCandidateAppliedPost,tvCandidateQual,tvCandidateSkills;
Button btnDeleteCandidate,btnSendMail;
public AppCandidateViewHolder(#NonNull View itemView) {
super(itemView);
tvCandidateName = itemView.findViewById(R.id.tvCandidateName);
tvCandidateAppliedPost = itemView.findViewById(R.id.tvCandidateAppliedPost);
tvCandidateQual = itemView.findViewById(R.id.tvCandidateQual);
tvCandidateSkills = itemView.findViewById(R.id.tvCandidateSkills);
btnDeleteCandidate = itemView.findViewById(R.id.btnDeleteCandidate);
btnSendMail = itemView.findViewById(R.id.btnSendMail);
}
}
}
}
Assuming your onDataChange does get called, successfully reads the PostJobData data from the snapshot, and adds it to ls, you're not telling Android that the list has changed. Only once you notify the adapter of the change, will it rerender the view.
dbJobPost = FirebaseDatabase.getInstance().getReference("Job Post").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
dbJobPost.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()) {
PostJobData postJobData = ds.getValue(PostJobData.class);
compNameposted = postJobData.getCompName().toString();
}
adapter.notifyDataSetChanged(); // notify the adapter
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});

Android - Firebase Ui get data from other table?

Hello everyone I need to get user_fname from other table reference with uid
Below this my code
I'm use IndexedQuery and not clear from tutorial and sample code Firebase Ui
mRef = FirebaseDatabase.getInstance().getReference().child("mainboard");
mReference = FirebaseDatabase.getInstance().getReference().child("user");
mRecyclerView = view.findViewById(R.id.mainboard_alllist);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mLayoutManager = new LinearLayoutManager(getContext());
mOption = new FirebaseRecyclerOptions.Builder<Mainboard>().
setIndexedQuery(mRef , mReference ,Mainboard.class)
.setLifecycleOwner(this)
.build();
mAdapter = new FirebaseRecyclerAdapter<Mainboard, MainboardViewHolder>(mOption) {
#Override
public MainboardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.mainboard_list , parent , false);
return new MainboardViewHolder(view);
}
#Override
protected void onBindViewHolder(MainboardViewHolder holder, int postion, Mainboard mainboard) {
String mb_id = mainboard.mb_id;
mRef.child( mb_id + "/mb_auther").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String mb_author = dataSnapshot.getValue().toString();
mReference.child(mb_author + "/user_fname").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String user_fname = dataSnapshot.getValue().toString();
Log.e("user_fname" , dataSnapshot.getValue().toString());
holder.setAuthor(user_fname);
}
}
}
};
}
}
Straight method
1.First get the mb_auther value using addListenerForSingleValueEvent listener
2.Then using that mb_auther value get the user_fname
mRef.child("id/mb_auther").addListenerForSingleValueEvent(new ValueEventListener() { //Your case id is -KrHOUwrsBbXHvUaOTIu
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String mb_auther = dataSnapshot.getValue().toString();
mReference.child(mb_auther + "/user_fname").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String user_fname = dataSnapshot.getValue().toString()
Log.e("user_fname", user_fname);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Retrieving data from Firebase but not showing

This is my firebase database from where I want to retrieve all the names of universities in ListView click here to see image
myRef= FirebaseDatabase.getInstance().getReference();
myRef.child("Universities").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
database c = postSnapshot.getValue(database.class);
final String name = c.getuniName();
userNameList.add(name);
final ArrayAdapter<String> mutahirAdapter=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1 , userNameList);
mListView.setAdapter(mutahirAdapter);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Database Class
I added data directly in Firebase now I am not getting the data in the ListView i wanted to retrieve all the child's of universities in ListView
package com.mutahir.futureguide;
public class database {
String Name;
public String uniName(String Name) {
this.Name= Name;
return Name;
}
public String getuniName() {
return Name;
}
public void setuniName(String Name) {
this.Name = Name;
}
}
Hope it worked!
myRef= FirebaseDatabase.getInstance().getReference();
myRef.child("Universities").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
final String name = postSnapshot.getValue("name").toString();
userNameList.add(name);
}
if(!userNameList.isEmpty()){
final ArrayAdapter<String> mutahirAdapter=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1 , userNameList);
mListView.setAdapter(mutahirAdapter);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Android Firebase : retrieve All data in ArrayList and randomly select string from that ArrayList

I am creating an app with Firebase in which user can share quotes. Data is inserted successfully and it looks like this in database after each value inserted.
please see this image for database values:
and I want to fetch all the data in an ArrayList. and onclick of refresh button the TextView should be updated to new value that will be randomly selected from ArrayList. I have tried something like this. but its not working. it showing nullpointerexception.
public View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle) {
this.localView = paramLayoutInflater.inflate(R.layout.fragmenthome, paramViewGroup, false);
story = (TextView) localView.findViewById(R.id.story_text);
rl = (RelativeLayout) localView.findViewById(R.id.rlLayout);
linearLayout = (LinearLayout) localView.findViewById(R.id.bottom_bar);
imgRefresh = (ImageView) localView.findViewById(R.id.refreshStory);
databaseReference = FirebaseDatabase.getInstance().getReference().child("stories");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
storiesary = new ArrayList<String>();
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
storiesary.add(childSnapshot.getValue().toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
imgRefresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setStory();
}
});
return localView;
}
public void setStory()
{
int arraysize = storiesary.size();
final int arrayposition1 = (new Random()).nextInt(arraysize);
story.setText(storiesary.get(arrayposition1));
}
Try this
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
storiesary = new ArrayList<String>();
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
HashMap map =(HashMap) childSnapshot.getValue();
if(map!=null) {
storiesary.add(map.get("storytext"));
}
//or
String name = (String) childSnapshot.child("storytext").getValue();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG,"Error");
}
});

Categories

Resources