Relevant activity is not closed - android

I have some weird situation:
I have 3 activities - MainFeed, From where I can post some image with description and then comment on it,
PostActivity, From where I actually upload an image and write some words and then it automatically updated in MainFeed
CommentActivity, From where I just write a comment to relevant post.
The problem is - when I am just scrolling through posts and click to write comment and write one - everything is being updated fine, but once I upload new POST, and then comment on any post, when I click on Update comment button I just moved to Postactivity... I need to click android back button and then I can see all my comments.
As I understand, the postactivity is not closed with finish() method.
Any help, please!!
package com.example.android.bluesky.Posts;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.bluesky.Login.LoginActivity;
import com.example.android.bluesky.Login.RegisterActivity;
import com.example.android.bluesky.R;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import de.hdodenhof.circleimageview.CircleImageView;
import static java.nio.file.Paths.get;
public class CommentsActivity extends AppCompatActivity
{
private ImageView PostCommentButton,BackButton;
private EditText CommentInputText;
private RecyclerView CommentsList;
private String Post_Key, current_user_id;
private long countPosts;
private DatabaseReference UsersRef,PostsRef;
private FirebaseAuth mAuth;
private String currentUserID, CommentRandomKey,post_user_uid_for_comment;
private int PostIntKeyFromMain;
private String comment_user_uid;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comments);
Post_Key=getIntent().getExtras().get("Post_Key").toString();
PostIntKeyFromMain =getIntent().getIntExtra("PostIntKey",5);
post_user_uid_for_comment=getIntent().getExtras().get("post_user_uid_for_comment").toString(); //Coming from mainfeed - commentPostButton
Toast.makeText(this, "received: "+post_user_uid_for_comment, Toast.LENGTH_SHORT).show();
UsersRef= FirebaseDatabase.getInstance().getReference().child("users");
mAuth=FirebaseAuth.getInstance();
current_user_id=mAuth.getCurrentUser().getUid();
currentUserID = mAuth.getCurrentUser().getUid();
PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts").child(Post_Key).child("comments");
BackButton=(ImageView) findViewById(R.id.backArrow) ;
CommentsList = (RecyclerView) findViewById(R.id.comment_list);
CommentsList.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager= new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
CommentsList.setLayoutManager(linearLayoutManager);
CommentInputText=(EditText) findViewById(R.id.comment_input);
PostCommentButton=(ImageView) findViewById(R.id.post_comment_button1);
BackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(CommentsActivity.this,MainFeedActivity.class);
intent.putExtra("PostIntKeyFromComment", PostIntKeyFromMain);
startActivity(intent);
finish();
}
});
PostCommentButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
UsersRef.child(current_user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists())
{
String userFullname=dataSnapshot.child("name").getValue().toString().toLowerCase()+"."+dataSnapshot.child("lastname").getValue().toString();
String userProfileimage=dataSnapshot.child("profileimage").getValue().toString();
ValidateComment(userFullname,userProfileimage);
CommentsList.smoothScrollToPosition(0);
CommentInputText.setText("");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
#Override
protected void onStart()
{
super.onStart();
PostsRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
countPosts = dataSnapshot.getChildrenCount();
countPosts=100000-countPosts;
} else {
countPosts = 100000;
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Query SortCommentsInDecendingOrder = PostsRef.orderByChild("counterC");
FirebaseRecyclerAdapter<Comments,CommentsViewHolder> firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<Comments, CommentsViewHolder>
(
Comments.class,
R.layout.all_comments_layout,
CommentsViewHolder.class,
SortCommentsInDecendingOrder
) {
#Override
protected void populateViewHolder(CommentsViewHolder viewHolder, Comments model, int position)
{
final String CommentKey = getRef(position).getKey();
//viewHolder.setUsername(model.getUsername());
viewHolder.setComment(model.getComment());
viewHolder.setDate(model.getDate());
viewHolder.setTime(model.getTime());
viewHolder.setLastname(model.getLastname());
viewHolder.setProfileimage(model.getProfileimage());
}
};
CommentsList.setAdapter(firebaseRecyclerAdapter);
}
public static class CommentsViewHolder extends RecyclerView.ViewHolder
{
View mView;
String currentUserID;
public CommentsViewHolder(View itemView) {
super(itemView);
mView=itemView;
currentUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();
}
public void setLastname(String lastname)
{
TextView myUserName=(TextView) mView.findViewById(R.id.comment_username1);
myUserName.setText("# " + lastname);
}
public void setComment(String comment)
{
TextView myComment=(TextView) mView.findViewById(R.id.comment_text);
myComment.setText(comment);
}
public void setDate(String date)
{
TextView myDate=(TextView) mView.findViewById(R.id.comment_date);
myDate.setText(date);
}
public void setTime(String time)
{
TextView myTime=(TextView) mView.findViewById(R.id.comment_time);
myTime.setText(time);
}
public void setProfileimage(String profileimage) {
CircleImageView myProfileImage = (CircleImageView) mView.findViewById(R.id.comment_profile_image);
Picasso.get().load(profileimage).into(myProfileImage);
}
}
private void ValidateComment(String userFullname, String userProfileimage, String userCountryimage,String userPartyimage )
{
String commentText=CommentInputText.getText().toString();
if(TextUtils.isEmpty(commentText))
{
Toast.makeText(this, "Please write text", Toast.LENGTH_SHORT).show();
}
else
{
Calendar calForDate = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
final String saveCurrentDate = currentDate.format(calForDate.getTime());
Calendar calForTimeSS = Calendar.getInstance();
SimpleDateFormat currentTimeSS = new SimpleDateFormat("HH:mm:ss");
final String saveCurrentTimeSS = currentTimeSS.format(calForDate.getTime());
Calendar calForTime = Calendar.getInstance();
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm");
final String saveCurrentTime = currentTime.format(calForDate.getTime());
final String RandomKey =current_user_id+ saveCurrentDate + saveCurrentTimeSS;
CommentRandomKey=RandomKey;
HashMap commentsMap = new HashMap();
commentsMap.put("uid",current_user_id);
commentsMap.put("comment",commentText);
commentsMap.put("date",saveCurrentDate);
commentsMap.put("time",saveCurrentTime);
commentsMap.put("lastname",userFullname);
commentsMap.put("counterC", countPosts);
commentsMap.put("profileimage", userProfileimage);
PostsRef.child(RandomKey).updateChildren(commentsMap).addOnCompleteListener(new OnCompleteListener()
{
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful())
{
Toast.makeText(CommentsActivity.this, "You have commented successfully", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(CommentsActivity.this, "Error occured, try again...", Toast.LENGTH_SHORT).show();
}
}
});
CommentsList.smoothScrollToPosition(0);
// Toast.makeText(CommentsActivity.this, ""+CurrentCommentKey, Toast.LENGTH_SHORT).show();
}
}
}
package com.example.android.bluesky.Posts;
import java.lang.Math;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.android.bluesky.R;
import com.example.android.bluesky.Utils.SquareImageView;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import de.hdodenhof.circleimageview.CircleImageView;
public class PostActivity extends AppCompatActivity {
private Toolbar mToolbar;
private ProgressDialog loadingBar;
//private ImageButton SelectPostImage;
private SquareImageView SelectPostImage;
private FloatingActionButton DonePostButton;
private FloatingActionButton UpdatePostButton;
private EditText PostDescription;
private long countPosts;
ImageView PartyImage;
private static final int Gallery_Pick = 1;
private Uri ImageUri;
private String Description;
//referense to store in firebase storage
private StorageReference PostsImagesReference;
private DatabaseReference UsersRef, PostsRef;
private FirebaseAuth mAuth;
private String saveCurrentDate, saveCurrentTime,saveCurrentTimeS, postRandomName, downloadUrl, current_user_id;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
//This two lines is to get current user from database
mAuth = FirebaseAuth.getInstance();
current_user_id = mAuth.getCurrentUser().getUid();
PostsImagesReference = FirebaseStorage.getInstance().getReference();
UsersRef = FirebaseDatabase.getInstance().getReference().child("users");
PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");
UserPhotosRef=FirebaseDatabase.getInstance().getReference().child("user_photos");
PhotosRef=FirebaseDatabase.getInstance().getReference().child("photos");
DonePostButton = (FloatingActionButton) findViewById(R.id.done_post_button);
SelectPostImage = (SquareImageView) findViewById(R.id.select_post_image);
UpdatePostButton = (FloatingActionButton) findViewById(R.id.update_post_button);
PostDescription = (EditText) findViewById(R.id.post_description);
PartyImage=(ImageView) findViewById(R.id.user_party_flag);
loadingBar = new ProgressDialog(this);
mToolbar = (Toolbar) findViewById(R.id.update_post_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Update post");
UpdatePostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onSelectImageClick(SelectPostImage);
// OpenGallery();
}
});
//UpdatePostButton.setOnClickListener(new View.OnClickListener() {
DonePostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ValidatePostInfo();
}
});
}
public void onSelectImageClick(View view) {
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setActivityTitle("My Crop")
//.setCropShape(CropImageView.CropShape.RECTANGLE)
.setCropMenuCropButtonTitle("Done")
//.setMaxCropResultSize(1000, 1000)
.setMinCropWindowSize(2000, 2000)
.setMinCropResultSize(2000, 2000)
.setRequestedSize(800, 800)
.setAspectRatio(1,1)
.setCropMenuCropButtonIcon(R.drawable.ic_checkmark)
.start(this);
//.startActivityForResult(galleryIntent,Gallery_Pick);
// / .start(getContext(),this);
}
private void ValidatePostInfo() {
//This Description var is using only in this method, there is another one for global use
Description = PostDescription.getText().toString();
if (ImageUri == null) {
Toast.makeText(this, "Please select post image", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(Description)) {
Toast.makeText(this, "Please say something about your image", Toast.LENGTH_SHORT).show();
} else {
loadingBar.setTitle("Add new post");
loadingBar.setMessage("Please wait, while we are updating your new post...");
loadingBar.show();
loadingBar.setCanceledOnTouchOutside(true);
//Code for storing image in firebase storage and database
StoringImageToFirebaseStorage();
}
}
private void StoringImageToFirebaseStorage() {
//assigning random uid for image based on date and time
Calendar calForDate = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
saveCurrentDate = currentDate.format(calForDate.getTime());
Calendar calForTime = Calendar.getInstance();
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm");
saveCurrentTime = currentTime.format(calForDate.getTime());
Calendar calForTimeS = Calendar.getInstance();
SimpleDateFormat currentTimeS = new SimpleDateFormat("HH:mm:ss");
saveCurrentTimeS = currentTime.format(calForDate.getTime());
postRandomName = saveCurrentDate + saveCurrentTimeS;
StorageReference filepath = PostsImagesReference.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");
//Now let's store the image to firebase storage
filepath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
downloadUrl = task.getResult().getDownloadUrl().toString();
Toast.makeText(PostActivity.this, "Image uploaded successfully to Storage", Toast.LENGTH_SHORT).show();
SavingPostInformationToDatabase();
} else {
String message = task.getException().getMessage();
Toast.makeText(PostActivity.this, "Error occured: " + message, Toast.LENGTH_SHORT).show();
}
}
});
}
private void SavingPostInformationToDatabase()
{
PostsRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
countPosts = dataSnapshot.getChildrenCount();
// countForPhotos="photo_"+countPosts;
} else {
countPosts = 0;
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
UsersRef.child(current_user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
//Two lines of code to retreive and assign to var the users fullname and uid of it profile image
String userFullName = "#" + dataSnapshot.child("name").getValue().toString().toLowerCase() + "." + dataSnapshot.child("lastname").getValue().toString();
String userProfileImage = dataSnapshot.child("profileimage").getValue().toString();
//Creating database for storing user posts data including users data
HashMap postsMap = new HashMap();
postsMap.put("uid", current_user_id);
postsMap.put("description", Description);
postsMap.put("postimage", downloadUrl);
postsMap.put("profileimage", userProfileImage);
postsMap.put("fullname", userFullName);
postsMap.put("counter", countPosts);
//Updating database of users post photo only
UserPhotosRef.child(current_user_id).child(current_user_id + postRandomName).updateChildren(postsMap_users_photo);
PostsRef.child(current_user_id + postRandomName).updateChildren(postsMap)
.addOnCompleteListener(new OnCompleteListener()
{
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
SendUserToMainActivity();
Toast.makeText(PostActivity.this, "The post is updated successfully!", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
finish();
} else {
Toast.makeText(PostActivity.this, "Error occurred while updating your post!", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
} else {
String userFullName = dataSnapshot.child("lastname").getValue().toString();
Toast.makeText(PostActivity.this, "You have a problem!!! " + userFullName, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK)
{
SelectPostImage.setImageURI(result.getUri());
Toast.makeText(this, "Cropping successful, Sample: " + result.getSampleSize(), Toast.LENGTH_LONG)
.show();
Uri resultUri = result.getUri();
ImageUri = resultUri;
}
else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Toast.makeText(this, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show();
}
}
}
private void SendUserToMainActivity() {
Intent intent = new Intent(PostActivity.this, MainFeedActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
}

The issue was with sendActivity inside Firebase initialization...

Related

why currentonline user is Null

currentonlineuser which I defined in Prevelent is returning null when clicking in cart button in details. class the getPhone is not returing anything even after initilizing it
this is code for details activity
private void addtocart() {
String saveCurrentDate, saveCurrentTime;
Calendar calForDate = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("MMM dd, yyyy");
saveCurrentDate = currentDate.format(calForDate.getTime());
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss a");
saveCurrentTime = currentTime.format(calForDate.getTime());
final DatabaseReference cartListRef = FirebaseDatabase.getInstance().getReference().child("Cart List");
final HashMap<String, Object> cartMap = new HashMap<>();
cartMap.put("productName",nameholder.getText().toString());
cartMap.put("productPrice",emailholder.getText().toString());
cartMap.put("date",saveCurrentDate);
cartMap.put("time",saveCurrentTime);
cartMap.put("quantity",quantity.getText().toString());
if (**Prevalent.currentonlineUsers** != null) {
String phone = **Prevalent.currentonlineUsers.getPhone**();
cartListRef.child("Admin View").child(`Prevalent.currentonlineUsers.getPhone`())
.child("Products").child("productName")
.updateChildren(cartMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
cartListRef.child("user View").child(**Prevalent.currentonlineUsers.getPhone**())
.child("Products").child("productName")
.updateChildren(cartMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(details.this, "Added to cart", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(details.this,MainActivity.class);
startActivity(intent);
}
});
}
}
});
} else {
Toast.makeText(this, "ERROR", Toast.LENGTH_SHORT).show();
}
package com.example.register.Prevalent;
import com.example.register.Model.Users;
public class Prevalent {
public static Users currentonlineUsers;
public static final String UserPhoneKey = "UserPhone";
public static final String UserPasswordKey = "UserPassword";
}
this is the code of Users class
package com.example.register.Model;
public class Users {
private String name,phone,password;
public Users() {
}
public Users(String name, String phone, String password) {
this.name = name;
this.phone = phone;
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
this is the code of login class
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.register.Model.Users;
import com.example.register.Prevalent.Prevalent;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import io.paperdb.Paper;
public class login extends AppCompatActivity {
private EditText InputPhoneNumber,InputPassword;
private ProgressDialog loadingBar;
private com.rey.material.widget.CheckBox chkbox;
private String parentDbName = "Users";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button loginButton = (Button) findViewById(R.id.button);
InputPassword = (EditText) findViewById(R.id.password);
InputPhoneNumber = (EditText) findViewById(R.id.username);
loadingBar = new ProgressDialog(this);
chkbox = (com.rey.material.widget.CheckBox) findViewById(R.id.rembemberme);
Paper.init(this);
loginButton.setOnClickListener((new View.OnClickListener() {
#Override
public void onClick(View view) {
LoginUser();
}
}));
}
private void LoginUser() {
String phone = InputPhoneNumber.getText().toString();
String password = InputPassword.getText().toString();
if(TextUtils.isEmpty(phone)){
Toast.makeText(this, "Please write your phone", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(phone)){
Toast.makeText(this, "Please write your password", Toast.LENGTH_SHORT).show();
}
else {
loadingBar.setTitle("Login Account");
loadingBar.setMessage("wait");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
AllowAccessToAccount(phone,password);
}
}
private void AllowAccessToAccount(String phone, String password) {
final DatabaseReference RootRef;
RootRef = FirebaseDatabase.getInstance().getReference();
RootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.child(parentDbName).child(phone).exists()){
Paper.book().write(Prevalent.UserPhoneKey,phone);
Paper.book().write(Prevalent.UserPasswordKey,password);
Users usersdata = snapshot.child(parentDbName).child(phone).getValue(Users.class);
if(usersdata.getPhone().equals(phone)){
if(usersdata.getPassword().equals(password)){
Toast.makeText(login.this, "Logged IN Successfully", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
Intent intent = new Intent(login.this,test.class);
startActivity(intent);
}
}
else{
Toast.makeText(login.this, "Phone number do not exists", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
Toast.makeText(login.this, "create new acc.", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
this is the code of register if in case the error is related to this
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.Navigator;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.HashMap;
public class register extends AppCompatActivity {
private Button CreateAccountButton;
private EditText InputName,InputPhoneNumber,InputPassword;
private ProgressDialog loadingBar;
Button exp;
//create obj of Databaserefrence to access firebase RealTime Database
DatabaseReference databaseReference ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CreateAccountButton =(Button) findViewById(R.id.sign);
InputName =(EditText) findViewById(R.id.Name);
InputPassword=(EditText) findViewById(R.id.password);
InputPhoneNumber=(EditText) findViewById(R.id.password);
loadingBar = new ProgressDialog(this);
CreateAccountButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CreateAccount();
}
});
}
private void CreateAccount() {
String name = InputName.getText().toString();
String phone = InputPhoneNumber.getText().toString();
String password = InputPassword.getText().toString();
if(TextUtils.isEmpty(name)){
Toast.makeText(this, "Please write your name", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(phone)){
Toast.makeText(this, "Please write your phone", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(phone)){
Toast.makeText(this, "Please write your password", Toast.LENGTH_SHORT).show();
}
else {
loadingBar.setTitle("Create Account");
loadingBar.setMessage("wait");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
ValidatephoneNumber(name,phone,password);
}
}
private void ValidatephoneNumber(String name, String phone, String password)
{
final DatabaseReference RootRef;
RootRef = FirebaseDatabase.getInstance().getReference();
RootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot datasnapshot) {
if(!(datasnapshot.child("Users").child(phone).exists())){
HashMap<String,Object>userdataMap=new HashMap<>();
userdataMap.put("phone",phone);
userdataMap.put("password",password);
userdataMap.put("name",name);
RootRef.child("Users").child(phone).updateChildren(userdataMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(register.this, "ACCOUNT CREATED", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
Intent intent = new Intent(register.this,test.class);
startActivity(intent);
}
else {
Toast.makeText(register.this, "Networ Error", Toast.LENGTH_SHORT).show();
}
}
});
}
else {
Toast.makeText(register.this, "phone number already exists", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
Toast.makeText(register.this, "Enter new number", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
exp = (Button) findViewById(R.id.login);
exp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(register.this,login.class);
startActivity(intent);
}
});
}
}
it was giving the Error
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.register.Model.Users.getPhone()' on a null object reference
then I applied null check
its showing ERROR after clicking addtocart

How can I display last message time of firebase at the top in recyclerView in AndroidStudio [duplicate]

This question already has answers here:
Android - Client-side sorting with FirebaseRecyclerAdapter
(1 answer)
FirebaseRecyclerPagingAdapter - sort list by date
(1 answer)
Cannot retrieve data in ascending order
(2 answers)
Firebase Data Desc Sorting in Android
(19 answers)
How to arrange firebase database data in ascending or descending order?
(2 answers)
Closed 8 months ago.
As now i am working on a chat application, here i have a problem that how can i display my last recent chat on the top of the recyclerview in ChatlistFragment,
for example if i had recently sent my last message to any user they have to displayed at the top of my recyclerview, here is my code
package com.micoder.whatsappclone;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class ChatsFragment extends Fragment {
private View PrivateChatsView;
private RecyclerView chatsList;
private DatabaseReference ChatsRef, UsersRef;
private FirebaseAuth mAuth;
private String currentUserID;
FloatingActionMenu fabMenu;
FloatingActionButton fabSettings, fabShare, fabContactDev;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
PrivateChatsView = inflater.inflate(R.layout.fragment_chats, container, false);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
ChatsRef = FirebaseDatabase.getInstance().getReference().child("Messages").child(currentUserID);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
chatsList = (RecyclerView) PrivateChatsView.findViewById(R.id.chats_list);
chatsList.setLayoutManager(new LinearLayoutManager(getContext()));
fabOptions();
return PrivateChatsView;
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerOptions<Contacts> options =
new FirebaseRecyclerOptions.Builder<Contacts>()
.setQuery(ChatsRef, Contacts.class)
.build();
FirebaseRecyclerAdapter<Contacts, ChatsViewHolder> adapter =
new FirebaseRecyclerAdapter<Contacts, ChatsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull ChatsViewHolder holder, int position, #NonNull Contacts model) {
final String usersIDs = getRef(position).getKey();
final String[] retImage = {"default_image"};
UsersRef.child(usersIDs).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child("userState").hasChild("state")) {
String state = dataSnapshot.child("userState").child("state").getValue().toString();
if (state.equals("online")) {
holder.onlineIcon.setVisibility(View.VISIBLE);
}
else if (state.equals("offline")) {
holder.onlineIcon.setVisibility(View.INVISIBLE);
}
}
else {
holder.onlineIcon.setVisibility(View.INVISIBLE);
}
if (dataSnapshot.exists()) {
if (dataSnapshot.hasChild("image")) {
retImage[0] = dataSnapshot.child("image").getValue().toString();
Picasso.get().load(retImage[0]).placeholder(R.drawable.profile_image).into(holder.profileImage);
}
final String retName = dataSnapshot.child("name").getValue().toString();
holder.userName.setText(retName);
if (dataSnapshot.child("userState").hasChild("state")) {
String state = dataSnapshot.child("userState").child("state").getValue().toString();
String date = dataSnapshot.child("userState").child("date").getValue().toString();
String time = dataSnapshot.child("userState").child("time").getValue().toString();
if (state.equals("online")) {
holder.userStatus.setText("online");
}
else if (state.equals("offline")) {
holder.userStatus.setText("Last Seen: " + date + " " + time);
}
}
else {
holder.userStatus.setText("offline");
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent chatIntent = new Intent(getContext(), ChatActivity.class);
chatIntent.putExtra("visit_user_id", usersIDs);
chatIntent.putExtra("visit_user_name", retName);
chatIntent.putExtra("visit_image", retImage[0]);
startActivity(chatIntent);
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#NonNull
#Override
public ChatsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.users_display_chats_layout, viewGroup, false);
return new ChatsViewHolder(view);
}
};
chatsList.setAdapter(adapter);
adapter.startListening();
}
public static class ChatsViewHolder extends RecyclerView.ViewHolder {
CircleImageView profileImage;
TextView userName, userStatus;
ImageView onlineIcon;
public ChatsViewHolder(#NonNull View itemView) {
super(itemView);
profileImage = itemView.findViewById(R.id.users_profile_image);
userName = itemView.findViewById(R.id.user_profile_name);
userStatus = itemView.findViewById(R.id.user_status);
onlineIcon = itemView.findViewById(R.id.user_online_status);
}
}
public void fabOptions() {
//FAB
fabMenu=PrivateChatsView.findViewById(R.id.fabMenu);
fabSettings=PrivateChatsView.findViewById(R.id.fabSettings);
fabContactDev=PrivateChatsView.findViewById(R.id.fabContactDev);
fabShare=PrivateChatsView.findViewById(R.id.fabShare);
fabShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "My application name");
String shareMessage= "\nLet me recommend you this application\n\n";
shareMessage = shareMessage + "https://play.google.com/store/apps/developer?id=MI_CODER"+"\n\n";
shareIntent.putExtra(Intent.EXTRA_TEXT, shareMessage);
startActivity(Intent.createChooser(shareIntent, "choose one"));
} catch(Exception e) {
//e.toString();
}
fabMenu.close(true);
}
});
fabSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Settings", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getActivity(),SettingsActivity.class));
fabMenu.close(true);
}
});
fabContactDev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(),"Loading...",Toast.LENGTH_SHORT).show();
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://micoder-dev.github.io/Resume-Page/"));
startActivity(browserIntent);
fabMenu.close(true);
}
});
}
}
if you need to refer my complete source code you can get here => https://github.com/Micoder-dev/ChatApp-FE-UI.git
I think this will help you to make it easier to get a solution.

