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

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.

Related

How to Retrive Data from Cloud Firestore

I'm developing my first android application and I'm having some difficulties understanding why the TextView "recipeContent" and "timeContent" are not being updated with the fields fetched from CloudFirestore.
I am using the following scripts.
CreateFragment.java:
package com.example.quickrecipe;
import static android.content.ContentValues.TAG;
import android.content.Intent;
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.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import com.blogspot.atifsoftwares.animatoolib.Animatoo;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentChange;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
public class CreateFragment extends Fragment {
ImageButton createButton;
RecyclerView recyclerView;
FirebaseFirestore firestore;
MyAdapter myAdapter;
ArrayList<Recipe> list;
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser currentUser = mAuth.getCurrentUser();
String email = currentUser.getEmail();
String usernameEmail = email.split("#")[0];
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_create, container, false);
createButton = view.findViewById(R.id.createButton);
recyclerView = view.findViewById(R.id.recipesList);
firestore = FirebaseFirestore.getInstance();
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
list = new ArrayList<>();
myAdapter = new MyAdapter(getContext(), list);
recyclerView.setAdapter(myAdapter);
Query query = firestore.collection(usernameEmail+"MyRecipes");
query.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot snapshot, FirebaseFirestoreException e) {
if (e != null) {
Log.w(TAG, "Listen failed.", e);
return;
}
for (DocumentChange dc : snapshot.getDocumentChanges()) {
switch (dc.getType()) {
case ADDED:
Recipe recipe = dc.getDocument().toObject(Recipe.class);
list.add(recipe);
break;
case MODIFIED:
Recipe modifiedRecipe = dc.getDocument().toObject(Recipe.class);
int modifiedIndex = getRecipeIndex(dc.getDocument().getId());
list.set(modifiedIndex, modifiedRecipe);
break;
case REMOVED:
int removedIndex = getRecipeIndex(dc.getDocument().getId());
list.remove(removedIndex);
break;
}
}
myAdapter.notifyDataSetChanged();
}
});
return view;
}
private int getRecipeIndex(String recipeId) {
for (int i = 0; i < list.size(); i++) {
Recipe recipe = list.get(i);
if (recipe.getId().equals(recipeId)) {
return i;
}
}
return -1;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
createButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), CreateRecipe.class);
startActivity(intent);
Animatoo.INSTANCE.animateSlideLeft(getActivity());
if (getActivity() != null) {
getActivity().finish();
}
}
});
}
}
CreateRecipe.java:
package com.example.quickrecipe;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.blogspot.atifsoftwares.animatoolib.Animatoo;
import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class CreateRecipe extends AppCompatActivity {
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser currentUser = mAuth.getCurrentUser();
String email = currentUser.getEmail();
String usernameEmail = email.split("#")[0];
FirebaseDatabase mDatabase;
StorageReference storageReference = FirebaseStorage.getInstance().getReference();
DocumentReference docRef = FirebaseFirestore.getInstance().collection("user").document("user-id");
FirebaseStorage mStorage;
FirebaseFirestore db;
EditText editTextRecipeName, editTextTime, editTextIngredients, editTextCook;
Button Createbtn;
Button SelectImageButton;
ImageView imageView;
final int GALLERY_REQUEST_CODE = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_recipe);
editTextRecipeName = findViewById(R.id.editTextRecipeName);
editTextTime = findViewById(R.id.editTextTime);
editTextIngredients = findViewById(R.id.editTextIngredients);
editTextCook = findViewById(R.id.editTextCook);
Createbtn = findViewById(R.id.Createbtn);
db = FirebaseFirestore.getInstance();
imageView = findViewById(R.id.selected_image);
SelectImageButton = findViewById(R.id.select_image_button);
SelectImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY_REQUEST_CODE);
imageView.setDrawingCacheEnabled(true);
imageView.buildDrawingCache();
}
});
mDatabase = FirebaseDatabase.getInstance();
mStorage = FirebaseStorage.getInstance();
Createbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String rp = editTextRecipeName.getText().toString().trim();
String tm = editTextTime.getText().toString().trim();
String ig = editTextIngredients.getText().toString().trim();
String ck = editTextCook.getText().toString().trim();
if (rp.isEmpty() || tm.isEmpty() || ig.isEmpty() || ck.isEmpty()) {
AlertDialog.Builder builder = new AlertDialog.Builder(CreateRecipe.this);
builder.setMessage("Você deseja criar um rascunho?")
.setCancelable(false)
.setPositiveButton("Sim", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Map<String, Object> recipe = new HashMap<>();
recipe.put("RecipeName", rp);
recipe.put("Time", tm);
recipe.put("Ingredients", ig);
recipe.put("Cook", ck);
db.collection(usernameEmail + "MyRecipesDraft")
.add(recipe)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(CreateRecipe.this, "Falhou!", Toast.LENGTH_SHORT).show();
}
});
Toast.makeText(getApplicationContext(), "Rascunho criado!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
Animatoo.INSTANCE.animateSlideRight(CreateRecipe.this);
finish();
}
})
.setNegativeButton("Não", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
Map<String, Object> recipe = new HashMap<>();
recipe.put("RecipeName", rp);
recipe.put("Time", tm);
recipe.put("Ingredients", ig);
recipe.put("Cook", ck);
db.collection(usernameEmail + "MyRecipes")
.add(recipe)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(CreateRecipe.this, "Falhou!", Toast.LENGTH_SHORT).show();
}
});
Bitmap bitmap = imageView.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (bitmap != null) {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] data = baos.toByteArray();
String fileName = UUID.randomUUID().toString();
StorageReference imageRef = storageReference.child(usernameEmail+"images/" + fileName + ".jpg");
UploadTask uploadTask = imageRef.putBytes(data);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Obtem a URL de download da imagem
imageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// Salva a URL de download da imagem no documento do usuário no Firestore
docRef.update("profileImageUrl", uri.toString());
}
});
}
});
} else {
}
Toast.makeText(getApplicationContext(), "Receita criada!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
Animatoo.INSTANCE.animateSlideRight(getApplicationContext());
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri imageUri = data.getData();
imageView.setImageURI(imageUri);
Glide.with(this)
.load(imageUri)
.centerCrop()
.placeholder(R.drawable.create_icon)
.into(imageView);
StorageReference storageRef = storageReference.child(usernameEmail+"_Images/" + UUID.randomUUID().toString() + ".jpg");
storageRef.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Imagem enviada com sucesso para o Firebase Storage
// Você pode obter a URL de download da imagem aqui e salvá-la no Firestore
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// Falha ao enviar a imagem para o Firebase Storage
}
});
}
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Você realmente deseja sair do criador de receitas?")
.setCancelable(false)
.setPositiveButton("Sim", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
Animatoo.INSTANCE.animateSlideRight(CreateRecipe.this);
finish();
}
})
.setNegativeButton("Não", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
MyAdapter.java:
package com.example.quickrecipe;
import static android.content.ContentValues.TAG;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.ArrayList;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private Context mContext;
private ArrayList<Recipe> mList;
public MyAdapter(Context context, ArrayList<Recipe> list) {
mContext = context;
mList = list;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
Recipe recipe = mList.get(position);
holder.bind(recipe);
FirebaseFirestore firestore = FirebaseFirestore.getInstance();
FirebaseAuth mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null && recipe.getId() != null) {
String usernameEmail = mAuth.getCurrentUser().getEmail().split("#")[0];
firestore.collection(usernameEmail+"MyRecipes")
.document(recipe.getId())
.get()
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
holder.bind(new Recipe(recipe.getId(), document.getString("RecipeName"), document.getString("Time")));
Log.d(TAG, "Document: " + document.getData());
} else {
Log.d(TAG, "No such document");
}
Log.d(TAG, "Document: " + document.getData());
} else {
Log.d(TAG, "get failed with ", task.getException());
}
});
}
}
#Override
public int getItemCount() {
return mList.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
public TextView recipeContent, timeContent;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
recipeContent = itemView.findViewById(R.id.recipeContent);
timeContent = itemView.findViewById(R.id.timeContent);
}
public void bind(Recipe recipe) {
recipeContent.setText(recipe.getRecipeName());
timeContent.setText(recipe.getTimeContent());
}
}
}
Recipe.java:
package com.example.quickrecipe;
public class Recipe {
private String id;
private String recipeName;
private String ingredients;
private String cook;
private String timeContent;
public Recipe() {}
public Recipe(String id, String recipeName, String ingredients) {
this.id = id;
this.recipeName = recipeName;
this.ingredients = ingredients;
this.cook = cook;
this.timeContent = timeContent;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getRecipeName() {
return recipeName;
}
public void setRecipeName(String recipeName) {
this.recipeName = recipeName;
}
public String getIngredients() {
return ingredients;
}
public void setIngredients(String ingredients) {
this.ingredients = ingredients;
}
public String getCook() {
return cook;
}
public void setCook(String cook) {
this.cook = cook;
}
public String getTimeContent() {
return timeContent;
}
public void setTimeContent(String timeContent) {
this.timeContent = timeContent;
}
}
RecyclerView item.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardElevation="8dp"
app:cardCornerRadius="8dp"
android:layout_margin="16dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal">
<ImageView
android:id="#+id/recipeImage"
android:layout_width="80dp"
android:layout_height="80dp">
</ImageView>
<TextView
android:id="#+id/recipeTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingTop="5dp"
android:text="Receita: ">
</TextView>
<TextView
android:id="#+id/recipeContent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="5dp"
>
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal">
<TextView
android:id="#+id/recipeTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="80dp"
android:paddingLeft="10dp"
android:paddingTop="5dp"
android:text="Tempo de preparo: ">
</TextView>
<TextView
android:id="#+id/timeContent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="5dp">
</TextView>
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
Firebase looks like this:
firebase_rules
firebase_fields
Do you know why this is happening?
I've already tried to redo the connection with Firebase, but the TextView data continues to be replaced by null/empty.

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.

Why I get a null object reference documentSnapshot.toObject() method?

I'm trying to add firebase auth and firebase database for a simple login/register form but got a crash because User currentUser = documentSnapshot.toObject(User.class); return a null object and I don't understand why.
Here's my code
ProfileActivity :
package fr.tom_d.growthwatcher;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentSnapshot;
import fr.tom_d.growthwatcher.api.UserHelper;
import fr.tom_d.growthwatcher.models.User;
public class ProfilActivity extends BaseActivity {
private static final int UPDATE_USERNAME = 30;
private FirebaseAuth mAuth;
private TextView mUsername;
private EditText mNewUsername;
private ProgressBar mProgressBar;
private Button mButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAuth = FirebaseAuth.getInstance();
setContentView(R.layout.activity_profil);
mUsername = findViewById(R.id.profile_tv_username);
mNewUsername = findViewById(R.id.profile_et_username);
mProgressBar = findViewById(R.id.profile_progressbar);
mButton = findViewById(R.id.profile_change_username_btn);
this.updateUIWhenCreating();
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateUsernameInFirebase();
}
});
}
private void updateUIWhenCreating(){
if (this.getCurrentUser() != null){
//Get email & username from Firebase
String username = TextUtils.isEmpty(this.getCurrentUser().getDisplayName()) ? getString(R.string.info_no_username_found) : this.getCurrentUser().getDisplayName();
//Update views with data
this.mUsername.setText(username);
}
UserHelper.getUser(this.getCurrentUser().getUid()).addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
User currentUser = documentSnapshot.toObject(User.class);
String username = TextUtils.isEmpty(currentUser.getUsername()) ? getString(R.string.info_no_username_found) : currentUser.getUsername();
mNewUsername.setText(username);
}
});
}
private void updateUsernameInFirebase(){
String username = this.mNewUsername.getText().toString();
if (this.getCurrentUser() != null){
if (!username.isEmpty() && !username.equals(getString(R.string.info_no_username_found))){
UserHelper.updateUsername(username, this.getCurrentUser().getUid()).addOnFailureListener(this.onFailureListener()).addOnSuccessListener(this.updateUIAfterRESTRequestsCompleted(UPDATE_USERNAME));
}
}
}
private OnSuccessListener<Void> updateUIAfterRESTRequestsCompleted(final int origin){
return new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
switch (origin){
// 8 - Hiding Progress bar after request completed
case UPDATE_USERNAME:
mProgressBar.setVisibility(View.INVISIBLE);
break;
}
}
};
}
}
User :
package fr.tom_d.growthwatcher.models;
import android.support.annotation.Nullable;
public class User {
private String mUid;
#Nullable
private String mUsername;
public User() { }
public User(String uid, String username) {
mUid = uid;
mUsername = username;
}
// --- GETTERS ---
public String getUid() { return mUid; }
public String getUsername() { return mUsername; }
// --- SETTERS ---
public void setUsername(String username) { this.mUsername = username; }
public void setUid(String uid) { this.mUid = uid; }
}
UserHelper :
package fr.tom_d.growthwatcher.api;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import fr.tom_d.growthwatcher.models.User;
public class UserHelper {
private static final String COLLECTION_NAME = "users";
// --- COLLECTION REFERENCE ---
public static CollectionReference getUsersCollection() {
return FirebaseFirestore.getInstance().collection(COLLECTION_NAME);
}
// --- CREATE ---
public static Task<Void> createUser(String uid, String username) {
User userToCreate = new User(uid, username);
return UserHelper.getUsersCollection().document(uid).set(userToCreate);
}
// --- GET ---
public static Task<DocumentSnapshot> getUser(String uid) {
return UserHelper.getUsersCollection().document(uid).get();
}
// --- UPDATE ---
public static Task<Void> updateUsername(String username, String uid) {
return UserHelper.getUsersCollection().document(uid).update("username", username);
}
// --- DELETE ---
public static Task<Void> deleteUser(String uid) {
return UserHelper.getUsersCollection().document(uid).delete();
}
}
I also noticed that my database Firebase was empty while a user must be created when I register with Displayname as his email address if he logs in via google, otherwise the nickname he indicates in an EditText. Then I run my main activity which is supposed to create a user in the database ....
The code of my mainActivity:
package fr.tom_d.growthwatcher;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.CoordinatorLayout;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.support.design.widget.Snackbar;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import fr.tom_d.growthwatcher.api.UserHelper;
public class MainActivity extends BaseActivity {
private final static int RC_SIGN_IN = 100;
private FirebaseAuth mAuth;
private TextView mMail, mId;
private EditText mPlantDate, mRelDate, mTempRel;
private Button mPlantDateBtn, mTempRelBtn, mProfilBtn;
private GraphView mGraph;
private DataPoint[] mDataPoint;
#Override
protected void onCreate(Bundle savedInstanceState) {
mAuth = FirebaseAuth.getInstance();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMail = findViewById(R.id.main_mail);
mId = findViewById(R.id.main_id);
//mGraph = findViewById(R.id.main_graph);
mPlantDate = findViewById(R.id.main_et_date_plant);
mPlantDateBtn = findViewById(R.id.main_ok_plant_btn);
mRelDate = findViewById(R.id.main_et_date_rel);
mTempRel = findViewById(R.id.main_et_temp);
mTempRelBtn = findViewById(R.id.main_ok_temp_btn);
mProfilBtn = findViewById(R.id.main_profil_btn);
//LineGraphSeries<DataPoint> series = new LineGraphSeries<>(mDataPoint);
mPlantDateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
mProfilBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent profileActivity = new Intent(MainActivity.this, ProfilActivity.class);
startActivity(profileActivity);
}
});
}
#Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
String vEmail = currentUser.getEmail();
String vId = currentUser.getProviderId();
mMail.setText(vEmail);
mId.setText(vId);
}
private void createUserInFirestore(){
if (this.getCurrentUser() != null){
String urlPicture = (this.getCurrentUser().getPhotoUrl() != null) ? this.getCurrentUser().getPhotoUrl().toString() : null;
String username = this.getCurrentUser().getDisplayName();
String uid = this.getCurrentUser().getUid();
UserHelper.createUser(uid, username).addOnFailureListener(this.onFailureListener());
}
}
private void handleResponseAfterSignIn(int requestCode, int resultCode, Intent data){
if (requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
this.createUserInFirestore();
} else {
Toast.makeText(MainActivity.this, "ERREUR CREATION USER FIREBASE",
Toast.LENGTH_SHORT).show();
}
}
}
}
RegisterActivity :
package fr.tom_d.growthwatcher;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.google.firebase.auth.UserProfileChangeRequest;
import fr.tom_d.growthwatcher.api.UserHelper;
public class RegisterActivity extends BaseActivity {
private final static String TAG = "RegisterActivity";
private final static int RC_SIGN_IN = 100;
private FirebaseAuth mAuth;
private Button mStartButton;
private TextView mAppText;
private EditText mPseudo, mMail, mPassword;
private boolean isPseudoOk, isPasswordOk, isMailOk;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAuth = FirebaseAuth.getInstance();
setContentView(R.layout.activity_register);
isMailOk = false;
isPasswordOk = false;
isPseudoOk = false;
mAppText = findViewById(R.id.register_app_text);
mPseudo = findViewById(R.id.register_et_pseudo);
mPassword = findViewById(R.id.register_et_password);
mMail = findViewById(R.id.register_et_email);
mStartButton = findViewById(R.id.register_start_button);
mPseudo.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.toString().length() >=3){
isPseudoOk=true;
}
if (isPseudoOk && isPasswordOk && isMailOk){
mStartButton.setEnabled(true);
}
else mStartButton.setEnabled(false);
}
#Override
public void afterTextChanged(Editable s) {
}
});
mPassword.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().length() >= 5){
isPasswordOk = true;
}
else isPasswordOk = false;
if (isPseudoOk && isPasswordOk && isMailOk){
mStartButton.setEnabled(true);
}
else mStartButton.setEnabled(false);
}
#Override
public void afterTextChanged(Editable s) {
}
});
mMail.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().length() >= 5){
isMailOk = true;
}
else isMailOk = false;
if (isPseudoOk && isPasswordOk && isMailOk){
mStartButton.setEnabled(true);
}
else mStartButton.setEnabled(false);
}
#Override
public void afterTextChanged(Editable s) {
}
});
mStartButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAuth.createUserWithEmailAndPassword(mMail.getText().toString(), mPassword.getText().toString())
.addOnCompleteListener(RegisterActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "createUserWithEmail:success");
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(mPseudo.getText().toString()).build();
getCurrentUser().updateProfile(profileUpdates);
createUserInFirestore();
Intent mainActivity = new Intent(RegisterActivity.this, MainActivity.class);
startActivity(mainActivity);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(RegisterActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
protected void onStart () {
super.onStart();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
Intent mainActivity = new Intent(RegisterActivity.this, MainActivity.class);
startActivity(mainActivity);
}
else {
// No user is signed in
}
}
}
According to the API documentation for toObject(), it will return null if the document doesn't exist. You should first check to see if it exists using exists().

