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.
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.
This question already has answers here:
Android - Client-side sorting with FirebaseRecyclerAdapter
(1 answer)
FirebaseRecyclerPagingAdapter - sort list by date
(1 answer)
Cannot retrieve data in ascending order
(2 answers)
Firebase Data Desc Sorting in Android
(19 answers)
How to arrange firebase database data in ascending or descending order?
(2 answers)
Closed 8 months ago.
As now i am working on a chat application, here i have a problem that how can i display my last recent chat on the top of the recyclerview in ChatlistFragment,
for example if i had recently sent my last message to any user they have to displayed at the top of my recyclerview, here is my code
package com.micoder.whatsappclone;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class ChatsFragment extends Fragment {
private View PrivateChatsView;
private RecyclerView chatsList;
private DatabaseReference ChatsRef, UsersRef;
private FirebaseAuth mAuth;
private String currentUserID;
FloatingActionMenu fabMenu;
FloatingActionButton fabSettings, fabShare, fabContactDev;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
PrivateChatsView = inflater.inflate(R.layout.fragment_chats, container, false);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
ChatsRef = FirebaseDatabase.getInstance().getReference().child("Messages").child(currentUserID);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
chatsList = (RecyclerView) PrivateChatsView.findViewById(R.id.chats_list);
chatsList.setLayoutManager(new LinearLayoutManager(getContext()));
fabOptions();
return PrivateChatsView;
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerOptions<Contacts> options =
new FirebaseRecyclerOptions.Builder<Contacts>()
.setQuery(ChatsRef, Contacts.class)
.build();
FirebaseRecyclerAdapter<Contacts, ChatsViewHolder> adapter =
new FirebaseRecyclerAdapter<Contacts, ChatsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull ChatsViewHolder holder, int position, #NonNull Contacts model) {
final String usersIDs = getRef(position).getKey();
final String[] retImage = {"default_image"};
UsersRef.child(usersIDs).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child("userState").hasChild("state")) {
String state = dataSnapshot.child("userState").child("state").getValue().toString();
if (state.equals("online")) {
holder.onlineIcon.setVisibility(View.VISIBLE);
}
else if (state.equals("offline")) {
holder.onlineIcon.setVisibility(View.INVISIBLE);
}
}
else {
holder.onlineIcon.setVisibility(View.INVISIBLE);
}
if (dataSnapshot.exists()) {
if (dataSnapshot.hasChild("image")) {
retImage[0] = dataSnapshot.child("image").getValue().toString();
Picasso.get().load(retImage[0]).placeholder(R.drawable.profile_image).into(holder.profileImage);
}
final String retName = dataSnapshot.child("name").getValue().toString();
holder.userName.setText(retName);
if (dataSnapshot.child("userState").hasChild("state")) {
String state = dataSnapshot.child("userState").child("state").getValue().toString();
String date = dataSnapshot.child("userState").child("date").getValue().toString();
String time = dataSnapshot.child("userState").child("time").getValue().toString();
if (state.equals("online")) {
holder.userStatus.setText("online");
}
else if (state.equals("offline")) {
holder.userStatus.setText("Last Seen: " + date + " " + time);
}
}
else {
holder.userStatus.setText("offline");
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent chatIntent = new Intent(getContext(), ChatActivity.class);
chatIntent.putExtra("visit_user_id", usersIDs);
chatIntent.putExtra("visit_user_name", retName);
chatIntent.putExtra("visit_image", retImage[0]);
startActivity(chatIntent);
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#NonNull
#Override
public ChatsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.users_display_chats_layout, viewGroup, false);
return new ChatsViewHolder(view);
}
};
chatsList.setAdapter(adapter);
adapter.startListening();
}
public static class ChatsViewHolder extends RecyclerView.ViewHolder {
CircleImageView profileImage;
TextView userName, userStatus;
ImageView onlineIcon;
public ChatsViewHolder(#NonNull View itemView) {
super(itemView);
profileImage = itemView.findViewById(R.id.users_profile_image);
userName = itemView.findViewById(R.id.user_profile_name);
userStatus = itemView.findViewById(R.id.user_status);
onlineIcon = itemView.findViewById(R.id.user_online_status);
}
}
public void fabOptions() {
//FAB
fabMenu=PrivateChatsView.findViewById(R.id.fabMenu);
fabSettings=PrivateChatsView.findViewById(R.id.fabSettings);
fabContactDev=PrivateChatsView.findViewById(R.id.fabContactDev);
fabShare=PrivateChatsView.findViewById(R.id.fabShare);
fabShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "My application name");
String shareMessage= "\nLet me recommend you this application\n\n";
shareMessage = shareMessage + "https://play.google.com/store/apps/developer?id=MI_CODER"+"\n\n";
shareIntent.putExtra(Intent.EXTRA_TEXT, shareMessage);
startActivity(Intent.createChooser(shareIntent, "choose one"));
} catch(Exception e) {
//e.toString();
}
fabMenu.close(true);
}
});
fabSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Settings", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getActivity(),SettingsActivity.class));
fabMenu.close(true);
}
});
fabContactDev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(),"Loading...",Toast.LENGTH_SHORT).show();
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://micoder-dev.github.io/Resume-Page/"));
startActivity(browserIntent);
fabMenu.close(true);
}
});
}
}
if you need to refer my complete source code you can get here => https://github.com/Micoder-dev/ChatApp-FE-UI.git
I think this will help you to make it easier to get a solution.
This question already has answers here:
Firebase No properties to serialize found on class
(12 answers)
Firebase release apk not loading data
(3 answers)
Firebase AndroidChat release build error
(3 answers)
Closed 2 years ago.
On my android studio debug theres nothing problem, but when i publish the app to playstore my app was close after splashscreen. my apps using firebase, and i have to added SHA-1 from playstore to my firebase project. but still cant crash :
this error i got from play console :
com.google.firebase.database.DatabaseException:
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.<init> (CustomClassMapper.java:11)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.loadOrCreateBeanMapperForClass (CustomClassMapper.java)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean (CustomClassMapper.java:4)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass (CustomClassMapper.java:4)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass (CustomClassMapper.java:8)
at com.google.firebase.database.DataSnapshot.getValue (DataSnapshot.java:8)
at com.kepulcorporation.kepul.HomeFragment$10.onDataChange (HomeFragment.java:8)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent (ValueEventRegistration.java:2)
at com.google.firebase.database.core.view.DataEvent.fire (DataEvent.java)
at com.google.firebase.database.core.view.EventRaiser$1.run (EventRaiser.java:6)
at android.os.Handler.handleCallback (Handler.java:751)
at android.os.Handler.dispatchMessage (Handler.java:95)
at android.os.Looper.loop (Looper.java:154)
at android.app.ActivityThread.main (ActivityThread.java:6121)
at java.lang.reflect.Method.invoke (Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:779)
this is my main activity :
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Registry;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.module.AppGlideModule;
import com.firebase.ui.storage.images.FirebaseImageLoader;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.storage.StorageReference;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private ActionBar actionBar;
private NestedScrollView nested_scroll_view;
private BottomSheetBehavior mBehavior;
private BottomSheetDialog mBottomSheetDialog;
private View bottom_sheet;
private HorizontalScrollView horizontalScrollView;
private Fragment fragment;
private Fragment fragmenthome;
private SessionManager sessionManager;
RelativeLayout toolbar;
LinearLayout content;
NestedScrollView scrolllayout;
ImageView home_icon, transaksi_icon, bantuan_icon, akun_icon;
TextView home_text, transaksi_text, bantuan_text, akun_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
content = findViewById(R.id.list_category_item_dashboard);
scrolllayout = findViewById(R.id.nested_scroll_view);
//Set Theme
Tools.setSystemBarColor(this, R.color.colorPrimary);
sessionManager = new SessionManager(this);
sessionManager.checkLogin(this);
home_icon = findViewById(R.id.home_icon);
transaksi_icon = findViewById(R.id.transaksi_icon);
bantuan_icon = findViewById(R.id.bantuan_icon);
akun_icon = findViewById(R.id.akun_icon);
home_text = findViewById(R.id.home_text);
transaksi_text = findViewById(R.id.transaksi_text);
bantuan_text = findViewById(R.id.bantuan_text);
akun_text = findViewById(R.id.akun_text);
FirebaseMessaging.getInstance().getToken()
.addOnCompleteListener(new OnCompleteListener<String>() {
#Override
public void onComplete(#NonNull Task<String> task) {
if (!task.isSuccessful()) {
// Toast.makeText(MainActivity.this, "Fetching FCM registration token failed", Toast.LENGTH_SHORT).show();
return;
}
// Get new FCM registration token
String token = task.getResult();
if(sessionManager.isLoggin())
{
save_fcm(token);
}
}
});
initComponent();
}
public void save_fcm(String token){
HashMap<String, String> user;
sessionManager = new SessionManager(MainActivity.this);
user = sessionManager.getUserDetail();
String email = user.get("EMAIL");
String convertemail = email.replaceAll("\\.", "_");
FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference tableuser = database.getReference("Users");
tableuser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String email = user.get("EMAIL");
String convertemail = email.replaceAll("\\.", "_");
Users users = snapshot.child(convertemail).getValue(Users.class);
Map<String, Object> updates = new HashMap<String,Object>();
updates.put("address", users.getAddress());
updates.put("email", email);
updates.put("name", users.getName());
updates.put("password", users.getPassword());
updates.put("phone", users.getPhone());
updates.put("photo_profile_path", users.getPhoto_profile_path());
updates.put("role_id", users.getRole_id());
updates.put("point", users.getPoint());
updates.put("token", token);
updates.put("promosipush", users.getPromosipush());
updates.put("promosiemail", users.getPromosiemail());
updates.put("statuspush", users.getStatuspush());
updates.put("statusemail", users.getStatusemail());
tableuser.child(convertemail).setValue(updates);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void initComponent() {
nested_scroll_view = (NestedScrollView) findViewById(R.id.nested_scroll_view);
fragment = new HomeFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment,
fragment.getClass().getSimpleName()).commit();
home_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.colorPrimary));
home_text.setTextColor(this.getResources().getColor(R.color.colorPrimary));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
} else {
Toast.makeText(getApplicationContext(), item.getTitle(), Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
public void toHome(View view) {
ViewAnimation.fadeOutIn(nested_scroll_view);
if (sessionManager.isLoggin()){
fragment = new HomeFragment();
}
else {
fragment = new HomeFragment();
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment,
fragment.getClass().getSimpleName()).commit();
home_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.colorPrimary));
home_text.setTextColor(this.getResources().getColor(R.color.colorPrimary));
transaksi_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
transaksi_text.setTextColor(this.getResources().getColor(R.color.text));
bantuan_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
bantuan_text.setTextColor(this.getResources().getColor(R.color.text));
akun_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
akun_text.setTextColor(this.getResources().getColor(R.color.text));
}
public void toTransaksi(View view) {
ViewAnimation.fadeOutIn(nested_scroll_view);
if (sessionManager.isLoggin()){
fragment = new TransaksiloginFragment();
}
else {
fragment = new TransaksiFragment();
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment,
fragment.getClass().getSimpleName()).commit();
home_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
home_text.setTextColor(this.getResources().getColor(R.color.text));
transaksi_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.colorPrimary));
transaksi_text.setTextColor(this.getResources().getColor(R.color.colorPrimary));
bantuan_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
bantuan_text.setTextColor(this.getResources().getColor(R.color.text));
akun_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
akun_text.setTextColor(this.getResources().getColor(R.color.text));
}
public void toBantuan(View view){
ViewAnimation.fadeOutIn(nested_scroll_view);
if (sessionManager.isLoggin()){
fragment = new BantuanFragment();
}
else {
fragment = new BantuanFragment();
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment,
fragment.getClass().getSimpleName()).commit();
home_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
home_text.setTextColor(this.getResources().getColor(R.color.text));
transaksi_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
transaksi_text.setTextColor(this.getResources().getColor(R.color.text));
bantuan_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.colorPrimary));
bantuan_text.setTextColor(this.getResources().getColor(R.color.colorPrimary));
akun_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
akun_text.setTextColor(this.getResources().getColor(R.color.text));
}
public void toAkun(View view){
ViewAnimation.fadeOutIn(nested_scroll_view);
if (sessionManager.isLoggin()){
fragment = new AkunLoginFragment();
}
else {
fragment = new AkunFragment();
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment,
fragment.getClass().getSimpleName()).commit();
home_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
home_text.setTextColor(this.getResources().getColor(R.color.text));
transaksi_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
transaksi_text.setTextColor(this.getResources().getColor(R.color.text));
bantuan_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
bantuan_text.setTextColor(this.getResources().getColor(R.color.text));
akun_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.colorPrimary));
akun_text.setTextColor(this.getResources().getColor(R.color.colorPrimary));
}
public void toSell(View view) {
ViewAnimation.fadeOutIn(nested_scroll_view);
if (sessionManager.isLoggin()){
startActivity(new Intent(MainActivity.this, JualsampahActivity.class));
}
else {
fragment = new JualFragment();
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment,
fragment.getClass().getSimpleName()).commit();
home_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
home_text.setTextColor(this.getResources().getColor(R.color.text));
transaksi_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
transaksi_text.setTextColor(this.getResources().getColor(R.color.text));
bantuan_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
bantuan_text.setTextColor(this.getResources().getColor(R.color.text));
akun_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
akun_text.setTextColor(this.getResources().getColor(R.color.text));
}
}
and this my HomeFragment :
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.media.Image;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.github.islamkhsh.CardSliderViewPager;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import org.w3c.dom.Text;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
import ru.tinkoff.scrollingpagerindicator.ScrollingPagerIndicator;
public class HomeFragment extends Fragment {
CardSliderViewPager cardSliderViewPager;
private List<Category>listData;
private List<Produk>listData1;
private List<SliderData>sliderData;
private RecyclerView rv;
private CategoryAdapter adapter;
private ProdukAdapter adapter1;
private SliderAdapter sliderAdapter;
private RecyclerView recyclerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View root = inflater.inflate(R.layout.fragment_home, container, false);
cardSliderViewPager = root.findViewById(R.id.viewPager);
recyclerView = root.findViewById(R.id.product_recyclerview);
rv = root.findViewById(R.id.category_recyclerview);
rv.setHasFixedSize(true);
rv.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
listData=new ArrayList<>();
listData1 = new ArrayList<>();
sliderData = new ArrayList<>();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference table = database.getReference("Category");
table.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(isAdded())
{
listData.clear();
for (DataSnapshot npsnapshot : snapshot.getChildren()){
Category l = npsnapshot.getValue(Category.class);
listData.add(l);
}
adapter=new CategoryAdapter(listData);
rv.setAdapter(adapter);
ScrollingPagerIndicator recyclerIndicator = root.findViewById(R.id.indicator2);
recyclerIndicator.attachToRecyclerView(rv);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
final SessionManager sessionManager = new SessionManager(getActivity());
HashMap<String, String> user = sessionManager.getUserDetail();
String email = user.get("EMAIL");
if(!sessionManager.isLoggin())
{
LinearLayout not_login = root.findViewById(R.id.not_login);
LinearLayout login = root.findViewById(R.id.login);
not_login.setVisibility(View.VISIBLE);
login.setVisibility(View.GONE);
}
else {
LinearLayout not_login = root.findViewById(R.id.not_login);
LinearLayout login = root.findViewById(R.id.login);
not_login.setVisibility(View.GONE);
login.setVisibility(View.VISIBLE);
FirebaseDatabase databaseuser = FirebaseDatabase.getInstance();
DatabaseReference tableuseruser = databaseuser.getReference("Users");
tableuseruser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(isAdded())
{
String convertemail = email.toString().replaceAll("\\.", "_").toString();
Users users = snapshot.child(convertemail).getValue(Users.class);
TextView point = root.findViewById(R.id.profile_point);
TextView name = root.findViewById(R.id.profile_name);
CircleImageView circleImageView = root.findViewById(R.id.profile_image);
name.setText(user.get("NAME"));
point.setText(users.getPoint().toString() + " Point");
if (user.get("PHOTO_PROFILE_PATH").equals(""))
{
Glide.with(getContext()).load("https://cdn.business2community.com/wp-content/uploads/2017/08/blank-profile-picture-973460_640.png").into(circleImageView);
}
else {
Glide.with(getContext()).load(user.get("PHOTO_PROFILE_PATH")).into(circleImageView);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
getbanner();
FirebaseDatabase databasepro = FirebaseDatabase.getInstance();
DatabaseReference tablepro = databasepro.getReference("Product");
tablepro.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(isAdded())
{
listData1.clear();
for (DataSnapshot npsnapshot : snapshot.getChildren()){
Produk l = npsnapshot.getValue(Produk.class);
listData1.add(l);
}
adapter1 = new ProdukAdapter((ArrayList<Produk>) listData1);
recyclerView.setAdapter(adapter1);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
LinearLayout jual = root.findViewById(R.id.btn_jual);
LinearLayout sedekah = root.findViewById(R.id.btn_sedekah);
LinearLayout baitullah = root.findViewById(R.id.btn_baitullah);
ImageView notif = root.findViewById(R.id.notif);
ReddotNotif reddotNotif = new ReddotNotif(getContext());
if(reddotNotif.isRedDot())
{
notif.setImageResource(R.drawable.ic_notify);
}
else {
notif.setImageResource(R.drawable.ic_notif);
}
notif.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
reddotNotif.logout();
startActivity(new Intent(getActivity(), HistorynotificationActivity.class));
}
});
baitullah.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(sessionManager.isLoggin())
{
startActivity(new Intent(getActivity(), MenujubaitullahActivity.class));
}
else {
Intent intent = new Intent(getActivity(), MustloginActivity.class);
intent.putExtra("type", "baitullah");
startActivity(intent);
}
}
});
jual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(sessionManager.isLoggin())
{
startActivity(new Intent(getActivity(), JualsampahActivity.class));
}
else {
Intent intent = new Intent(getActivity(), MustloginActivity.class);
intent.putExtra("type", "jual");
startActivity(intent);
}
}
});
sedekah.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Boolean login = false;
if(sessionManager.isLoggin())
{
startActivity(new Intent(getActivity(), SedekahsampahActivity.class));
}
else {
Intent intent = new Intent(getActivity(), MustloginActivity.class);
intent.putExtra("type", "sedekah");
startActivity(intent);
}
}
});
Button login = root.findViewById(R.id.login_button);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), LoginActivity.class));
}
});
TextView FAQ = root.findViewById(R.id.faq);
String FAQTEXT = "Untuk informasi lebih lanjut, kunjungi halaman FAQ. <font color=#0098FF>di sini </font> ";
FAQ.setText(Html.fromHtml(FAQTEXT));
FAQ.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getActivity(), FaqActivity.class));
}
});
return root;
}
private void getbanner() {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference table = database.getReference("Banner");
table.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(isAdded())
{
sliderData.clear();
for (DataSnapshot npsnapshot : snapshot.getChildren()){
SliderData l = npsnapshot.getValue(SliderData.class);
sliderData.add(l);
}
sliderAdapter = new SliderAdapter((ArrayList<SliderData>) sliderData);
cardSliderViewPager.setAdapter(sliderAdapter);
cardSliderViewPager.setSmallScaleFactor(0.9f);
cardSliderViewPager.setSmallAlphaFactor(0.5f);
cardSliderViewPager.setAutoSlideTime(5);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
this my Category class :
public class Category {
private String id;
private String name;
private String picture_path;
public Category(){
}
public Category(String id, String name, String picture_path) {
this.id = id;
this.name = name;
this.picture_path = picture_path;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPicture_path() {
return picture_path;
}
public void setPicture_path(String picture_path) {
this.picture_path = picture_path;
}
}
and this category at database :
category database
can you help me please, I've been looking for a week where it went wrong, but still can't find it.
Facing an error.
I am making a chat application with firebase. where i am sending and printing the data from Firebase Realtime Database. the issue is that whenever i am adding or sending a data into the Firebase Realtime Database, its not only printing the currently added data but also printing the whole data from node Chats again and again wherever any data added into the Firebase Realtime Database.
how can i fix this?
Whats my think to solve the error?
I think removing of event listener which are being attached on call of
getMessage(); can fix the error.
This is my ChatActivity
package com.socialcodia.sherewatan;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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.socialcodia.sherewatan.adapter.ChatAdapter;
import com.socialcodia.sherewatan.model.ChatModel;
import com.socialcodia.sherewatan.storage.Constants;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class ChatActivity extends AppCompatActivity {
Toolbar toolbar;
private EditText inputMessage;
private ImageButton btnSendMessage;
private TextView toolbarUserName, toolbarUserStatus;
private ImageView toolbarUserImage;
//Firebase
FirebaseAuth firebaseAuth;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
DatabaseReference chatDatabaseReference;
FirebaseUser firebaseUser;
RecyclerView chatRecyclerView;
Intent intent;
String toUid;
String myUid;
List<ChatModel> chatList;
ChatAdapter chatAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
//init Chat Recycler View
chatRecyclerView = findViewById(R.id.chatRecyclerView);
//set layout manager at chatRecyclerview
LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
chatRecyclerView.setLayoutManager(layoutManager);
//Firebase Init
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Users");
chatDatabaseReference = firebaseDatabase.getReference("Chats");
firebaseUser =firebaseAuth.getCurrentUser();
//Init
inputMessage = findViewById(R.id.inputMessage);
btnSendMessage = findViewById(R.id.btnSendMessage);
toolbarUserName = findViewById(R.id.toolbarUserName);
toolbarUserStatus = findViewById(R.id.toolbarUserStatus);
toolbarUserImage = findViewById(R.id.toolbarUserImage);
toolbar = findViewById(R.id.chat_toolbar);
setSupportActionBar(toolbar);
intent = getIntent();
//Data From intent
toUid = intent.getStringExtra("uid");
//Click listener on btn send message
btnSendMessage.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
ValidateAndSendMessage();
}
});
getMessage();
}
private void ValidateAndSendMessage()
{
String message = inputMessage.getText().toString().trim();
if (message.isEmpty())
{
Toast.makeText(this, "Can't send empty message", Toast.LENGTH_SHORT).show();
}
else
{
sendMessage(message);
}
}
private void sendMessage(String message)
{
HashMap<String, Object> map = new HashMap<>();
map.put("msg",message);
map.put(Constants.TIMESTAMP,System.currentTimeMillis()/1000);
map.put("fromUid",myUid);
map.put("toUid",toUid);
DatabaseReference chatRef = firebaseDatabase.getReference("Chats");
chatRef.push().setValue(map);
inputMessage.setText("");
}
private void getMessage()
{
chatList = new ArrayList<>();
final DatabaseReference chatRef = firebaseDatabase.getReference("Chats");
chatRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren())
{
ChatModel chatModel = ds.getValue(ChatModel.class);
if (chatModel.getFromUid().equals(myUid) && chatModel.getToUid().equals(toUid) ||
chatModel.getFromUid().equals(toUid) && chatModel.getToUid().equals(myUid))
{
chatList.add(chatModel);
}
chatAdapter = new ChatAdapter(chatList,getApplicationContext());
chatAdapter.notifyDataSetChanged();
chatRecyclerView.setAdapter(chatAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
This is my ChatAdapter.class
package com.socialcodia.sherewatan.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.socialcodia.sherewatan.R;
import com.socialcodia.sherewatan.model.ChatModel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ChatViewHolder> {
List<ChatModel> modelClassList;
Context context;
private static final int MSG_TYPE_RIGHT = 0;
private static final int MSG_TYPE_LEFT = 1;
FirebaseUser firebaseUser;
public ChatAdapter(List<ChatModel> modelClassList, Context context) {
this.modelClassList = modelClassList;
this.context = context;
}
#NonNull
#Override
public ChatViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType==MSG_TYPE_RIGHT)
{
View view = LayoutInflater.from(context).inflate(R.layout.chat_right,parent,false);
ChatViewHolder viewHolder = new ChatViewHolder(view);
return viewHolder;
}
else
{
View view = LayoutInflater.from(context).inflate(R.layout.chat_left,parent,false);
ChatViewHolder viewHolder = new ChatViewHolder(view);
return viewHolder;
}
}
#Override
public void onBindViewHolder(#NonNull ChatViewHolder holder, int position) {
String msg = modelClassList.get(position).getMsg();
Long timestamp = modelClassList.get(position).getTimestamp();
holder.tvChatMessage.setText(msg);
holder.tvChatTime.setText(getTime(timestamp));
}
private String getTime(Long timestamp) {
Long ts = timestamp*1000;
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:a");
String time = sdf.format(new Date(ts));
return time;
}
#Override
public int getItemCount() {
return modelClassList.size();
}
#Override
public int getItemViewType(int position) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (modelClassList.get(position).getFromUid().equals(firebaseUser.getUid()))
{
return MSG_TYPE_RIGHT;
}
else
{
return MSG_TYPE_LEFT;
}
}
public class ChatViewHolder extends RecyclerView.ViewHolder
{
private TextView tvChatMessage, tvChatTime;
public ChatViewHolder(#NonNull View itemView) {
super(itemView);
tvChatMessage = itemView.findViewById(R.id.tvChatMessage);
tvChatTime = itemView.findViewById(R.id.tvChatTime);
}
}
}
This is my ChatModel.class
package com.socialcodia.sherewatan.model;
public class ChatModel {
public String fromUid, toUid, msg;
Long timestamp;
public ChatModel() {
}
public ChatModel(String fromUid, String toUid, String msg, Long timestamp) {
this.fromUid = fromUid;
this.toUid = toUid;
this.msg = msg;
this.timestamp = timestamp;
}
public String getFromUid() {
return fromUid;
}
public void setFromUid(String fromUid) {
this.fromUid = fromUid;
}
public String getToUid() {
return toUid;
}
public void setToUid(String toUid) {
this.toUid = toUid;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
}
You forgot to clear the modelClassList.
private void getMessage()
{
chatList = new ArrayList<>();
final DatabaseReference chatRef = firebaseDatabase.getReference("Chats");
chatRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
chatList.clear(); // Clear list
for (DataSnapshot ds : dataSnapshot.getChildren())
{
ChatModel chatModel = ds.getValue(ChatModel.class);
if (chatModel.getFromUid().equals(myUid) && chatModel.getToUid().equals(toUid) ||
chatModel.getFromUid().equals(toUid) && chatModel.getToUid().equals(myUid))
{
chatList.add(chatModel);
}
chatAdapter = new ChatAdapter(chatList,getApplicationContext());
chatAdapter.notifyDataSetChanged();
chatRecyclerView.setAdapter(chatAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
That will clear the list as well fix your problem.
Declare HashMap or ArrayList globally and write this code map.clear() or arrayList.clear() at the very beginning of the method from which you are retreiving your data. Hopefully the problem will be solved.
public class Constant {
public static final String FIREBASE_CHAT_URL="https://roadcaremap.firebaseio.com/";
public static final String CHILD_USERS="users";
public static final String CHILD_CHAT="chat";
public static final String KEY_SEND_USER="key_send_user";
public static final String CHILD_CONNECTION="connecttion";
public static final String CHILD_LATITUDE="latitude";
public static final String CHILD_LONGITUDE="longitude";
public static final String KEY_EMAIL="email";
public static final String KEY_ONLINE="online";
public static final String KEY_OFFLINE="offline";
public static final String KEY_CLOSE="key_close";
}
I'm new to android. Recently, I encountered a problem when running the application on my device. The app crashes and shows me an error on this line which I do not know how to solve. I've added the code and picture of the logcat. Any help would be much appreciated. The error is shown in this line.
rootUrl = new Firebase(Constant.FIREBASE_CHAT_URL);
package com.snapsofts.demogmap.activity;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.firebase.client.AuthData;
import com.firebase.client.ChildEventListener;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import com.firebase.ui.auth.AuthUI;
import com.google.firebase.auth.FirebaseAuth;
import com.google.gson.Gson;
import com.snapsofts.demogmap.R;
import com.snapsofts.demogmap.Services.LocationService;
import com.snapsofts.demogmap.common.Constant;
import com.snapsofts.demogmap.object.User;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity {
private Firebase rootUrl;
private Firebase urlCurrenUser;
private Firebase urlAllUser;
private FirebaseAuth mAuth;
private Firebase.AuthStateListener mAuthStateListener;
private String currenUserId;
private String currenUserEmail;
private ArrayList<User> arrUser;
private AllUserAdapter allUserAdapter;
private ArrayList<String> arrStringEmail;
private ValueEventListener valueEventListenerUserConnected;
private User currenUser;
#BindView(R.id.btnLogout)
Button btnLogout;
#BindView(R.id.lvUser)
ListView lvUser;
#BindView(R.id.tvUsserName)
TextView tvUsserName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
MainActivity.this.startService(new Intent(MainActivity.this, LocationService.class));
arrStringEmail = new ArrayList<>();
arrUser = new ArrayList<User>();
allUserAdapter = new AllUserAdapter(MainActivity.this, 0, arrUser);
lvUser.setAdapter(allUserAdapter);
lvUser.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent=new Intent(MainActivity.this,MapsActivity.class);
User user=arrUser.get(position);
Gson gson=new Gson();
intent.putExtra(Constant.KEY_SEND_USER,gson.toJson(user).toString()+"---"+gson.toJson(currenUser).toString());
startActivity(intent);
mAuth = FirebaseAuth.getInstance();
}
});
rootUrl = new Firebase(Constant.FIREBASE_CHAT_URL);
mAuthStateListener = new Firebase.AuthStateListener() {
#Override
public void onAuthStateChanged(AuthData authData) {
setAuthenticatedUser();
}
};
rootUrl.addAuthStateListener(mAuthStateListener);
}
private void setAuthenticatedUser () {
if (FirebaseAuth.getInstance().getCurrentUser() != null) {
currenUserId = FirebaseAuth.getInstance().getCurrentUser().getUid();
currenUserEmail = FirebaseAuth.getInstance().getCurrentUser().getEmail();
getCurrenUser();
getAllUser();
} else {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
}
public void getCurrenUser() {
urlCurrenUser = new Firebase(Constant.FIREBASE_CHAT_URL).child(Constant.CHILD_USERS).child(FirebaseAuth.getInstance().getCurrentUser().getUid());
urlCurrenUser.addValueEventListener(valueEventListenerCurrenUser);
valueEventListenerUserConnected=rootUrl.getRoot().child(".info/connected").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
boolean connected = (Boolean) dataSnapshot.getValue();
if (connected) {
urlCurrenUser.child(Constant.CHILD_CONNECTION).setValue(Constant.KEY_ONLINE);
urlCurrenUser.child(Constant.CHILD_CONNECTION).onDisconnect().setValue(Constant.KEY_OFFLINE);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
private ValueEventListener valueEventListenerCurrenUser = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
tvUsserName.setText("Hello "+user.name);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
};
public void getAllUser() {
urlAllUser = new Firebase(Constant.FIREBASE_CHAT_URL).child(Constant.CHILD_USERS);
urlAllUser.addChildEventListener(childEventListenerAllUser);
}
private ChildEventListener childEventListenerAllUser = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
User user = dataSnapshot.getValue(User.class);
if (!dataSnapshot.getKey().equals(currenUserId)){
arrStringEmail.add(user.email);
arrUser.add(user);
allUserAdapter.notifyDataSetChanged();
}else {
currenUser=user;
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
if (!dataSnapshot.getKey().equals(currenUserId)){
User user = dataSnapshot.getValue(User.class);
int index = arrStringEmail.indexOf(user.email);
arrUser.set(index, user);
allUserAdapter.notifyDataSetChanged();
}
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
};
#Override
protected void onDestroy() {
super.onDestroy();
try {
rootUrl.removeAuthStateListener(mAuthStateListener);
} catch (Exception e) {
}
try {
urlCurrenUser.removeEventListener(valueEventListenerCurrenUser);
} catch (Exception e) {
}
try {
urlAllUser.removeEventListener(childEventListenerAllUser);
} catch (Exception e) {
}
try {
rootUrl.getRoot().child(".info/connected").removeEventListener(valueEventListenerUserConnected);
}catch (Exception e){}
}
#OnClick(R.id.btnLogout)
public void btnLogout() {
if (FirebaseAuth.getInstance().getCurrentUser() != null) {
stopService(new Intent(this, LocationService.class));
AuthUI.getInstance().signOut(this);
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
finish();
}
}
public class AllUserAdapter extends ArrayAdapter<User> {
private Activity mActivity;
private ArrayList<User> mArrUser;
#BindView(R.id.tvNameUser)
TextView tvNameUser;
#BindView(R.id.tvStatus)
TextView tvStatus;
public AllUserAdapter(Activity mActivity, int resource, ArrayList<User> mArrUser) {
super(mActivity, resource, mArrUser);
this.mActivity = mActivity;
this.mArrUser = mArrUser;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater layoutInflater = mActivity.getLayoutInflater();
convertView = layoutInflater.inflate(R.layout.item_list_user, null);
}
ButterKnife.bind(this, convertView);
tvNameUser.setText(mArrUser.get(position).name);
tvStatus.setText(mArrUser.get(position).connecttion);
if (mArrUser.get(position).connecttion.equals(Constant.KEY_ONLINE)){
tvStatus.setTextColor(Color.parseColor("#00FF00"));
}else {
tvStatus.setTextColor(Color.parseColor("#FF0000"));
}
return convertView;
}
}
}
logcat