Firebase error after published to play store [duplicate]

This question already has answers here:
Firebase No properties to serialize found on class
(12 answers)
Firebase release apk not loading data
(3 answers)
Firebase AndroidChat release build error
(3 answers)
Closed 2 years ago.
On my android studio debug theres nothing problem, but when i publish the app to playstore my app was close after splashscreen. my apps using firebase, and i have to added SHA-1 from playstore to my firebase project. but still cant crash :
this error i got from play console :
com.google.firebase.database.DatabaseException:
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.<init> (CustomClassMapper.java:11)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.loadOrCreateBeanMapperForClass (CustomClassMapper.java)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean (CustomClassMapper.java:4)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass (CustomClassMapper.java:4)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass (CustomClassMapper.java:8)
at com.google.firebase.database.DataSnapshot.getValue (DataSnapshot.java:8)
at com.kepulcorporation.kepul.HomeFragment$10.onDataChange (HomeFragment.java:8)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent (ValueEventRegistration.java:2)
at com.google.firebase.database.core.view.DataEvent.fire (DataEvent.java)
at com.google.firebase.database.core.view.EventRaiser$1.run (EventRaiser.java:6)
at android.os.Handler.handleCallback (Handler.java:751)
at android.os.Handler.dispatchMessage (Handler.java:95)
at android.os.Looper.loop (Looper.java:154)
at android.app.ActivityThread.main (ActivityThread.java:6121)
at java.lang.reflect.Method.invoke (Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:779)
this is my main activity :
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Registry;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.module.AppGlideModule;
import com.firebase.ui.storage.images.FirebaseImageLoader;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.storage.StorageReference;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private ActionBar actionBar;
private NestedScrollView nested_scroll_view;
private BottomSheetBehavior mBehavior;
private BottomSheetDialog mBottomSheetDialog;
private View bottom_sheet;
private HorizontalScrollView horizontalScrollView;
private Fragment fragment;
private Fragment fragmenthome;
private SessionManager sessionManager;
RelativeLayout toolbar;
LinearLayout content;
NestedScrollView scrolllayout;
ImageView home_icon, transaksi_icon, bantuan_icon, akun_icon;
TextView home_text, transaksi_text, bantuan_text, akun_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
content = findViewById(R.id.list_category_item_dashboard);
scrolllayout = findViewById(R.id.nested_scroll_view);
//Set Theme
Tools.setSystemBarColor(this, R.color.colorPrimary);
sessionManager = new SessionManager(this);
sessionManager.checkLogin(this);
home_icon = findViewById(R.id.home_icon);
transaksi_icon = findViewById(R.id.transaksi_icon);
bantuan_icon = findViewById(R.id.bantuan_icon);
akun_icon = findViewById(R.id.akun_icon);
home_text = findViewById(R.id.home_text);
transaksi_text = findViewById(R.id.transaksi_text);
bantuan_text = findViewById(R.id.bantuan_text);
akun_text = findViewById(R.id.akun_text);
FirebaseMessaging.getInstance().getToken()
.addOnCompleteListener(new OnCompleteListener<String>() {
#Override
public void onComplete(#NonNull Task<String> task) {
if (!task.isSuccessful()) {
// Toast.makeText(MainActivity.this, "Fetching FCM registration token failed", Toast.LENGTH_SHORT).show();
return;
}
// Get new FCM registration token
String token = task.getResult();
if(sessionManager.isLoggin())
{
save_fcm(token);
}
}
});
initComponent();
}
public void save_fcm(String token){
HashMap<String, String> user;
sessionManager = new SessionManager(MainActivity.this);
user = sessionManager.getUserDetail();
String email = user.get("EMAIL");
String convertemail = email.replaceAll("\\.", "_");
FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference tableuser = database.getReference("Users");
tableuser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String email = user.get("EMAIL");
String convertemail = email.replaceAll("\\.", "_");
Users users = snapshot.child(convertemail).getValue(Users.class);
Map<String, Object> updates = new HashMap<String,Object>();
updates.put("address", users.getAddress());
updates.put("email", email);
updates.put("name", users.getName());
updates.put("password", users.getPassword());
updates.put("phone", users.getPhone());
updates.put("photo_profile_path", users.getPhoto_profile_path());
updates.put("role_id", users.getRole_id());
updates.put("point", users.getPoint());
updates.put("token", token);
updates.put("promosipush", users.getPromosipush());
updates.put("promosiemail", users.getPromosiemail());
updates.put("statuspush", users.getStatuspush());
updates.put("statusemail", users.getStatusemail());
tableuser.child(convertemail).setValue(updates);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void initComponent() {
nested_scroll_view = (NestedScrollView) findViewById(R.id.nested_scroll_view);
fragment = new HomeFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment,
fragment.getClass().getSimpleName()).commit();
home_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.colorPrimary));
home_text.setTextColor(this.getResources().getColor(R.color.colorPrimary));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
} else {
Toast.makeText(getApplicationContext(), item.getTitle(), Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
public void toHome(View view) {
ViewAnimation.fadeOutIn(nested_scroll_view);
if (sessionManager.isLoggin()){
fragment = new HomeFragment();
}
else {
fragment = new HomeFragment();
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment,
fragment.getClass().getSimpleName()).commit();
home_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.colorPrimary));
home_text.setTextColor(this.getResources().getColor(R.color.colorPrimary));
transaksi_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
transaksi_text.setTextColor(this.getResources().getColor(R.color.text));
bantuan_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
bantuan_text.setTextColor(this.getResources().getColor(R.color.text));
akun_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
akun_text.setTextColor(this.getResources().getColor(R.color.text));
}
public void toTransaksi(View view) {
ViewAnimation.fadeOutIn(nested_scroll_view);
if (sessionManager.isLoggin()){
fragment = new TransaksiloginFragment();
}
else {
fragment = new TransaksiFragment();
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment,
fragment.getClass().getSimpleName()).commit();
home_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
home_text.setTextColor(this.getResources().getColor(R.color.text));
transaksi_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.colorPrimary));
transaksi_text.setTextColor(this.getResources().getColor(R.color.colorPrimary));
bantuan_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
bantuan_text.setTextColor(this.getResources().getColor(R.color.text));
akun_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
akun_text.setTextColor(this.getResources().getColor(R.color.text));
}
public void toBantuan(View view){
ViewAnimation.fadeOutIn(nested_scroll_view);
if (sessionManager.isLoggin()){
fragment = new BantuanFragment();
}
else {
fragment = new BantuanFragment();
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment,
fragment.getClass().getSimpleName()).commit();
home_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
home_text.setTextColor(this.getResources().getColor(R.color.text));
transaksi_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
transaksi_text.setTextColor(this.getResources().getColor(R.color.text));
bantuan_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.colorPrimary));
bantuan_text.setTextColor(this.getResources().getColor(R.color.colorPrimary));
akun_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
akun_text.setTextColor(this.getResources().getColor(R.color.text));
}
public void toAkun(View view){
ViewAnimation.fadeOutIn(nested_scroll_view);
if (sessionManager.isLoggin()){
fragment = new AkunLoginFragment();
}
else {
fragment = new AkunFragment();
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment,
fragment.getClass().getSimpleName()).commit();
home_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
home_text.setTextColor(this.getResources().getColor(R.color.text));
transaksi_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
transaksi_text.setTextColor(this.getResources().getColor(R.color.text));
bantuan_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
bantuan_text.setTextColor(this.getResources().getColor(R.color.text));
akun_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.colorPrimary));
akun_text.setTextColor(this.getResources().getColor(R.color.colorPrimary));
}
public void toSell(View view) {
ViewAnimation.fadeOutIn(nested_scroll_view);
if (sessionManager.isLoggin()){
startActivity(new Intent(MainActivity.this, JualsampahActivity.class));
}
else {
fragment = new JualFragment();
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment,
fragment.getClass().getSimpleName()).commit();
home_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
home_text.setTextColor(this.getResources().getColor(R.color.text));
transaksi_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
transaksi_text.setTextColor(this.getResources().getColor(R.color.text));
bantuan_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
bantuan_text.setTextColor(this.getResources().getColor(R.color.text));
akun_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
akun_text.setTextColor(this.getResources().getColor(R.color.text));
}
}
and this my HomeFragment :
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.media.Image;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.github.islamkhsh.CardSliderViewPager;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import org.w3c.dom.Text;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
import ru.tinkoff.scrollingpagerindicator.ScrollingPagerIndicator;
public class HomeFragment extends Fragment {
CardSliderViewPager cardSliderViewPager;
private List<Category>listData;
private List<Produk>listData1;
private List<SliderData>sliderData;
private RecyclerView rv;
private CategoryAdapter adapter;
private ProdukAdapter adapter1;
private SliderAdapter sliderAdapter;
private RecyclerView recyclerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View root = inflater.inflate(R.layout.fragment_home, container, false);
cardSliderViewPager = root.findViewById(R.id.viewPager);
recyclerView = root.findViewById(R.id.product_recyclerview);
rv = root.findViewById(R.id.category_recyclerview);
rv.setHasFixedSize(true);
rv.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
listData=new ArrayList<>();
listData1 = new ArrayList<>();
sliderData = new ArrayList<>();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference table = database.getReference("Category");
table.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(isAdded())
{
listData.clear();
for (DataSnapshot npsnapshot : snapshot.getChildren()){
Category l = npsnapshot.getValue(Category.class);
listData.add(l);
}
adapter=new CategoryAdapter(listData);
rv.setAdapter(adapter);
ScrollingPagerIndicator recyclerIndicator = root.findViewById(R.id.indicator2);
recyclerIndicator.attachToRecyclerView(rv);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
final SessionManager sessionManager = new SessionManager(getActivity());
HashMap<String, String> user = sessionManager.getUserDetail();
String email = user.get("EMAIL");
if(!sessionManager.isLoggin())
{
LinearLayout not_login = root.findViewById(R.id.not_login);
LinearLayout login = root.findViewById(R.id.login);
not_login.setVisibility(View.VISIBLE);
login.setVisibility(View.GONE);
}
else {
LinearLayout not_login = root.findViewById(R.id.not_login);
LinearLayout login = root.findViewById(R.id.login);
not_login.setVisibility(View.GONE);
login.setVisibility(View.VISIBLE);
FirebaseDatabase databaseuser = FirebaseDatabase.getInstance();
DatabaseReference tableuseruser = databaseuser.getReference("Users");
tableuseruser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(isAdded())
{
String convertemail = email.toString().replaceAll("\\.", "_").toString();
Users users = snapshot.child(convertemail).getValue(Users.class);
TextView point = root.findViewById(R.id.profile_point);
TextView name = root.findViewById(R.id.profile_name);
CircleImageView circleImageView = root.findViewById(R.id.profile_image);
name.setText(user.get("NAME"));
point.setText(users.getPoint().toString() + " Point");
if (user.get("PHOTO_PROFILE_PATH").equals(""))
{
Glide.with(getContext()).load("https://cdn.business2community.com/wp-content/uploads/2017/08/blank-profile-picture-973460_640.png").into(circleImageView);
}
else {
Glide.with(getContext()).load(user.get("PHOTO_PROFILE_PATH")).into(circleImageView);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
getbanner();
FirebaseDatabase databasepro = FirebaseDatabase.getInstance();
DatabaseReference tablepro = databasepro.getReference("Product");
tablepro.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(isAdded())
{
listData1.clear();
for (DataSnapshot npsnapshot : snapshot.getChildren()){
Produk l = npsnapshot.getValue(Produk.class);
listData1.add(l);
}
adapter1 = new ProdukAdapter((ArrayList<Produk>) listData1);
recyclerView.setAdapter(adapter1);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
LinearLayout jual = root.findViewById(R.id.btn_jual);
LinearLayout sedekah = root.findViewById(R.id.btn_sedekah);
LinearLayout baitullah = root.findViewById(R.id.btn_baitullah);
ImageView notif = root.findViewById(R.id.notif);
ReddotNotif reddotNotif = new ReddotNotif(getContext());
if(reddotNotif.isRedDot())
{
notif.setImageResource(R.drawable.ic_notify);
}
else {
notif.setImageResource(R.drawable.ic_notif);
}
notif.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
reddotNotif.logout();
startActivity(new Intent(getActivity(), HistorynotificationActivity.class));
}
});
baitullah.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(sessionManager.isLoggin())
{
startActivity(new Intent(getActivity(), MenujubaitullahActivity.class));
}
else {
Intent intent = new Intent(getActivity(), MustloginActivity.class);
intent.putExtra("type", "baitullah");
startActivity(intent);
}
}
});
jual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(sessionManager.isLoggin())
{
startActivity(new Intent(getActivity(), JualsampahActivity.class));
}
else {
Intent intent = new Intent(getActivity(), MustloginActivity.class);
intent.putExtra("type", "jual");
startActivity(intent);
}
}
});
sedekah.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Boolean login = false;
if(sessionManager.isLoggin())
{
startActivity(new Intent(getActivity(), SedekahsampahActivity.class));
}
else {
Intent intent = new Intent(getActivity(), MustloginActivity.class);
intent.putExtra("type", "sedekah");
startActivity(intent);
}
}
});
Button login = root.findViewById(R.id.login_button);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), LoginActivity.class));
}
});
TextView FAQ = root.findViewById(R.id.faq);
String FAQTEXT = "Untuk informasi lebih lanjut, kunjungi halaman FAQ. <font color=#0098FF>di sini </font> ";
FAQ.setText(Html.fromHtml(FAQTEXT));
FAQ.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getActivity(), FaqActivity.class));
}
});
return root;
}
private void getbanner() {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference table = database.getReference("Banner");
table.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(isAdded())
{
sliderData.clear();
for (DataSnapshot npsnapshot : snapshot.getChildren()){
SliderData l = npsnapshot.getValue(SliderData.class);
sliderData.add(l);
}
sliderAdapter = new SliderAdapter((ArrayList<SliderData>) sliderData);
cardSliderViewPager.setAdapter(sliderAdapter);
cardSliderViewPager.setSmallScaleFactor(0.9f);
cardSliderViewPager.setSmallAlphaFactor(0.5f);
cardSliderViewPager.setAutoSlideTime(5);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
this my Category class :
public class Category {
private String id;
private String name;
private String picture_path;
public Category(){
}
public Category(String id, String name, String picture_path) {
this.id = id;
this.name = name;
this.picture_path = picture_path;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPicture_path() {
return picture_path;
}
public void setPicture_path(String picture_path) {
this.picture_path = picture_path;
}
}
and this category at database :
category database
can you help me please, I've been looking for a week where it went wrong, but still can't find it.

How to get the specific key in realtime database?

I am currently having a trouble on deleting a specific data from my firebase. So basically I have recyclerview wherein my datas are displayed and I have a button in each data display there and that's EDIT button. Whenever I try to click the EDIT button it should intent me to another activity with the same data displayed in the recyclerview and there's a another button displayed there and that's DELETE button. But whenever I try to click the delete button, it deletes all the data from the child. I only need to DELETE the selected ID/Data that is passing when intent occurs.
Edit.
EditResearch.java
package com.example.citeresearchrepository.AdminPackage;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.citeresearchrepository.Model.ResearchRepository;
import com.example.citeresearchrepository.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
public class EditResearchActivity extends AppCompatActivity {
EditText editfilehandler_et,editrepo_title,editrepo_description,editrepo_currentdate;
Button editrepo_savebtn;
ImageView backbtn_editresearch;
DatabaseReference databaseReference;
FirebaseDatabase firebaseDatabase;
StorageReference storageReference;
String researchtitle,researchdate,researchname,researchdescription;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_research);
editfilehandler_et = findViewById(R.id.editfilehandler_et);
editrepo_title = findViewById(R.id.editrepo_title);
editrepo_description = findViewById(R.id.editrepo_description);
editrepo_currentdate = findViewById(R.id.editrepo_currentdate);
editrepo_savebtn = findViewById(R.id.editrepo_savebtn);
backbtn_editresearch = findViewById(R.id.backbtn_editresearch);
Intent intent = getIntent();
researchtitle = intent.getStringExtra("researchtitle");
researchdate = intent.getStringExtra("researchdate");
researchname = intent.getStringExtra("researchname");
researchdescription = intent.getStringExtra("researchdescription");
databaseReference = FirebaseDatabase.getInstance().getReference("ResearchRepository");
storageReference = FirebaseStorage.getInstance().getReference();
editfilehandler_et.setText(researchname);
editrepo_title.setText(researchtitle);
editrepo_currentdate.setText(researchdate);
editrepo_description.setText(researchdescription);
editrepo_savebtn.setEnabled(false);
editfilehandler_et.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectPDF();
}
});
/* Update Files */
backbtn_editresearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), AdminResearchRepoActivity.class));
}
});
}
private void selectPDF(){
Intent intent = new Intent();
intent.setType("application/pdf");
intent.setAction(intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "PDF FILE SELECTED"), 12);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==12 && resultCode == RESULT_OK && data!=null && data.getData()!=null){
editrepo_savebtn.setEnabled(true);
editfilehandler_et.setText(data.getDataString().substring(data.getDataString().lastIndexOf("/") + 1));
editrepo_savebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deletePreviousImage();
uploadResearch(data.getData());
}
});
}
}
private void deleteSelectedRow(){
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("ResearchRepository");
databaseReference.removeValue();
}
private void uploadResearch(Uri data) {
final String filecapture = editfilehandler_et.getText().toString();
final String researchtitle = editrepo_title.getText().toString();
final String researchdescription = editrepo_description.getText().toString();
final String researchtimeline = editrepo_currentdate.getText().toString();
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("File Uploading...");
progressDialog.show();
StorageReference reference = storageReference.child("ResearchRepository" +System.currentTimeMillis() + ".pdf");
reference.putFile(data).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while(!uriTask.isComplete());
Uri uri = uriTask.getResult();
ResearchRepository researchRepository = new ResearchRepository(filecapture,researchtitle,researchdescription,researchtimeline,uri.toString());
databaseReference.child(databaseReference.push().getKey()).setValue(researchRepository);
Toast.makeText(EditResearchActivity.this, "File Uploaded", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
editfilehandler_et.setText("");
editrepo_title.setText("");
editrepo_currentdate.setText("");
editrepo_description.setText("");
startActivity(new Intent(getApplicationContext(), AdminResearchRepoActivity.class));
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
double progress = (100*snapshot.getBytesTransferred())/snapshot.getTotalByteCount();
progressDialog.setMessage("File Uploading..."+(int)progress+"%");
}
});
}
private void deletePreviousImage(){
StorageReference reference = FirebaseStorage.getInstance().getReference().child(researchtitle);
reference.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(EditResearchActivity.this, "Previous File Deleted", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(EditResearchActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
AdminResearchRepoActivity.java
package com.example.citeresearchrepository.AdminPackage;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.citeresearchrepository.AdminAdapter.AdminRepoAdapter;
import com.example.citeresearchrepository.Model.ResearchRepository;
import com.example.citeresearchrepository.R;
import com.example.citeresearchrepository.ViewHolder.AdminResearchRepositoryViewHolder;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class AdminResearchRepoActivity extends AppCompatActivity {
ImageView adminrepo_backbtn;
RecyclerView reporecycler;
FloatingActionButton addresearch_btn;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
AdminRepoAdapter adminRepoAdapter;
ArrayList<ResearchRepository> researchRepositoryArrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_research_repo);
// Buttons
adminrepo_backbtn = findViewById(R.id.backbtn_adminrepo);
addresearch_btn = findViewById(R.id.addresearch_btn);
addresearch_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), AddResearchActivity.class));
}
});
adminrepo_backbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), WelcomeAdminActivity.class));
}
});
// Recycler
reporecycler = findViewById(R.id.reporecycler);
reporecycler.setLayoutManager(new LinearLayoutManager(this));
// Firebase Connection
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference().child("ResearchRepository");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
researchRepositoryArrayList = new ArrayList<ResearchRepository>();
for (DataSnapshot dataSnapshot: snapshot.getChildren()){
ResearchRepository researchRepository = dataSnapshot.getValue(ResearchRepository.class);
researchRepositoryArrayList.add(researchRepository);
}
adminRepoAdapter = new AdminRepoAdapter(AdminResearchRepoActivity.this,researchRepositoryArrayList);
reporecycler.setAdapter(adminRepoAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(AdminResearchRepoActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
AdminRepoAdapter.java
package com.example.citeresearchrepository.AdminAdapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.citeresearchrepository.AdminPackage.EditResearchActivity;
import com.example.citeresearchrepository.Model.ResearchRepository;
import com.example.citeresearchrepository.R;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class AdminRepoAdapter extends RecyclerView.Adapter<AdminRepoAdapter.AdminViewHolder> {
Context context;
ArrayList<ResearchRepository> researchRepositories;
public AdminRepoAdapter(Context c, ArrayList<ResearchRepository> repositories){
context = c;
researchRepositories = repositories;
}
#NonNull
#Override
public AdminViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new AdminViewHolder(LayoutInflater.from(context).inflate(R.layout.admineditrepo_row,parent,false));
}
#Override
public void onBindViewHolder(#NonNull AdminViewHolder holder, final int position) {
holder.researchtitle_view.setText(researchRepositories.get(position).getResearchtitle());
holder.researchdate_view.setText(researchRepositories.get(position).getResearchtimeline());
holder.researchname_view.setText(researchRepositories.get(position).getFilecapture());
holder.researchdescription_view.setText(researchRepositories.get(position).getResearchdescription());
holder.btnpdf_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, EditResearchActivity.class);
intent.putExtra("researchtitle",researchRepositories.get(position).getResearchtitle());
intent.putExtra("researchdate",researchRepositories.get(position).getResearchtimeline());
intent.putExtra("researchname",researchRepositories.get(position).getFilecapture());
intent.putExtra("researchdescription",researchRepositories.get(position).getResearchdescription());
v.getContext().startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return researchRepositories.size();
}
class AdminViewHolder extends RecyclerView.ViewHolder{
public TextView researchtitle_view,researchdate_view,researchname_view,researchdescription_view,researchtitle_url;
public Button btnpdf_edit;
public AdminViewHolder (#NonNull View itemView) {
super(itemView);
researchtitle_view = itemView.findViewById(R.id.researchtitle_view);
researchdate_view = itemView.findViewById(R.id.researchdate_view);
researchname_view = itemView.findViewById(R.id.researchname_view);
researchdescription_view = itemView.findViewById(R.id.researchdescription_view);
researchtitle_url = itemView.findViewById(R.id.researchtitle_view);
btnpdf_edit = itemView.findViewById(R.id.btnpdf_edit);
}
}
}
ResearchRepository.class
package com.example.citeresearchrepository.Model;
public class ResearchRepository {
public String filecapture;
public String researchtitle;
public String researchdescription;
public String researchtimeline;
public String url;
public ResearchRepository() {
}
public ResearchRepository(String filecapture, String researchtitle, String researchdescription, String researchtimeline, String url) {
this.filecapture = filecapture;
this.researchtitle = researchtitle;
this.researchdescription = researchdescription;
this.researchtimeline = researchtimeline;
this.url = url;
}
public String getFilecapture() {
return filecapture;
}
public void setFilecapture(String filecapture) {
this.filecapture = filecapture;
}
public String getResearchtitle() {
return researchtitle;
}
public void setResearchtitle(String researchtitle) {
this.researchtitle = researchtitle;
}
public String getResearchdescription() {
return researchdescription;
}
public void setResearchdescription(String researchdescription) {
this.researchdescription = researchdescription;
}
public String getResearchtimeline() {
return researchtimeline;
}
public void setResearchtimeline(String researchtimeline) {
this.researchtimeline = researchtimeline;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
Here's my realtime-database : https://i.stack.imgur.com/lML0i.png
I just wanna delete the red box.
From what I see you are getting an instance to only the ResearchRepository node instead of the specific child node that you want to delete. You need to keep track of the unique IDs you are pushing on to the ResearchRepository node and pass it in the intent as well;
Add the code to pass the unique ID of the ResearchRepository child you want to delete.
Then do this in your new activity where the delete code is present.
String childToDelete; //retrieve the value from the intent
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("ResearchRepository").child(childToDelete);
databaseReference.removeValue();
This should do it if that is your purpose.
Edit 1:-
I got your point. Please follow the approach I will be showing now and it will work for you.
Edit your class as shown below:-
AdminRepoAdapter.java
public class AdminRepoAdapter extends RecyclerView.Adapter<AdminRepoAdapter.AdminViewHolder> {
Context context;
Map<String,ResearchRepository> researchRepositories;
ArrayList<ResearchRepository> researchRepositoriesHolder;
public AdminRepoAdapter(Context c, Map<String,ResearchRepository> repositories){
context = c;
researchRepositories = repositories;
researchRepositoriesHolder = new ArrayList<>(researchRepositories.values());
}
#NonNull
#Override
public AdminViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new AdminViewHolder(LayoutInflater.from(context).inflate(R.layout.admineditrepo_row,parent,false));
}
#Override
public void onBindViewHolder(#NonNull AdminViewHolder holder, final int position) {
holder.researchtitle_view.setText(researchRepositoriesHolder.get(position).getResearchtitle());
holder.researchdate_view.setText(researchRepositoriesHolder.get(position).getResearchtimeline());
holder.researchname_view.setText(researchRepositoriesHOlder.get(position).getFilecapture());
holder.researchdescription_view.setText(researchRepositoriesHolder.get(position).getResearchdescription());
holder.btnpdf_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Map.Entry<String,ResearchRepository> entry = null; //Just for initialization
for (Map.Entry<String,ResearchRepository> var : researchRepositories.entrySet()) {
if(var.getValue() == researchRepositoriesHolder.get(position)){
entry = var;
break;
}
}
Intent intent = new Intent(context, EditResearchActivity.class);
intent.putExtra("researchtitle",entry.getValue().getResearchtitle());
intent.putExtra("researchdate",entry.getValue().getResearchtimeline());
intent.putExtra("researchname",entry.getValue().getFilecapture());
intent.putExtra("researchdescription",entry.getValue().getResearchdescription());
intent.putExtra("childNodeKey",entry.getKey());
v.getContext().startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return researchRepositoriesHolder.size();
}
class AdminViewHolder extends RecyclerView.ViewHolder{
public TextView researchtitle_view,researchdate_view,researchname_view,researchdescription_view,researchtitle_url;
public Button btnpdf_edit;
public AdminViewHolder (#NonNull View itemView) {
super(itemView);
researchtitle_view = itemView.findViewById(R.id.researchtitle_view);
researchdate_view = itemView.findViewById(R.id.researchdate_view);
researchname_view = itemView.findViewById(R.id.researchname_view);
researchdescription_view = itemView.findViewById(R.id.researchdescription_view);
researchtitle_url = itemView.findViewById(R.id.researchtitle_view);
btnpdf_edit = itemView.findViewById(R.id.btnpdf_edit);
}
}
}
AdminResearchRepoActivity.java
public class AdminResearchRepoActivity extends AppCompatActivity {
ImageView adminrepo_backbtn;
RecyclerView reporecycler;
FloatingActionButton addresearch_btn;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
AdminRepoAdapter adminRepoAdapter;
Map<String, ResearchRepository> researchRepositoryMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_research_repo);
// Buttons
adminrepo_backbtn = findViewById(R.id.backbtn_adminrepo);
addresearch_btn = findViewById(R.id.addresearch_btn);
addresearch_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), AddResearchActivity.class));
}
});
adminrepo_backbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), WelcomeAdminActivity.class));
}
});
// Recycler
reporecycler = findViewById(R.id.reporecycler);
reporecycler.setLayoutManager(new LinearLayoutManager(this));
// Firebase Connection
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference().child("ResearchRepository");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
researchRepositoryMap = (Map)snapshot.getValue()
adminRepoAdapter = new AdminRepoAdapter(AdminResearchRepoActivity.this,researchRepositoryMap);
reporecycler.setAdapter(adminRepoAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(AdminResearchRepoActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
In this way when you pass a Intent from your AdminRepoAdapter to EditResearchActivity you will have the key stored as 'childNodeKey' in your intent.
You can then follow the procedure I mentioned before the edit to delete using the key you got from here.

Firebase StorageException has occurred. Code: -13000 HttpResult: 400

Before starting explaining my problem, i'll show you the full image of my error.
I did my best to find the solution and the reason why this error would happen.
I found a few sources such as this or this.
I'm afraid you guys would think that my question is the same as those questions, but I think that there are some differences, so i really hope you guys read my question.
First, I have followed the official chat app tutorial by Google. (this)
and I just copied the source codes, but the error occured on chapter 8(Send Message). And there were no problems when i send the message just with texts, but problem occured when i send the message with image file from my local storage. And i just found the source that says 'In the google firebase this type of StorageException are commonly caused because of wrong StorageReference reference.', so I looked my source codes about StorageReference. But i couldn't understand that answer and I couldn't find any problems.
Second, I showed you more detail about the error message and i'll show you my full source code of MainActivity.
package com.google.firebase.codelab.friendlychat;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Layout;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.firebase.ui.database.SnapshotParser;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.appinvite.AppInvite;
import com.google.android.gms.appinvite.AppInviteInvitation;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.crash.FirebaseCrash;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.remoteconfig.FirebaseRemoteConfig;
import com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings;
import com.google.firebase.appindexing.Action;
import com.google.firebase.appindexing.FirebaseAppIndex;
import com.google.firebase.appindexing.FirebaseUserActions;
import com.google.firebase.appindexing.Indexable;
import com.google.firebase.appindexing.builders.Indexables;
import com.google.firebase.appindexing.builders.PersonBuilder;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.util.HashMap;
import java.util.Map;
import de.hdodenhof.circleimageview.CircleImageView;
public class MainActivity extends AppCompatActivity
implements GoogleApiClient.OnConnectionFailedListener {
public static class MessageViewHolder extends RecyclerView.ViewHolder {
TextView messageTextView;
ImageView messageImageView;
TextView messengerTextView;
CircleImageView messengerImageView;
public MessageViewHolder(View v) {
super(v);
messageTextView = (TextView) itemView.findViewById(R.id.messageTextView);
messageImageView = (ImageView) itemView.findViewById(R.id.messageImageView);
messengerTextView = (TextView) itemView.findViewById(R.id.messengerTextView);
messengerImageView = (CircleImageView) itemView.findViewById(R.id.messengerImageView);
}
public void bind(FriendlyMessage friendlyMessage){
messageTextView.setText(friendlyMessage.getText());
messageTextView.setVisibility(View.VISIBLE);
messageImageView.setVisibility(View.GONE);
}
}
private static final String TAG = "MainActivity";
public static final String MESSAGES_CHILD = "messages";
private static final int REQUEST_INVITE = 1;
private static final int REQUEST_IMAGE = 2;
private static final String LOADING_IMAGE_URL = "https://www.google.com/images/spin-32.gif";
public static final int DEFAULT_MSG_LENGTH_LIMIT = 10;
public static final String ANONYMOUS = "anonymous";
private static final String MESSAGE_SENT_EVENT = "message_sent";
private String mUsername;
private String mPhotoUrl;
private SharedPreferences mSharedPreferences;
private GoogleApiClient mGoogleApiClient;
private static final String MESSAGE_URL = "http://friendlychat.firebase.google.com/message/";
private Button mSendButton;
private RecyclerView mMessageRecyclerView;
private LinearLayoutManager mLinearLayoutManager;
private ProgressBar mProgressBar;
private EditText mMessageEditText;
private ImageView mAddMessageImageView;
// Firebase instance variables
private FirebaseAuth mFirebaseAuth;
private FirebaseUser mFirebaseUser;
private DatabaseReference mFirebaseDatabaseReference;
private FirebaseRecyclerAdapter<FriendlyMessage, MessageViewHolder> mFirebaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
// Set default username is anonymous.
mUsername = ANONYMOUS;
// Initialize Firebase Auth
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
if(mFirebaseUser == null){
// Not signed in, launch the Sign In activity
startActivity(new Intent(this, SignInActivity.class));
finish();
return;
}
else {
mUsername = mFirebaseUser.getDisplayName();
if(mFirebaseUser.getPhotoUrl() != null){
mPhotoUrl = mFirebaseUser.getPhotoUrl().toString();
}
}
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API)
.build();
// Initialize ProgressBar and RecyclerView.
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mMessageRecyclerView = (RecyclerView) findViewById(R.id.messageRecyclerView);
mLinearLayoutManager = new LinearLayoutManager(this);
mLinearLayoutManager.setStackFromEnd(true);
// mLinearLayoutManager.setReverseLayout(true);
mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
mProgressBar.setVisibility(ProgressBar.INVISIBLE);
mMessageEditText = (EditText) findViewById(R.id.messageEditText);
mMessageEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(mSharedPreferences
.getInt(CodelabPreferences.FRIENDLY_MSG_LENGTH, DEFAULT_MSG_LENGTH_LIMIT))});
mMessageEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().trim().length() > 0) {
mSendButton.setEnabled(true);
} else {
mSendButton.setEnabled(false);
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
mSendButton = (Button) findViewById(R.id.sendButton);
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Send messages on click.
FriendlyMessage friendlyMessage = new FriendlyMessage(mMessageEditText.getText().toString(),
mUsername,
mPhotoUrl,
null);
mFirebaseDatabaseReference.child(MESSAGES_CHILD)
.push().setValue(friendlyMessage);
mMessageEditText.setText("");
}
});
mAddMessageImageView = (ImageView) findViewById(R.id.addMessageImageView);
mAddMessageImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Select image for image message on click.
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_IMAGE);
}
});
// New child entries
mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference();
SnapshotParser<FriendlyMessage> parser = new SnapshotParser<FriendlyMessage>() {
#Override
public FriendlyMessage parseSnapshot(DataSnapshot dataSnapshot) {
FriendlyMessage friendlyMessage = dataSnapshot.getValue(FriendlyMessage.class);
if(friendlyMessage != null){
friendlyMessage.setId(dataSnapshot.getKey());
}
return friendlyMessage;
}
};
DatabaseReference messageRef = mFirebaseDatabaseReference.child(MESSAGES_CHILD);
FirebaseRecyclerOptions<FriendlyMessage> options =
new FirebaseRecyclerOptions.Builder<FriendlyMessage>()
.setQuery(messageRef, parser)
.build();
mFirebaseAdapter = new FirebaseRecyclerAdapter<FriendlyMessage, MessageViewHolder>(options) {
#Override
public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
return new MessageViewHolder(inflater.inflate(R.layout.item_message, parent, false));
}
#Override
protected void onBindViewHolder(final MessageViewHolder holder, int position, FriendlyMessage friendlyMessage) {
mProgressBar.setVisibility(View.INVISIBLE);
if(friendlyMessage.getText() != null){
holder.bind(friendlyMessage);
}
else {
String imageUrl = friendlyMessage.getImageUrl();
if(imageUrl.startsWith("gs://")) {
StorageReference storageReference = FirebaseStorage.getInstance()
.getReferenceFromUrl(imageUrl);
storageReference.getDownloadUrl().addOnCompleteListener(
new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if(task.isSuccessful()){
String downloadUrl= task.getResult().toString();
Glide.with(holder.messageImageView.getContext())
.load(downloadUrl)
.into(holder.messageImageView);
}
else {
Log.w(TAG, "Getting download url was not seccessful.",
task.getException());
}
}
}
);
}
else {
Glide.with(holder.messageImageView.getContext())
.load(friendlyMessage.getImageUrl())
.into(holder.messageImageView);
}
holder.messageImageView.setVisibility(ImageView.VISIBLE);
holder.messageTextView.setVisibility(TextView.GONE);
}
holder.messengerTextView.setText(friendlyMessage.getName());
if(friendlyMessage.getPhotoUrl() == null){
holder.messengerImageView.setImageDrawable(ContextCompat.getDrawable(MainActivity.this,
R.drawable.ic_account_circle_black_36dp));
}
else {
Glide.with(MainActivity.this)
.load(friendlyMessage.getPhotoUrl())
.into(holder.messengerImageView);
}
}
};
mFirebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
int friendlyMessageCount = mFirebaseAdapter.getItemCount();
int lastVisiblePosotion =
mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
if(lastVisiblePosotion == -1 ||
(positionStart >= (friendlyMessageCount - 1) && lastVisiblePosotion == (positionStart - 1))){
mMessageRecyclerView.scrollToPosition(positionStart);
}
}
});
mMessageRecyclerView.setAdapter(mFirebaseAdapter);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "onActivityResult: requestCode=" + requestCode + ", resultCode=" + resultCode);
if (requestCode == REQUEST_IMAGE) {
if (resultCode == RESULT_OK) {
if (data != null) {
final Uri uri = data.getData();
Log.d(TAG, "Uri: " + uri.toString());
FriendlyMessage tempMessage = new FriendlyMessage(null, mUsername, mPhotoUrl,
LOADING_IMAGE_URL);
mFirebaseDatabaseReference.child(MESSAGES_CHILD).push()
.setValue(tempMessage, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError,
DatabaseReference databaseReference) {
if (databaseError == null) {
String key = databaseReference.getKey();
StorageReference storageReference =
FirebaseStorage.getInstance()
.getReference(mFirebaseUser.getUid())
.child(key)
.child( uri.getLastPathSegment());
putImageInStorage(storageReference, uri, key);
} else {
Log.w(TAG, "Unable to write message to database.",
databaseError.toException());
}
}
});
}
}
}
}
private void putImageInStorage(StorageReference storageReference, Uri uri, final String key) {
storageReference.putFile(uri).addOnCompleteListener(MainActivity.this,
new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
FriendlyMessage friendlyMessage =
new FriendlyMessage(null, mUsername, mPhotoUrl,
task.getResult().getMetadata().getDownloadUrl()
.toString());
mFirebaseDatabaseReference.child(MESSAGES_CHILD).child(key)
.setValue(friendlyMessage);
} else {
Log.w(TAG, "Image upload task was not successful.",
task.getException());
}
}
});
}
#Override
public void onStart() {
super.onStart();
// Check if user is signed in.
// TODO: Add code to check if user is signed in.
}
#Override
public void onPause() {
mFirebaseAdapter.stopListening();
super.onPause();
}
#Override
public void onResume() {
super.onResume();
mFirebaseAdapter.startListening();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.sign_out_menu:
mFirebaseAuth.signOut();
Auth.GoogleSignInApi.signOut(mGoogleApiClient);
mUsername = ANONYMOUS;
startActivity(new Intent(this, SignInActivity.class));
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
// An unresolvable error has occurred and Google APIs (including Sign-In) will not
// be available.
Log.d(TAG, "onConnectionFailed:" + connectionResult);
Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show();
}
}
I think I have no problems with Firebase authentication and the intallation or the version of Google Play Service.
Thank you for reading my question.

Categories

Resources