Find out when does Query finish loading the latest added item - android

I have a function which write data into database
private void startCommenting() {
final String comment_val = meditComment.getText().toString().trim();
meditComment.setText("");
if (!TextUtils.isEmpty(comment_val)) {
mProgress.show();
final DatabaseReference newPost = mComment.child(post_key).push();
final String commentkey = newPost.getKey();
mUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String,Object> checkoutData=new HashMap<>();
checkoutData.put("time",ServerValue.TIMESTAMP);
newPost.setValue(checkoutData);
newPost.child("comment").setValue(comment_val);
newPost.child("uid").setValue(dataSnapshot.child("id").getValue());
newPost.child("blogpost").setValue(dataSnapshot.child("blogkey").getValue());
newPost.child("userimage").setValue(dataSnapshot.child("image").getValue());
newPost.child("username").setValue(dataSnapshot.child("name").getValue());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
After this function was called, a Query was made to get the data which contains the right post_key in the child ("blogpost").
mpostComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startCommenting();
mQueryCurrentComment = mComment.child(post_key).orderByChild("blogpost").equalTo(post_key);
mQueryCurrentComment.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String currentuserid;
String lastuserid = "";
String currentcommentuid;
for (DataSnapshot dsp : dataSnapshot.getChildren()) {
currentuserid = dsp.child("uid").getValue().toString();
Log.d(TAG, "user newid: " + currentuserid);
Log.d(TAG, "user oldid: " + lastuserid);
if (currentuserid.equals(lastuserid)) {
} else {
final DatabaseReference newCommentLike = mComment.child(currentuserid).push();
Map<String, Object> checkTime = new HashMap<>();
checkTime.put("time", ServerValue.TIMESTAMP);
newCommentLike.setValue(checkTime);
newCommentLike.child("location").setValue(location_key);
newCommentLike.child("category").setValue(category_key);
newCommentLike.child("pressed").setValue("false");
newCommentLike.child("message").setValue(" has also commented your post. ");
newCommentLike.child("blogpost").setValue(post_key);
newCommentLike.child(post_key).setValue(true);
}
lastuserid = currentuserid;
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
However, the Query was triggered twice, one before the new item was added, another after new item was added, which looks like below:
How can I only perform the actions inside Query after the newest item was added and not twice? Any help is appreciated!

Related

I have a problem accessing child nodes. (firebase realtime database - increment reports)

Here is my data structure.
"Posts" : {
"-MpVVpVIqmn0Iu78hDRp" : {
"description" : "",
"picture" : "",
"postKey" : "",
"reports" : 0,
"timeStamp" : 1638001760487,
"title" : "",
"userId" : "",
"userPhoto" : ""
},
"-MpVcioadtvRBRaa0n96" : {
"description" : "",
"picture" : "",
"postKey" : "",
"reports" : 0,
"timeStamp" : 1638003830234,
"title" : "",
"userId" : "",
"userPhoto" : ""
},
I want to access the "reports" part. So I use
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.child("Posts").child("reports").setValue(1);
But It creates reports value 1 right below Posts not below "-MpVVpVIqmn0Iu78hDRp" this.
I want to increment the report. But I don't know how can I approach to reports node.
Here is my full code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_detail);
imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
et = (EditText)findViewById(R.id.post_detail_comment);
// let's set the statue bar to transparent
// ini Views
RvComment = findViewById(R.id.rv_comment);
imgPost =findViewById(R.id.post_detail_img);
imgUserPost = findViewById(R.id.post_detail_user_img);
imgCurrentUser = findViewById(R.id.post_detail_currentuser_img);
txtPostTitle = findViewById(R.id.post_detail_title);
txtPostDesc = findViewById(R.id.post_detail_desc);
txtPostDateName = findViewById(R.id.post_detail_date_name);
editTextComment = findViewById(R.id.post_detail_comment);
btnAddComment = findViewById(R.id.post_detail_add_comment_btn);
btnDeletePost = findViewById(R.id.button_delete);
btnnoti = findViewById(R.id.button_noti);
btncommentnoti = findViewById(R.id.comment_noti);
firebaseAuth = FirebaseAuth.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
firebaseDatabase = FirebaseDatabase.getInstance();
// add post delete button
mDatabase= FirebaseDatabase.getInstance().getReference();
myUid = FirebaseAuth.getInstance().getCurrentUser().getUid();
//게시글 신고기능
btnnoti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.child("Posts").child("reports").setValue(1);
}
});
btnDeletePost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//여기 수정 주의 UId.equals(myUid)
if (true){
Toast.makeText(PostDetailActivity.this,"삭제중...",Toast.LENGTH_SHORT).show();
beginDelete();
onBackPressed();
}
}
});
// add Comment button click listener
btnAddComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btnAddComment.setVisibility(View.INVISIBLE);
DatabaseReference commentReference = firebaseDatabase.getReference(COMMENT_KEY).child(PostKey).push();
String comment_content = editTextComment.getText().toString();
String uid = firebaseUser.getUid();
String uname = firebaseUser.getDisplayName();
if (firebaseUser.getPhotoUrl()!=null){
String uimg = firebaseUser.getPhotoUrl().toString();
Comment comment = new Comment(comment_content,uid,uimg,uname);
commentReference.setValue(comment).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
showMessage("댓글이 등록되었습니다.");
editTextComment.setText("");
btnAddComment.setVisibility(View.VISIBLE);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
showMessage("fail to add comment : "+e.getMessage());
}
});
}
else{
String usphoto =Integer.toString(R.drawable.userphoto);
Comment comment = new Comment(comment_content,uid,usphoto,uname);
commentReference.setValue(comment).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
showMessage("comment added");
editTextComment.setText("");
btnAddComment.setVisibility(View.VISIBLE);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
showMessage("fail to add comment : "+e.getMessage());
}
});
}
}
});
// now we need to bind all data into those views
// first we need to get post data
// we need to send post detail data to this activity first ...
// now we can get post data
// 게시글 사진 백지 케이스
postImage = getIntent().getExtras().getString("postImage") ;
if(postImage!=null){
Glide.with(this).load(postImage).into(imgPost);
}
else{
Glide.with(this).load(R.drawable.whitepaper).into(imgPost);
}
String postTitle = getIntent().getExtras().getString("title");
txtPostTitle.setText(postTitle);
String userpostImage = getIntent().getExtras().getString("userPhoto");
if (userpostImage!=null){
Glide.with(this).load(userpostImage).into(imgUserPost);
}
else {
Glide.with(this).load(R.drawable.userphoto).into(imgUserPost);
}
String postDescription = getIntent().getExtras().getString("description");
txtPostDesc.setText(postDescription);
// set comment user image
if (firebaseUser.getPhotoUrl()!=null){
Glide.with(this).load(firebaseUser.getPhotoUrl()).into(imgCurrentUser);
}
else{
Glide.with(this).load(R.drawable.userphoto).into(imgCurrentUser);
}
// get post key
PostKey = getIntent().getExtras().getString("postKey");
String date = timestampToString(getIntent().getExtras().getLong("postDate"));
txtPostDateName.setText(date);
// get post uid
UId = getIntent().getExtras().getString("userId");
// ini Recyclerview Comment
iniRvComment();
}
private void beginDelete() {
//서버 관리용 개발자 옵션
if (myUid.equals("k1kn0JF5idhrMzuw46GarEIBgPw2")) {
long tlong = System.currentTimeMillis(); long ttime;
ttime = tlong - 3*24*60*60*1000;
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
Query queryByTimestamp = db.child("Posts").orderByChild("timeStamp").endAt(ttime);
queryByTimestamp.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
ds.getRef().removeValue();
Toast.makeText(PostDetailActivity.this,"게시글이 삭제되었습니다.",Toast.LENGTH_SHORT).show();
}
} else {
Log.d("TAG", task.getException().getMessage());
Toast.makeText(PostDetailActivity.this,"게시글이 삭제되지않았습니다.",Toast.LENGTH_SHORT).show();
}
}
});
}
else if (UId.equals(myUid)) {
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
Query queryByTimestamp = db.child("Posts").orderByChild("postKey").equalTo(PostKey);
queryByTimestamp.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
ds.getRef().removeValue();
Toast.makeText(PostDetailActivity.this, "게시글이 삭제되었습니다.", Toast.LENGTH_SHORT).show();
}
} else {
Log.d("TAG", task.getException().getMessage());
Toast.makeText(PostDetailActivity.this, "게시글이 삭제되지않았습니다.", Toast.LENGTH_SHORT).show();
}
}
});
}
else{
Toast.makeText(PostDetailActivity.this,"다른 사용자의 게시글입니다.",Toast.LENGTH_SHORT).show();
}
}
public void linearOnClick(View v) {
imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
}
private void iniRvComment() {
RvComment.setLayoutManager(new LinearLayoutManager(this));
DatabaseReference commentRef = firebaseDatabase.getReference(COMMENT_KEY).child(PostKey);
commentRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
listComment = new ArrayList<>();
for (DataSnapshot snap:dataSnapshot.getChildren()) {
Comment comment = snap.getValue(Comment.class);
listComment.add(comment) ;
}
commentAdapter = new CommentAdapter(getApplicationContext(),listComment);
RvComment.setAdapter(commentAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void showMessage(String message) {
Toast.makeText(this,message,Toast.LENGTH_LONG).show();
}
private String timestampToString(long time) {
Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
calendar.setTimeInMillis(time);
String date = DateFormat.format("yyyy-MM-dd",calendar).toString();
return date;
}
}
This is the part of my question
btnnoti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.child("Posts").child("reports").setValue(1);
}
});
I also tried orderbychild but I think it is not the right code.
This code:
rootRef.child("Posts").child("reports").setValue(1);
You're telling the database to set the value of /Posts/reports to 1, which is precisely what it then does.
If you want increment the current value of a node, you can use the atomic increment operation:
rootRef.child("Posts").child("reports").setValue(ServerValue.increment(1));
If you want to increment the reports property of a specific node under Posts, you will need to know the key of that node. For example:
rootRef.child("Posts/-MpVVpVIqmn0Iu78hDRp/reports").setValue(ServerValue.increment(1));
If you don't know the key of the node to increment, but do know some other value that uniquely (enough) identifies the node(s) to update, you can use a query to find the keys.
For example, to update all nodes with a specific postKey:
Query query = rootRef.child("Posts").orderByChild("postKey").equalTo("thePostKeyValue");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
postSnapshot.getReference().child("reports").setValue(ServerValue.increment(1));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}

