connection between two tables in firebase android studio - android

in firebase I have two tables: itinerary with id, title, hour, minutes, seconds, description, level of difficulty and image while in review I have title, image and rating now I should insert the itinerary id, generated with getNewKey, in review so that one itinerary has several reviews. The created method is:
public void addReview() {
storageReference = FirebaseStorage.getInstance().getReference();
referenceDb = FirebaseDatabase.getInstance().getReference();
auth = FirebaseAuth.getInstance();
FirebaseUser firebaseUser = auth.getCurrentUser();
String titleReview = insertReviews_fragment.getTitleReview();
String descriptionReview = insertReviews_fragment.getDescriptionReview();
String voteItinerary = insertReviews_fragment.getVoteReview();
//String ItineraryId = String.valueOf(explore_fragment.getId());
String itineraryId = referenceDb.child("Itinerary").push().getKey();
ReviewDao reviewDao = new ReviewDao();
String reviewId = reviewDao.getNewKey();
if (images != null) {
StorageReference reviewRef = storageReference.child("review_image/").child(reviewId + ".jpg");
reviewRef.putFile(Uri.parse(String.valueOf(images))).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
reviewRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String uid = auth.getUid();
String email = firebaseUser.getEmail();
HashMap<String, Object> map = new HashMap<>();
map.put("titleReview", titleReview);
map.put("image", uri.toString());
map.put("email", email);
map.put("voteReview", voteItinerary);
map.put("descriptionReview", descriptionReview);
map.put("userId", uid);
map.put("reviewId", reviewId);
map.put("ItineraryId", itineraryId);
referenceDb.child("Reviews").child(reviewId).setValue(map).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
//APRO SCHERMATA List Review
Toast.makeText(insertReviews_fragment.getActivity(), "Operation successful, thanks for your feedback", Toast.LENGTH_SHORT).show();
openListReviewsFragment();
} else {
//ERRORE
Toast.makeText(insertReviews_fragment.getActivity(), "Operation failed. Please try again", Toast.LENGTH_SHORT).show();
}
}
});
}
});
} else {
Toast.makeText(insertReviews_fragment.getActivity(), task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
} else {
Toast.makeText(insertReviews_fragment.getActivity(), "Please add image", Toast.LENGTH_SHORT).show();
}
}
public void getAllItinerary(){
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference referenceDb = database.getReference("Itinerary");
itineraryList = new ArrayList<>();
Itinerary iter = new Itinerary();
itineraryList.clear();
referenceDb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
Iterable<DataSnapshot> dataSnapsho1 = snapshot.getChildren();
for(DataSnapshot ds : dataSnapsho1) {
if(ds.child("titleItinerary").getValue() != null){
Itinerary iter = new Itinerary(
(String) ds.child("itineraryId").getValue(),
(String) ds.child("titleItinerary").getValue(),
(String) ds.child("descriptionItinerary").getValue(),
(String) ds.child("difficultyLevel").getValue(),
(String) ds.child("hours").getValue(),
(String) ds.child("minutes").getValue(),
(String) ds.child("seconds").getValue(),
String.valueOf(ds.child("image").getValue()));
iter.setEmail((String)ds.child("email").getValue());
itineraryList.add(iter);
}
}
adapterListItinerary = new AdapterListItinerary(getActivity(), itineraryList);
recyclerView.setAdapter(adapterListItinerary);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
But this way a new id code is associated with the itineraryId attribute in the reviews table. How can I fix?

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

Null Pointer Exception as notification was added

I don't get the error when i run the app everything works fine, but when i click on the send message button the app crashes but the message still gets sent. below is my code for the chatActivity and logcat message
package com.paddi.paddi.paddi;
public class ChatActivity extends AppCompatActivity
{
private String messageReceiverId;
private String messageReceiverName;
// private Toolbar ChatToolBar;
private TextView userNameTitle;
private TextView userLastSeen;
private CircleImageView userChatProfileImage;
private ImageButton SendMessageButton;
// private ImageButton SelectImageButton;
private EditText InputMessageText;
FirebaseUser fuser;
DatabaseReference rootRef;
private FirebaseAuth mAuth;
private String messageSenderId;
private RecyclerView userMessagesList;
private final List<Messages> messageList = new ArrayList<>();
private LinearLayoutManager linearLayoutManager;
private MessageAdapter messageAdapter;
private static int Gallery_Pick = 1;
private StorageReference MessageImageStorageRef;
private ProgressDialog loadingBar;
private String downloadImageUrl;
Intent intent;
ValueEventListener seenListener;
String userid;
APIServiceFragment apiService;
boolean notify = false;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
rootRef = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
messageSenderId = mAuth.getCurrentUser().getUid();
messageReceiverId = getIntent().getExtras().get("visit_user_id").toString();
messageReceiverName = getIntent().getExtras().get("user_name").toString();
MessageImageStorageRef = FirebaseStorage.getInstance().getReference().child("Messages_Pictures");
apiService = Client.getClient("https://fcm.googleapis.com/").create(APIServiceFragment.class);
// ChatToolBar = (Toolbar) findViewById(R.id.chat_bar_layout);
// setSupportActionBar(ChatToolBar);
loadingBar = new ProgressDialog(this);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
LayoutInflater layoutInflater = (LayoutInflater)
this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View action_bar_view = layoutInflater.inflate(R.layout.chat_custom_bar, null);
actionBar.setCustomView(action_bar_view);
userNameTitle = (TextView) findViewById(R.id.custom_profile_name);
userLastSeen = (TextView) findViewById(R.id.custom_user_last_seen);
userChatProfileImage = (CircleImageView) findViewById(R.id.custom_profile_image_last_seen);
SendMessageButton = (ImageButton) findViewById(R.id.send_message_btn);
// SelectImageButton = (ImageButton) findViewById(R.id.select_image);
InputMessageText = (EditText) findViewById(R.id.input_message);
messageAdapter = new MessageAdapter(messageList);
userMessagesList = (RecyclerView) findViewById(R.id.messages_list_of_users);
linearLayoutManager = new LinearLayoutManager(this);
userMessagesList.setHasFixedSize(true);
userMessagesList.setLayoutManager(linearLayoutManager);
userMessagesList.setAdapter(messageAdapter);
FetchMessages();
userNameTitle.setText(messageReceiverName);
rootRef.child("Users").child(messageReceiverId).addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
final String online = dataSnapshot.child("online").getValue().toString();
final String userThumb = dataSnapshot.child("user_thumb_image").getValue().toString();
Picasso.with(ChatActivity.this).load(userThumb).fit().centerInside().networkPolicy(NetworkPolicy.OFFLINE).placeholder(R.drawable.default_profile)
.into(userChatProfileImage, new Callback() {
#Override
public void onSuccess()
{
}
#Override
public void onError()
{
Picasso.with(ChatActivity.this).load(userThumb).fit().centerInside().placeholder(R.drawable.default_profile).into(userChatProfileImage);
}
});
if (online != null) {
if (online.equals("true"))
{
userLastSeen.setText("online");
}
else
{
LastSeenTime getTime = new LastSeenTime();
long last_seen = Long.parseLong(online);
//problem with last seen time here
String lastSeenDisplayTime = getTime.getTimeAgo(last_seen, getApplicationContext()).toString();
userLastSeen.setText(lastSeenDisplayTime);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
});
SendMessageButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
SendMessage();
}
});
// SelectImageButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v)
// {
// Intent galleryIntent = new Intent();
// galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// galleryIntent.setType("image/*");
// startActivityForResult(galleryIntent, Gallery_Pick);
//}
//});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==Gallery_Pick && resultCode==RESULT_OK &&data!=null)
{
loadingBar.setTitle("Sending Image");
loadingBar.setMessage("Please Wait");
loadingBar.show();
Uri ImageUri = data.getData();
final String message_sender_ref = "Messages/" + messageSenderId + "/" + messageReceiverId;
final String message_receiver_ref = "Messages/" + messageReceiverId + "/" + messageSenderId;
DatabaseReference user_message_key = rootRef.child("Messages").child(messageSenderId)
.child(messageReceiverId).push();
final String message_push_id = user_message_key.getKey();
final StorageReference filePath = MessageImageStorageRef.child(message_push_id + ".jpg");
final StorageTask<UploadTask.TaskSnapshot> taskSnapshotStorageTask = filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
downloadImageUrl = filePath.getDownloadUrl().toString();
// return filePath.getDownloadUrl();
Map messageTextBody = new HashMap();
messageTextBody.put("message", downloadImageUrl);
messageTextBody.put("isseen", true);
messageTextBody.put("type", "image");
messageTextBody.put("time", ServerValue.TIMESTAMP);
messageTextBody.put("from", messageSenderId);
messageTextBody.put("to", messageReceiverId);
Map messageBodyDetails = new HashMap();
messageBodyDetails.put(message_sender_ref + "/" + message_push_id, messageTextBody);
messageBodyDetails.put(message_receiver_ref + "/" + message_push_id, messageTextBody);
rootRef.updateChildren(messageBodyDetails, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError != null) {
Log.d("Chat_Log", databaseError.getMessage().toString());
}
InputMessageText.setText("");
loadingBar.dismiss();
}
});
Toast.makeText(ChatActivity.this, "Picture Sent Successfully.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
} else {
Toast.makeText(ChatActivity.this, "Picture not sent, Try again", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
private void FetchMessages()
{
rootRef.child("Messages").child(messageSenderId).child(messageReceiverId)
.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s)
{
if (dataSnapshot.exists())
{
Messages messages = dataSnapshot.getValue(Messages.class);
messageList.add(messages);
messageAdapter.notifyDataSetChanged();
userMessagesList.smoothScrollToPosition(userMessagesList.getAdapter().getItemCount());
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s)
{
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot)
{
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s)
{
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
});
// seenMessage(userid);
}
private void seenMessage(final String userid) //add String and userid
{
rootRef = FirebaseDatabase.getInstance().getReference("Messages");
seenListener = rootRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
for (DataSnapshot snapshot : dataSnapshot.getChildren())
{
Messages messages = snapshot.getValue(Messages.class);
if (messages.getTo().equals(fuser.getUid()) && messages.getFrom().equals(ChatActivity.this.userid))//change messages to userid
{
Map messageTextBody = new HashMap();
messageTextBody.put("isseen", true);
snapshot.getRef().updateChildren(messageTextBody);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void SendMessage()
{
notify = true;
String messageText = InputMessageText.getText().toString();
if (TextUtils.isEmpty(messageText))
{
Toast.makeText(ChatActivity.this,
"Input message", Toast.LENGTH_SHORT).show();
}
else
{
String message_sender_ref = "Messages/" + messageSenderId + "/" + messageReceiverId;
final String message_receiver_ref = "Messages/" + messageReceiverId + "/" + messageSenderId;
DatabaseReference user_message_key = rootRef.child("Messages").child(messageSenderId)
.child(messageReceiverId).push();
String message_push_id = user_message_key.getKey();
Map messageTextBody = new HashMap();
messageTextBody.put("message", messageText);
messageTextBody.put("isseen", false);
messageTextBody.put("type", "text");
messageTextBody.put("time", ServerValue.TIMESTAMP);
messageTextBody.put("from", messageSenderId);
messageTextBody.put("to", messageReceiverId);
Map messageBodyDetails = new HashMap();
messageBodyDetails.put(message_sender_ref + "/" + message_push_id, messageTextBody);
messageBodyDetails.put(message_receiver_ref + "/" + message_push_id, messageTextBody);
rootRef.updateChildren(messageBodyDetails).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task)
{
if (task.isSuccessful())
{
Toast.makeText(ChatActivity.this, "Message Sent", Toast.LENGTH_SHORT).show();
InputMessageText.setText("");
}
else
{
String message = task.getException().getMessage();
Toast.makeText(ChatActivity.this, "Error:" + message, Toast.LENGTH_SHORT).show();
InputMessageText.setText("");
}
}
});
**i tried sending chat notification with the code below
and that was what triggered the error the messages still get sent but the app crashes and restarts itself.**
final String msg = messageText;
rootRef = FirebaseDatabase.getInstance().getReference("Users").child(fuser.getUid());
rootRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
User user = dataSnapshot.getValue(User.class);
if (notify) {
sendNotification(message_receiver_ref, user.getUsername(), msg);
}
notify = false;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
private void sendNotification(String message_receiver_ref, final String username, final String message)
{
DatabaseReference tokens = FirebaseDatabase.getInstance().getReference("Tokens");
Query query = tokens.orderByKey().equalTo(message_receiver_ref);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
for (DataSnapshot snapshot: dataSnapshot.getChildren())
{
Token token = snapshot.getValue(Token.class);
Data data = new Data(fuser.getUid(), R.mipmap.app_icon, username+": "+message, "New Message",
userid);
Sender sender = new Sender(data, token.getToken());
apiService.sendNotification(sender)
.enqueue(new retrofit2.Callback<MyResponse>() {
#Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response)
{
if (response.code() == 200)
{
if (response.body().success != 1)
{
Toast.makeText(ChatActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onFailure(Call<MyResponse> call, Throwable t)
{
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
}
});
}
}
this is the logcat below
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
at com.paddi.paddi.paddi.ChatActivity.SendMessage(ChatActivity.java:504)
at com.paddi.paddi.paddi.ChatActivity.access$200(ChatActivity.java:58)
at com.paddi.paddi.paddi.ChatActivity$2.onClick(ChatActivity.java:251)
at android.view.View.performClick(View.java:5274)
at android.view.View$PerformClick.run(View.java:21543)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5765)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
You are getting the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
Because your fuser object is not initialized. To solve this, please add the following line of code in your onCreate() method:
fuser = FirebaseAuth.getInstance().getCurrentUser().getUid();

Storing the same Strings on firebase like string1, string2, string3

How can I store equal strings os firebase ?
I have a class on firebase that allows me to add students but I don't know how do I create student1, student2, student3.
This is the code:
bSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!validateForm()) {
return;
}
if (mAuth.getCurrentUser() != null) {
String user_id = mAuth.getCurrentUser().getUid();
final DatabaseReference add_student_db = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id).child("Alunos");
final String anome = aNome.getText().toString();
Map newPost = new HashMap();
newPost.put("Aluno", anome);
add_student_db.setValue(newPost);
}else {
Toast.makeText(AddStudent.this, "Erro ao Adicionar o Nome",
Toast.LENGTH_SHORT).show();
}
}
});
"Aluno" is student in portuguese.
My child stops at "Alunos" and I want it to create inside of "Alunos", "Aluno1", "Aluno2"...
Thanks.
Update:
I solved my problem by doing this:
if (mAuth.getCurrentUser() != null) {
String user_id = mAuth.getCurrentUser().getUid();
final String anome = aNome.getText().toString();
if (filePath != null){
final StorageReference add_student_sr = FirebaseStorage.getInstance().getReference().child("Users").child(user_id).child("Alunos").child(anome);
StorageReference riversRef = add_student_sr.child(anome+"_profilePic.jpg");
riversRef.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getApplicationContext(), "File Uploaded ", Toast.LENGTH_LONG).show();
String downloadUrl = taskSnapshot.getDownloadUrl().toString();
String user_id = mAuth.getCurrentUser().getUid();
final DatabaseReference add_student_db = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id).child("Alunos").child(anome);
Map newPost = new HashMap();
newPost.put("profilePic", downloadUrl);
add_student_db.setValue(newPost);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
}
});
}
One way to handle this is to call push().
When you call push() Firebase creates a new unique location under the location. You can then call setValue on that new location
final DatabaseReference add_student_db = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id).child("Alunos");
final String anome = aNome.getText().toString();
add_student_db.push().setValue(anome);
Every time you run this code a new child node will be created under /Users/$user_id/Alunos with "Aluno": "Name from aNome".

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.

Find out when does Query finish loading the latest added item

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!

Categories

Resources