So, I am working on a single user text messaging app and the whole thing essentially works, but I'm experiencing an odd error with the conversation view (where the chatting takes place). Essentially, when the RecyclerView extends beyond a certain point, it seems to bug when it reads in the messages. The RecyclerView will expand, but messages won't display, or messages that were displaying will suddenly be invisible. I'm guessing I'm not sure if its how I'm updating the RecyclerView or how I'm loading data into the message blocks. Here is an example of the glitch:
Messages not displaying correctly
I've noticed that while scrolling up and down, the messages that are visible and invisible seem to change around, often leading to large groups of messages being invisible.
Here is the code for the Conversations activity:
package net.whispwriting.mantischat;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
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.firestore.DocumentReference;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import de.hdodenhof.circleimageview.CircleImageView;
public class Conversation extends AppCompatActivity {
private String userID, name, image;
private DocumentReference userDoc;
private CircleImageView profileIcon;
private FloatingActionButton sendMessageButton;
private FloatingActionButton attachImageButton;
private EditText messageBox;
private FirebaseUser currentUser;
private DatabaseReference rootRef;
private RecyclerView messagesView;
private List<Message> messageList = new ArrayList<>();
private LinearLayoutManager linearLayoutManager;
private MessageAdapter messageAdapter;
private StorageReference imageStorage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_conversation);
final Toolbar convToolbar = findViewById(R.id.conversation_bar);
setSupportActionBar(convToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
profileIcon = (CircleImageView) findViewById(R.id.profile_image_conv);
sendMessageButton = (FloatingActionButton) findViewById(R.id.sendMessage);
attachImageButton = (FloatingActionButton) findViewById(R.id.attachImageButton);
messageBox = (EditText) findViewById(R.id.message);
linearLayoutManager = new LinearLayoutManager(this);
messagesView = (RecyclerView) findViewById(R.id.conversation_recycler);
messageAdapter = new MessageAdapter(messageList, this, messagesView);
messagesView.setHasFixedSize(true);
messagesView.setLayoutManager(linearLayoutManager);
messagesView.setAdapter(messageAdapter);
userID = getIntent().getStringExtra("userID");
name = getIntent().getStringExtra("name");
image = getIntent().getStringExtra("image");
currentUser = FirebaseAuth.getInstance().getCurrentUser();
rootRef = FirebaseDatabase.getInstance().getReference();
imageStorage = FirebaseStorage.getInstance().getReference();
Picasso.get().load(image).placeholder(R.drawable.avatar).into(profileIcon);
getSupportActionBar().setTitle(name);
messagesView = (RecyclerView) findViewById(R.id.conversation_recycler);
loadMessages();
sendMessageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendMessage(messageBox.getText().toString(), "text");
messageBox.setText("");
}
});
attachImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.start(Conversation.this);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
sendMessage(resultUri.toString(), "image");
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
private void sendMessage(String message, String type){
final Map<String, String> messageMap = new HashMap<>();
DatabaseReference userMessagePush = rootRef.child("messages").child(currentUser.getUid())
.child(userID).push();
String pushID = userMessagePush.getKey();
String currentUserRef = "messages/" + currentUser.getUid() + "/" + userID;
String chatUserRef = "messages/" + userID + "/" + currentUser.getUid();
final Map<String, Object> messageUserMap = new HashMap<>();
messageUserMap.put(currentUserRef + "/" + pushID, messageMap);
messageUserMap.put(chatUserRef + "/" + pushID, messageMap);
if (type.equals("text")){
if (!TextUtils.isEmpty(message)) {
messageMap.put("message", message);
messageMap.put("type", "text");
messageMap.put("from", currentUser.getUid());
messageMap.put("timestamp", System.currentTimeMillis() + "");
rootRef.updateChildren(messageUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(#Nullable DatabaseError error, #NonNull DatabaseReference ref) {
if (error != null) {
Log.w("CHAT", error.getMessage());
}
}
});
}
}else{
final StorageReference filepath = imageStorage.child("message_images").child(pushID + ".jpg");
Uri imageUri = Uri.parse(message);
filepath.putFile(imageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(#NonNull Uri uri) {
messageMap.put("message", uri.toString());
messageMap.put("type", "image");
messageMap.put("from", currentUser.getUid());
messageMap.put("timestamp", System.currentTimeMillis() + "");
rootRef.updateChildren(messageUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(#Nullable DatabaseError error, #NonNull DatabaseReference ref) {
if (error != null) {
Log.w("CHAT", error.getMessage());
}
}
});
}
});
}
});
}
}
public void loadMessages(){
rootRef.child("messages").child(currentUser.getUid()).child(userID).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
Message message = snapshot.getValue(Message.class);
messageList.add(message);
messageAdapter.notifyDataSetChanged();
//messageAdapter.notifyItemInserted(messageList.size());
//messageAdapter.notifyItemInserted(messageList.size()-1);
}
#Override
public void onChildChanged(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot snapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
This line, messageAdapter.notifyDataSetChanged();, is where the view is updated. I commented out the other notifiers I've tried. Then there's my messages class, where the message views are configured.
package net.whispwriting.mantischat;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.MimeTypeMap;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageViewHolder>{
private List<Message> messageList;
private FirebaseUser currentUser;
private Context context;
private RecyclerView messageView;
public MessageAdapter(List<Message> messageList, Context context, RecyclerView messageView){
this.messageList = messageList;
currentUser = FirebaseAuth.getInstance().getCurrentUser();
this.context = context;
this.messageView = messageView;
}
#Override
public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.message_single_layout, parent, false);
return new MessageViewHolder(v);
}
#Override
public void onBindViewHolder(final MessageViewHolder viewHolder, final int i){
final Message message = messageList.get(i);
if (message.getFrom().equals(currentUser.getUid())){
viewHolder.messageText.setVisibility(View.INVISIBLE);
viewHolder.image.setVisibility(View.INVISIBLE);
if (message.getType().equals("image")){
viewHolder.sentMessageText.setVisibility(View.INVISIBLE);
Picasso.get().load(message.getMessage()).into(viewHolder.sentImage);
viewHolder.sentImage.setMaxHeight(50);
viewHolder.sentImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri uri = Uri.parse(message.getMessage());
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
String mime = "*/*";
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
if (mimeTypeMap.hasExtension(
mimeTypeMap.getFileExtensionFromUrl(uri.toString())))
mime = mimeTypeMap.getMimeTypeFromExtension(
mimeTypeMap.getFileExtensionFromUrl(uri.toString()));
intent.setDataAndType(uri,mime);
context.startActivity(intent);
}
});
}else {
viewHolder.sentImage.setVisibility(View.INVISIBLE);
viewHolder.sentMessageText.setText(message.getMessage());
}
}else{
viewHolder.sentMessageText.setVisibility(View.INVISIBLE);
FirebaseFirestore.getInstance().collection("Users").document(message.getFrom())
.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()){
DocumentSnapshot document = task.getResult();
if (document.exists()){
Picasso.get().load(document.getString("image"))
.networkPolicy(NetworkPolicy.OFFLINE)
.placeholder(R.drawable.avatar)
.into(viewHolder.image);
}
}
}
});
if (message.getType().equals("image")){
viewHolder.messageText.setVisibility(View.INVISIBLE);
Picasso.get().load(message.getMessage()).into(viewHolder.receivedImage);
viewHolder.receivedImage.setMaxHeight(50);
viewHolder.receivedImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri uri = Uri.parse(message.getMessage());
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
String mime = "*/*";
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
if (mimeTypeMap.hasExtension(
mimeTypeMap.getFileExtensionFromUrl(uri.toString())))
mime = mimeTypeMap.getMimeTypeFromExtension(
mimeTypeMap.getFileExtensionFromUrl(uri.toString()));
intent.setDataAndType(uri,mime);
context.startActivity(intent);
}
});
}else {
viewHolder.receivedImage.setVisibility(View.INVISIBLE);
viewHolder.messageText.setText(message.getMessage());
}
}
}
#Override
public int getItemCount(){
return messageList.size();
}
public class MessageViewHolder extends RecyclerView.ViewHolder{
private TextView messageText, sentMessageText;
private ImageView receivedImage, sentImage;
private CircleImageView image;
public MessageViewHolder(View view){
super(view);
messageText = (TextView) view.findViewById(R.id.messageText);
sentMessageText = (TextView) view.findViewById(R.id.sentMessageText);
receivedImage = (ImageView) view.findViewById(R.id.receivedImage);
sentImage = (ImageView) view.findViewById(R.id.sentImage);
image = (CircleImageView) view.findViewById(R.id.profile_image_message);
}
}
}
And then, the XML that holds the message view:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/profile_image_message"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentStart="true"
android:layout_marginStart="0dp"
tools:src="#drawable/avatar" />
<TextView
android:id="#+id/messageText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#id/profile_image_message"
android:layout_marginStart="14dp"
android:layout_toEndOf="#id/profile_image_message"
android:background="#drawable/message_background"
android:padding="15dp"
android:paddingTop="6dp"
android:paddingBottom="6dp"
android:text="TextView"
android:textSize="14sp" />
<TextView
android:id="#+id/sentMessageText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_marginEnd="0dp"
android:background="#drawable/current_message_background"
android:textColor="#android:color/white"
android:padding="15dp"
android:paddingTop="6dp"
android:paddingBottom="6dp"
android:text="TextView"
android:textSize="14sp" />
<ImageView
android:id="#+id/receivedImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/messageText"
android:layout_marginStart="14dp"
android:layout_toEndOf="#id/profile_image_message"
android:layout_alignEnd="#id/messageText"
android:maxHeight="50dp"
android:maxWidth="50dp"
android:scaleType="centerCrop" />
<ImageView
android:id="#+id/sentImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/sentMessageText"
android:layout_alignParentEnd="true"
android:layout_marginEnd="0dp"
android:layout_alignStart="#id/sentMessageText"
android:maxHeight="50dp"
android:maxWidth="50dp"
android:scaleType="centerCrop" />
</RelativeLayout>
The XML layout is used like this: Both message displays are side-by-side. If the message was received, the stuff for a sent message is hidden and the stuff for the received message is modify. When a message is sent, the opposite happens. I've been trying to figure out for a few days why this is happening, and I just have no idea. I hoped a second set of eyes might see something I'm missing that could be causing this. Any help with this is appreciated.
Well, I figured out what my own problem was. It was the maximum size of the RecyclerView's pool. Here's the fix:
recyclerView.getRecycledViewPool().setMaxRecycledViews(0, 0);
According to the documentation, the first int for viewType. I'm not sure what that means, but 0 seems to work. The second integer is the max count. Setting it to 0 I think disables the limit.
Related
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.
I have been trying to create a chat application and have implemented it using firestore database. The chat functionality works fine but as soon as the screen is filled and some scrolling is required to see the previous messages, the database updates in a weird way and the order becomes random and sometimes recent messages show up and sometimes older messages show up as a new message. I have used timestamp to order them but it doesn't seem to work. Even after using pagination, it didn't help. The data and order seem to change while scrolling the recycler view. I will put up the code and some screen shots for a better understanding.
Message Model.java
public class MessageModel {
String message, senderID, receiverID;
Long timestamp;
public MessageModel() {
}
public MessageModel(String senderID, String receiverID, String message, Long timestamp) {
this.senderID = senderID;
this.receiverID = receiverID;
this.message = message;
this.timestamp = timestamp;
}
public MessageModel(String senderID, String message) {
this.senderID = senderID;
this.message = message;
}
public String getReceiverID() {
return receiverID;
}
public void setReceiverID(String receiverID) {
this.receiverID = receiverID;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
public String getSenderID() {
return senderID;
}
public void setSenderID(String senderID) {
this.senderID = senderID;
}
}
Message Adapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.chatdemo.Models.MessageModel;
import com.example.chatdemo.databinding.ReceiverTextItemBinding;
import com.example.chatdemo.databinding.SenderTextItemBinding;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class NewMessageAdapter extends RecyclerView.Adapter {
private ReceiverTextItemBinding receiverTextItemBinding;
private SenderTextItemBinding senderTextItemBinding;
private Context context;
private FirebaseUser fUser;
private int SENDER_VIEW_TYPE = 1, RECEIVER_VIEW_TYPE = 2;
private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yy KK:mm a", Locale.US);
private List<MessageModel> mMessage;
public NewMessageAdapter(Context context, List<MessageModel> mMessage) {
this.context = context;
this.mMessage = mMessage;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == SENDER_VIEW_TYPE) {
senderTextItemBinding = SenderTextItemBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
return new SenderViewHolder(senderTextItemBinding.getRoot());
} else {
receiverTextItemBinding = ReceiverTextItemBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
return new ReceiverViewHolder(receiverTextItemBinding.getRoot());
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
MessageModel messageModel = mMessage.get(position);
if (holder.getClass() == SenderViewHolder.class) {
senderTextItemBinding.tvSenderText.setText(messageModel.getMessage());
senderTextItemBinding.tvSenderTextTime.setText(simpleDateFormat
.format(new Date(Long.parseLong(messageModel.getTimestamp().toString()))));
} else {
receiverTextItemBinding.tvReceiverText.setText(messageModel.getMessage());
receiverTextItemBinding.tvReceiverTextTime.setText(simpleDateFormat
.format(new Date(Long.parseLong(messageModel.getTimestamp().toString()))));
}
}
#Override
public int getItemCount() {
return mMessage.size();
}
#Override
public int getItemViewType(int position) {
fUser = FirebaseAuth.getInstance().getCurrentUser();
if (mMessage.get(position).getSenderID().equals(fUser.getUid())) {
return SENDER_VIEW_TYPE;
} else {
return RECEIVER_VIEW_TYPE;
}
}
public class ReceiverViewHolder extends RecyclerView.ViewHolder {
private TextView receivedMessage, receivedTime;
public ReceiverViewHolder(#NonNull View itemView) {
super(itemView);
receivedMessage = receiverTextItemBinding.tvReceiverText;
receivedTime = receiverTextItemBinding.tvReceiverTextTime;
}
}
public class SenderViewHolder extends RecyclerView.ViewHolder {
private TextView sentMessage, sentTime;
public SenderViewHolder(#NonNull View itemView) {
super(itemView);
sentMessage = senderTextItemBinding.tvSenderText;
sentTime = senderTextItemBinding.tvSenderTextTime;
}
}
}
Chat Activity
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.example.chatdemo.Adapters.ChatAdapter;
import com.example.chatdemo.Adapters.NewMessageAdapter;
import com.example.chatdemo.Constants.Constants;
import com.example.chatdemo.Models.MessageModel;
import com.example.chatdemo.databinding.ActivityChatDetailBinding;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
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.ListenerRegistration;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
public class ChatDetailActivity extends AppCompatActivity {
private ActivityChatDetailBinding binding;
private Constants constants;
private MessageModel messageModel;
private FirebaseAuth firebaseAuth;
private FirebaseFirestore firestoreDB;
private String userID;
private FirestoreRecyclerOptions<MessageModel> options;
private ChatAdapter chatAdapter;
public static final String TAG = "paginate";
private NewMessageAdapter newMessageAdapter;
private RecyclerView recyclerView;
private List<MessageModel> mMessage;
private final int limit = 15;
private DocumentSnapshot lastVisible;
private boolean isScrolling = false;
private boolean isLastItemReached = false;
private String senderID, receiverID, receiverName, receiverPhoto;
private CollectionReference collectionReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityChatDetailBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
firebaseAuth = FirebaseAuth.getInstance();
firestoreDB = FirebaseFirestore.getInstance();
userID = firebaseAuth.getUid();
constants = new Constants();
senderID = firebaseAuth.getUid();
receiverID = getIntent().getStringExtra("receiverID");
receiverName = getIntent().getStringExtra("receiverName");
receiverPhoto = getIntent().getStringExtra("receiverPhoto");
binding.chatUserName.setText(receiverName);
Glide.with(getApplicationContext())
.load(Uri.parse(receiverPhoto))
.into(binding.chatUserImage);
binding.btnChatBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Go back
startActivity(new Intent(ChatDetailActivity.this, MainActivity.class));
}
});
collectionReference = firestoreDB.collection(constants.getChats())
.document(userID)
.collection(constants.getMessages())
.document(receiverID)
.collection(constants.getMessages());
binding.btnSendChat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!binding.etMessage.getText().toString().equals("")) {
String message = binding.etMessage.getText().toString().trim();
messageModel = new MessageModel(senderID, receiverID, message, new Date().getTime());
binding.etMessage.setText("");
ProgressDialog progressDialog = new ProgressDialog(ChatDetailActivity.this);
progressDialog.setMessage("Sending...");
progressDialog.show();
firestoreDB.collection(constants.getChats())
.document(userID)
.collection(constants.getMessages())
.document(receiverID)
.collection(constants.getMessages())
.add(messageModel)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
firestoreDB.collection(constants.getChats())
.document(receiverID)
.collection(constants.getMessages())
.document(userID)
.collection(constants.getMessages())
.add(messageModel)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
progressDialog.dismiss();
Toast.makeText(ChatDetailActivity.this, "Message Sent", Toast.LENGTH_SHORT).show();
}
});
}
});
progressDialog.dismiss();
}
}
});
collectionReference.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException error) {
Toast.makeText(ChatDetailActivity.this, "Change", Toast.LENGTH_SHORT).show();
readMessage(userID, receiverID);
}
});
initNewRecycler();
}
private void initNewRecycler() {
recyclerView = binding.chatRecyclerView;
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setStackFromEnd(false);
linearLayoutManager.setReverseLayout(true);
recyclerView.setLayoutManager(linearLayoutManager);
}
private void readMessage(String userID, String receiverID) {
mMessage = new ArrayList<>();
collectionReference.orderBy("timestamp", Query.Direction.DESCENDING).limit(limit)
.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
mMessage.clear();
for (QueryDocumentSnapshot snapshot : queryDocumentSnapshots) {
MessageModel model = snapshot.toObject(MessageModel.class);
if (model.getReceiverID().equals(userID) && model.getSenderID().equals(receiverID)
|| model.getReceiverID().equals(receiverID) && model.getSenderID().equals(userID)) {
mMessage.add(model);
}
newMessageAdapter = new NewMessageAdapter(ChatDetailActivity.this, mMessage);
recyclerView.setAdapter(newMessageAdapter);
}
}
});
}
}
Firebase firestore database structure
Firebase-root
|
---- chats
|
---- userID
|
---messages
|
---receiverID
|
---messages
|
---- message: "Hello!"
|
---- timestamp: 1498472455940
|
---- senderID: senderID
|
---- receiverID: receiverID
Some sample screenshots of the problem I have been facing
The first screen is what appears when the chat activity is first opened and the messages are displayed. Here everything works fine and the messaging system works.
In the second picture however we can see that when the user scrolls up to see the previous messages, some of them are shown correctly but some of them like "Does it work" and "No perhaps" have different time and some are not in the correct order. This happens frequently whenever the user scrolls the list
This is the problem I have been facing for quite a while now. I am not sure what is causing this kind of behaviour and would love to have some light shed in this issue. If anyone can help, it would be highly appreciated. Thanks.
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.
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...
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.