Relevant activity is not closed

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...

Chat messages are not showed when exit and reopen app

I have made a chat app using this lesson. I have tested it:
Then I closed the app, and opened it some time later. And surprisingly all messages had disappeared:
They appeared back only when I logged out and logged in again.
How to solve that bug?
My code:
MainActivity.java:
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.firebase.ui.auth.AuthUI;
import com.firebase.ui.database.FirebaseListAdapter;
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.FirebaseDatabase;
public class MainActivity extends AppCompatActivity {
private static final int SIGN_IN_REQUEST_CODE = 111;
private FirebaseListAdapter<ChatMessage> adapter;
private ListView listView;
private String loggedInUserName = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//find views by Ids
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
final EditText input = (EditText) findViewById(R.id.input);
listView = (ListView) findViewById(R.id.list);
if (FirebaseAuth.getInstance().getCurrentUser() == null) {
// Start sign in/sign up activity
startActivityForResult(AuthUI.getInstance()
.createSignInIntentBuilder()
.build(), SIGN_IN_REQUEST_CODE);
} else {
// User is already signed in, show list of messages
showAllOldMessages();
}
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (input.getText().toString().trim().equals("")) {
Toast.makeText(MainActivity.this, "Please enter some texts!", Toast.LENGTH_SHORT).show();
} else {
FirebaseDatabase.getInstance()
.getReference()
.push()
.setValue(new ChatMessage(input.getText().toString(),
FirebaseAuth.getInstance().getCurrentUser().getDisplayName(),
FirebaseAuth.getInstance().getCurrentUser().getUid())
);
input.setText("");
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_sign_out) {
AuthUI.getInstance().signOut(this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(MainActivity.this, "You have logged out!", Toast.LENGTH_SHORT).show();
finish();
}
});
}
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SIGN_IN_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Toast.makeText(this, "Signed in successful!", Toast.LENGTH_LONG).show();
showAllOldMessages();
} else {
Toast.makeText(this, "Sign in failed, please try again later", Toast.LENGTH_LONG).show();
// Close the app
finish();
}
}
}
private void showAllOldMessages() {
loggedInUserName = FirebaseAuth.getInstance().getCurrentUser().getUid();
Log.d("Main", "user id: " + loggedInUserName);
adapter = new MessageAdapter(this, ChatMessage.class, R.layout.item_in_message,
FirebaseDatabase.getInstance().getReference());
listView.setAdapter(adapter);
}
public String getLoggedInUserName() {
return loggedInUserName;
}
}
ChatMessage.java:
public class ChatMessage {
private String messageText;
private String messageUser;
private String messageUserId;
public ChatMessage(String messageText, String messageUser, String messageUserId) {
this.messageText = messageText;
this.messageUser = messageUser;
this.messageUserId = messageUserId;
}
public ChatMessage(){
}
public String getMessageUserId() {
return messageUserId;
}
public void setMessageUserId(String messageUserId) {
this.messageUserId = messageUserId;
}
public String getMessageText() {
return messageText;
}
public void setMessageText(String messageText) {
this.messageText = messageText;
}
public String getMessageUser() {
return messageUser;
}
public void setMessageUser(String messageUser) {
this.messageUser = messageUser;
}
}
ChatAdapter.java:
import android.text.format.DateFormat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseListAdapter;
import com.google.firebase.database.DatabaseReference;
public class MessageAdapter extends FirebaseListAdapter<ChatMessage> {
private MainActivity activity;
public MessageAdapter(MainActivity activity, Class<ChatMessage> modelClass, int modelLayout, DatabaseReference ref) {
super(activity, modelClass, modelLayout, ref);
this.activity = activity;
}
#Override
protected void populateView(View v, ChatMessage model, int position) {
TextView messageText = (TextView) v.findViewById(R.id.message_text);
TextView messageUser = (TextView) v.findViewById(R.id.message_user);
messageText.setText(model.getMessageText());
messageUser.setText(model.getMessageUser());
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
ChatMessage chatMessage = getItem(position);
if (chatMessage.getMessageUserId().equals(activity.getLoggedInUserName()))
view = activity.getLayoutInflater().inflate(R.layout.item_out_message, viewGroup, false);
else
view = activity.getLayoutInflater().inflate(R.layout.item_in_message, viewGroup, false);
//generating view
populateView(view, chatMessage, position);
return view;
}
#Override
public int getViewTypeCount() {
// return the total number of view types. this value should never change
// at runtime
return 2;
}
#Override
public int getItemViewType(int position) {
// return a value between 0 and (getViewTypeCount - 1)
return position % 2;
}
}
P.S I have tried to paste code below into onResume method of MainActivity but nothing good is happening.
if (FirebaseAuth.getInstance().getCurrentUser() == null) {
// Start sign in/sign up activity
startActivityForResult(AuthUI.getInstance()
.createSignInIntentBuilder()
.build(), SIGN_IN_REQUEST_CODE);
} else {
// User is already signed in, show list of messages
showAllOldMessages();
}
P.P.S When I try to send new messages in chat, when there is a bug, I see them. But when I log out and login again, these messages are absent.
Check the logs when you close and re-open the app or if you want a tutorial here's one that uses firebase to create a chat application.
Part-1 https://www.youtube.com/watch?v=wVCz1a3ogqk
Part-2 https://www.youtube.com/watch?v=uX6_w6yhj4E

Categories

Resources