How to read data from RecyclerView and make comparison?

Hi I want to read the display data from RecyclerView and make comparison.
This my layout for the activity:
What I want to do is to read all data from RecyclerView and compare with Daily Calorie Suggestion.
After reading all data, I need to make comparisons on how many times the user have taken above, less or sufficient total calories as shown in the "Analysis of Total Calories Consumed of Last 7 Days"
The code:
#Override
protected void onStart() {
Query query = ref.orderByChild("timeStamp").limitToLast(7).endAt(Date);
super.onStart();
if (query != null) {
query .addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
userHighlights = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
userHighlights.add(ds.getValue(HighightsModel.class));
requiredCalorieRef = FirebaseDatabase.getInstance().getReference("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
requiredCalorieRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String userCalorieSuggestion = String.valueOf((dataSnapshot.child("daily calorie").getValue()));
int daily_calorie = Integer.parseInt(userCalorieSuggestion);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
HighlightsAdapter highlightsAdapter = new HighlightsAdapter(userHighlights);
highlightsRV.setAdapter(highlightsAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(UserNewHighlights.this, databaseError.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
}
}
This is my firebase:
Do I have to write a new code to solve this problem or else? Any help will be much appreciated. Thanks
As #MasoudDarzi mentioned, it's not related to the RecyclerView.
You can try something like this:
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
userHighlights = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
userHighlights.add(ds.getValue(HighightsModel.class));
requiredCalorieRef = FirebaseDatabase.getInstance().getReference("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
requiredCalorieRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String userCalorieSuggestion = String.valueOf((dataSnapshot.child("daily calorie").getValue()));
int daily_calorie = Integer.parseInt(userCalorieSuggestion);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
HighlightsAdapter highlightsAdapter = new HighlightsAdapter(userHighlights);
highlightsRV.setAdapter(highlightsAdapter);
// do calculation here with userHighlights
int countExceeded = 0, countBelow = 0, countSufficient = 0;
for (HighightsModel h : userHighlights) {
if (h.totalCalorie > daily_calorie) {
countExceeded++;
} else if (h.totalCalorie < daily_calorie) {
countBelow++;
} else {
countSufficient++;
}
}
// update your TextView with the count numbers
// todo
}
}
so The brute force solution is to have a for in your data after getting the 7 days average.
for (your 7 days data){
// check if your data is lower or higher than the average
// and store number of higher or lower
}
looking for a better solution?
I have solved my problem by adding another child at History node. Whereby, previously I have only these for History :
but I add new child which is called STATUS, the status is updated from previous activity as seen the pic below:
so what I did for the code is :
private void upDateAnalysisAbove() {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("History");
DatabaseReference mRef = ref.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
Query mQuery = mRef.orderByChild("status").equalTo("ABOVE").limitToLast(7);
mQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = String.valueOf(dataSnapshot.getChildrenCount());
int values = Integer.parseInt(value);
txt_above_output.setText(values + " times(s)");
upDateAnalysisLess(values);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
//LESS
private void upDateAnalysisLess(int values) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("History");
DatabaseReference mRef = ref.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
Query mQuery = mRef.orderByChild("status").equalTo("LESS").limitToFirst(7);
mQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String valueLess = String.valueOf(dataSnapshot.getChildrenCount());
int values_Less = Integer.parseInt(valueLess);
if (values_Less == 0){
txt_less_output.setText(values_Less + " times(s)");
}
if (values > values_Less){
int finalCount = values - values_Less ;
txt_less_output.setText(finalCount + " times(s)");
}
if (values <values_Less){
int finalCount = values_Less - values ;
txt_less_output.setText(finalCount + " times(s)");
}
updateSuff();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
//SUFFICIENT
private void updateSuff() {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("History");
DatabaseReference mRef = ref.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
Query mQuery = mRef.orderByChild("status").equalTo("SUFFICIENT").limitToFirst(7);
mQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = String.valueOf(dataSnapshot.getChildrenCount());
int suffValue = Integer.parseInt(value);
if (suffValue == 0) {
txt_sufficient_output.setText(suffValue + " times(s)");
}
if (suffValue != 0){
txt_sufficient_output.setText(suffValue + " times(s)");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Here is the output:
credit to this post that helped me a lot, and thanks for those who tried to help me.

Do calculation by retrieving data from Child Node is not working at all in Android Studio/Firebase

I have a problem to do subtract calculation by retrieving data from a Child Nod. As you can see my layout below, what I want to do is to get Remaining Kcal value by calculating Daily Kcal value minus Total Kcal and display the Remaining Kcal to the TextView.
I suspected the calculation for the subtraction part (code below) is not working at all as I tried to put the remainingCount/remainingCalorie value into firebase but nothing happened.
//CALCULATE AND DISPLAY REMAINING CALORIE
private void updateRemainingKcal(final double finalCount) {
DatabaseReference userRecord = FirebaseDatabase.getInstance().getReference();
DatabaseReference userReference = userRecord.child("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
userReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
double remainingCount = 0;
for (DataSnapshot userChild: dataSnapshot.getChildren()) {
for (DataSnapshot recordSnapshot: userChild.getChildren()) {
double userCalorie = Double.valueOf(recordSnapshot.child("daily calorie").getValue(String.class));
remainingCount = userCalorie - finalCount;
userRemainingCalorie.setText((remainingCount +"kcal"));
myHistoryRef = FirebaseDatabase.getInstance().
getReference("History").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date_record).child("Total Calorie");
Map<String, Object> values = new HashMap<>();
values.put("remainingCalorie", remainingCount);
myHistoryRef.updateChildren(values).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
});
}
}
Log.d("TAG", remainingCount + "");
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
This is relevant code to do this operation, whereby I need to retrieve "daily calorie' from User first, then I can do the substraction daily calorie (Required Kcal) - total calorie consume (Total Kcal) = Remaining Calorie (Remaining Kcal):
//**********************DATABASE REFERENCE FOR USER REQUIRED CALORIE***************************//
requiredCalorieRef = FirebaseDatabase.getInstance().getReference("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
requiredCalorieRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String userCalorieSuggestion = String.valueOf((dataSnapshot.child("daily calorie").getValue()));
userRequiredCalorie.setText((userCalorieSuggestion +"kcal"));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
//CALCULATE AND DISPLAY TOTAL CALORIE ACCORDING TO DATE
private void updateTotalCalorie(final String date_n) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference nameRef = rootRef.child("UsersRecords").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child(date_record);
nameRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
double count = 0;
for (DataSnapshot foodTypeSnapshot: dataSnapshot.getChildren()) {
for (DataSnapshot recordSnapshot: foodTypeSnapshot.getChildren()) {
double foodCalorie = Double.valueOf(recordSnapshot.child("foodCalorie").getValue(String.class));
count = count + foodCalorie;
userTotalCalorie.setText((count +"kcal"));
myHistoryRef = FirebaseDatabase.getInstance().
getReference("History").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date_record).child("Total Calorie");
Map<String, Object> values = new HashMap<>();
values.put("totalCalorie", count);
values.put("Date Consume", date_n);
final double finalCount = count;
myHistoryRef.updateChildren(values).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
updateRemainingKcal(finalCount);
}
});
}
}
Log.d("TAG", count + "");
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
//CALCULATE AND DISPLAY REMAINING CALORIE
private void updateRemainingKcal(final double finalCount) {
DatabaseReference userRecord = FirebaseDatabase.getInstance().getReference();
DatabaseReference userReference = userRecord.child("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
userReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
double remainingCount = 0;
for (DataSnapshot userChild: dataSnapshot.getChildren()) {
for (DataSnapshot recordSnapshot: userChild.getChildren()) {
double userCalorie = Double.valueOf(recordSnapshot.child("daily calorie").getValue(String.class));
remainingCount = userCalorie - finalCount;
userRemainingCalorie.setText((remainingCount +"kcal"));
myHistoryRef = FirebaseDatabase.getInstance().
getReference("History").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date_record).child("Total Calorie");
Map<String, Object> values = new HashMap<>();
values.put("remainingCalorie", remainingCount);
myHistoryRef.updateChildren(values).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
});
}
}
Log.d("TAG", remainingCount + "");
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
This is my firebase looks like - there is no node of RemainingCalorie at all at History node:
How can I solve this issue despite knowing the problem. I have tried several ways but nothing could help to solve this code problem.
I have solved my own problem. Thank you, finally did it. This is right code for those who have same problem in future:
private void updateRemaining(final int finalCount) {
userDatabase = FirebaseDatabase.getInstance().getReference("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
userDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String user = String.valueOf((dataSnapshot.child("daily calorie").getValue()));
int dailyCalorie = Integer.parseInt(user);
int remainingCalorie = dailyCalorie-finalCount;
userRemainingCalorie.setText((remainingCalorie +"kcal"));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
this is the screen-shot

How can I compare this 2 value then show to FirebaseRecyclerAdapter?

I want to connect the user id with the same key in Users, then show the key to FirebaseRecyclerAdapter. I get the key in Friend child already but don't know how to match this to Users.
And my code:
mFriendList = FirebaseDatabase.getInstance().getReference().child("Friends").child(current_id);
mFriendDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mFriendList.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String sd = snapshot.getKey(); //key from Friends
final FirebaseRecyclerAdapter<Users_Friends, UsersFriendViewHolder> firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<Users_Friends, UsersFriendViewHolder>(
Users_Friends.class,
R.layout.users_single_friend_layout,
UsersFriendViewHolder.class,
filter
) {
#Override
protected void populateViewHolder(UsersFriendViewHolder viewHolder, Users_Friends users, int position) {
viewHolder.setDisplayName(users.getName());
viewHolder.setStatusUsers(users.getStatus());
viewHolder.setUserImage(users.getImage(), getContext().getApplicationContext());
final String user_id = getRef(position).getKey();
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent profileIntent = new Intent(getActivity(), ProfileActivity.class);
profileIntent.putExtra("user_id", user_id);
startActivity(profileIntent);
}
});
}
};
mReqList.setAdapter(firebaseRecyclerAdapter);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
You only need to use exists() method directly on the dataSnapshot object like this:
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(current_id).exists()) {
Log.d("TAG", "User exists");
} else {
Log.d("TAG", "User does not exist");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
mFriendDatabase.addListenerForSingleValueEvent(eventListener);

Android Studio Firebase Database return null object reference

Hello Guys i need you I have a problem with Firebase Realtime Database I put the data successful to the Firebase but when I try to retrieve it from Firebase I got a problem there is how I put the data
private void user_info(String user_id, String user_display_name) {
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id);
HashMap<String, String> userMap = new HashMap<>();
userMap.put("Name",user_display_name);
userMap.put("Balls","30");
userMap.put("Level","1");
mProgressDialog.setMessage("Please Wait...");
mDatabase.setValue(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
}
else
Toast.makeText(WelcomeActivity.this, ""+task.getException(), Toast.LENGTH_SHORT).show();
mProgressDialog.dismiss();
}
});
}
And how I try to retrieve the data
private FirebaseUser mUser;
private DatabaseReference mDatabase;
private String level,level1;
private int lev,i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level_acticity);
//Image
mImg_level1 = (ImageView)findViewById(R.id.mImg_lev1);
mImg_level2 = (ImageView)findViewById(R.id.mImg_lev2);
mImg_level3 = (ImageView)findViewById(R.id.mImg_lev3);
mImg_level4 = (ImageView)findViewById(R.id.mImg_lev4);
mImg_level5 = (ImageView)findViewById(R.id.mImg_lev5);
mImg_level6 = (ImageView)findViewById(R.id.mImg_lev6);
mImg_level7 = (ImageView)findViewById(R.id.mImg_lev7);
mImg_level8 = (ImageView)findViewById(R.id.mImg_lev8);
mImg_level9 = (ImageView)findViewById(R.id.mImg_lev9);
mImg_level10 = (ImageView)findViewById(R.id.mImg_lev10);
mImg_level11 = (ImageView)findViewById(R.id.mImg_lev11);
//Firebase
mUser = FirebaseAuth.getInstance().getCurrentUser();
String user_id = mUser.getUid();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
level = dataSnapshot.child("Level").getValue().toString();
if (level.equals("1")){
level1 = "1";
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Toast.makeText(this, level1, Toast.LENGTH_SHORT).show();
The toast don't show anything because it null
Change this :-
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
level = dataSnapshot.child("Level").getValue().toString();
if (level.equals("1")){
level1 = "1";
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Toast.makeText(this, level1, Toast.LENGTH_SHORT).show();
to this :-
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
level = dataSnapshot.child("Level").getValue().toString();
if (level.equals("1")){
level1 = "1";
}
Toast.makeText(this, level1, Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The reason this works is that Firebase downloads asynchronously and your code lines execute synchronously.

Categories

Resources