data selected in spinner is not transferred the first time - android

A video showing the problem:
video
public class ListActivity extends AppCompatActivity {
private ActivityListBinding binding;
private FirebaseAuth firebaseAuth;
private FirebaseFirestore firebaseFirestore;
PaketAdapter adapter;
ArrayList<Paket> paketArrayList;
String magaza;
String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityListBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
firebaseAuth = FirebaseAuth.getInstance();
firebaseFirestore = FirebaseFirestore.getInstance();
paketArrayList = new ArrayList<>();
binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new PaketAdapter(paketArrayList);
binding.recyclerView.setAdapter(adapter);
Intent intent = getIntent();
magaza = intent.getStringExtra("magaza");
getData();
}
public void getData(){
firebaseFirestore.collection(magaza).addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException error) {
if (error!=null){
Toast.makeText(ListActivity.this,error.getLocalizedMessage(),Toast.LENGTH_LONG).show();
}else if (value!=null){
for (DocumentSnapshot documentSnapshot:value.getDocuments()){
Map<String,Object> data = documentSnapshot.getData();
name = (String) data.get("name");
String paketSayisi = (String) data.get("paketSayisi");
String angaryaSayisi = (String) data.get("angaryaSayisi");
//FieldValue tarih = (FieldValue) data.get("tarih");
//String magaza = (String) data.get("magaza");
Paket paket = new Paket(name,paketSayisi,angaryaSayisi);
paketArrayList.add(paket);
}
}
}
}); adapter.notifyDataSetChanged();
}
public void delete(View view){
for (int i=0;i<= paketArrayList.size();i++){
firebaseFirestore.collection(magaza).document(name).delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Toast.makeText(ListActivity.this,"SİLİNDİ",Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ListActivity.this,e.getLocalizedMessage(),Toast.LENGTH_LONG).show();
}
});
}
in the application I made, the user selects the store from the spinner and in the other activity, the package information from that store appears. However, when I log in and switch to other activity, the data is not coming. When I go back and go again, the data appears. Does anyone know where I went wrong or what I should do?
public class LoginActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private ActivityLoginBinding binding;
FirebaseAuth firebaseAuth;
String magaza;
Intent intenttoList;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityLoginBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
intent = new Intent(LoginActivity.this,ListActivity.class);
Intent gelenintent = getIntent();
String email =gelenintent.getStringExtra("email");
if (email.equals("")){
}else {
binding.username.setText(email);
}
binding.spinner.setOnItemSelectedListener(this);
firebaseAuth = FirebaseAuth.getInstance();
intenttoList = new Intent(LoginActivity.this,ListActivity.class);
magaza="";
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.magazaList,R.layout.support_simple_spinner_dropdown_item);
binding.spinner.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
public void logIn(View view){
if (magaza.equals("çöp")){
Toast.makeText(LoginActivity.this,"MAĞAZA SEÇMENİZ GEREKMEKTEDİR",Toast.LENGTH_LONG).show();
}else{
String username = binding.username.getText().toString();
String password = binding.passWord.getText().toString();
firebaseAuth.signInWithEmailAndPassword(username,password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
startActivity(intent);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(LoginActivity.this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (adapterView.getItemAtPosition(i).toString().equals("MAĞAZA SEÇİN")){
Toast.makeText(LoginActivity.this,"MAĞAZA SEÇMENİZ GEREKLİDİR",Toast.LENGTH_LONG).show();
magaza ="çöp";
}else{
magaza =adapterView.getItemAtPosition(i).toString();
intent.putExtra("magaza",magaza);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}

Try this
firebaseAuth.signInWithEmailAndPassword(username,password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
Intent intent = new Intent(this, ListActivity.class)
intent.putExtra("magaza",magaza);
startActivity(intent);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(LoginActivity.this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
});
In the ListActivity.class call adapter.notifyDataSetChanged(); inside the addSnapshotListener callback.
firebaseFirestore.collection(magaza).addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException error) {
if (error!=null){
Toast.makeText(ListActivity.this,error.getLocalizedMessage(),Toast.LENGTH_LONG).show();
}else if (value!=null){
for (DocumentSnapshot documentSnapshot:value.getDocuments()){
Map<String,Object> data = documentSnapshot.getData();
name = (String) data.get("name");
String paketSayisi = (String) data.get("paketSayisi");
String angaryaSayisi = (String) data.get("angaryaSayisi");
//FieldValue tarih = (FieldValue) data.get("tarih");
//String magaza = (String) data.get("magaza");
Paket paket = new Paket(name,paketSayisi,angaryaSayisi);
paketArrayList.add(paket);
}
adapter.notifyDataSetChanged();
}
}
});

Related

How to associate each Firebase user with their own recyclerView Data

I'm creating an app that display notes list in a recyclerView. I connected the app with firebase authentication and realtime database.
The Realtime Database JSON tree looks like this:
The problem is that I want "Notes" to be part of "Users" which is not the case, because when I login to my app, I found the same Notes in every user account. I want the notes to be displayed for a specific user when they create them.
Here is my code:
SignupActivity.java
public class SignupActivity extends AppCompatActivity {
private static final String TAG = "";
private static final int RC_SIGN_IN = 9001;
EditText mName, mEmail,mPassword;
Button mSignupBtn;
FirebaseAuth mAuth;
ProgressBar progressBar;
View mViewHelper;
GoogleSignInButton button;
GoogleSignInClient mGoogleSignInClient;
FirebaseAuth.AuthStateListener mAuthListner;
FirebaseFirestore fStore;
String userID;
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListner);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
TextView textView = findViewById(R.id.textView);
textView.setText(Html.fromHtml(getString(R.string.agree_terms)));
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
mEmail = findViewById(R.id.et_email_address);
mPassword = findViewById(R.id.et_password);
mName = findViewById(R.id.et_name);
mSignupBtn = findViewById(R.id.create_btn);
progressBar = findViewById(R.id.loading_spinner);
mViewHelper = findViewById(R.id.view_helper);
button = findViewById(R.id.login_google_btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signIn();
}
});
mAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
mSignupBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
final String name = mName.getText().toString();
if(TextUtils.isEmpty(email)) {
mEmail.setError("Email is required.");
return;
}
if(TextUtils.isEmpty(name)) {
mName.setError("Name is required.");
return;
}
if(TextUtils.isEmpty(password)) {
mPassword.setError("Password is required.");
return;
}
if(password.length() < 6) {
mPassword.setError("Password Must be >= 6 Characters");
return;
}
progressBar.setVisibility(View.VISIBLE);
mViewHelper.setVisibility(View.VISIBLE);
mSignupBtn.setVisibility(View.INVISIBLE);
// register the user in firebase
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
Toast.makeText(SignupActivity.this, "User Created", Toast.LENGTH_SHORT).show();
userID = mAuth.getCurrentUser().getUid();
DocumentReference documentReference = fStore.collection("users").document(userID);
DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Users").child(userID);
Map<String, Object> user = new HashMap<>();
user.put("name", name);
user.put("email", email);
user.put("image", "default");
user.put("thumb_image", "default");
current_user_db.setValue(user);
documentReference.set(user).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "onSuccess: user Profile is created for "+ userID);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: "+ e.toString());
}
});
Intent intent = new Intent(SignupActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
else{
Toast.makeText(SignupActivity.this, "Error !" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
mViewHelper.setVisibility(View.INVISIBLE);
mSignupBtn.setVisibility(View.VISIBLE);
}
});
}
});
mAuthListner = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null) {
startActivity(new Intent(SignupActivity.this, MainActivity.class));
}
}
};
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken("886475354465-j5suema9gt5mhi2fhli0un9vsn1olvaa.apps.googleusercontent.com")
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
// ...
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
//updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(SignupActivity.this, "Aut Fail", Toast.LENGTH_SHORT).show();
//updateUI(null);
}
// ...
}
});
}
}
NotesAdapter.java
public class NotesAdapter extends RecyclerView.Adapter<NotesAdapter.MyHolder>
{
List<Listdata> noteslist;
private Context context;
public NotesAdapter(List<Listdata> noteslist,Context context)
{
this.context=context;
this.noteslist=noteslist;
}
#NonNull
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item,viewGroup,false);
MyHolder myHolder=new MyHolder(view);
return myHolder;
}
#Override
public void onBindViewHolder(#NonNull MyHolder myHolder, int position) {
Listdata data=noteslist.get(position);
myHolder.title.setText(data.getTitle());
myHolder.desc.setText(data.getDesc());
}
#Override
public int getItemCount() {
return noteslist.size();
}
class MyHolder extends RecyclerView.ViewHolder {
TextView title,desc;
public MyHolder(#NonNull View itemView) {
super(itemView);
title=itemView.findViewById(R.id.title);
desc=itemView.findViewById(R.id.desc);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Listdata listdata=noteslist.get(getAdapterPosition());
Intent i=new Intent(context, StreamActivity.class);
i.putExtra("id",listdata.id);
i.putExtra("title",listdata.title);
i.putExtra("desc",listdata.desc);
context.startActivity(i);
}
});
}
}
}
AddNotesActivity.java
public class AddNotesActivity extends AppCompatActivity {
EditText title,desc;
String titlesend,descsend;
private DatabaseReference mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_notes);
title=findViewById(R.id.title);
desc=findViewById(R.id.desc);
mDatabase = FirebaseDatabase.getInstance().getReference();
}
public void AddNotes(View view) {
titlesend=title.getText().toString();
descsend=desc.getText().toString();
if(TextUtils.isEmpty(titlesend) || TextUtils.isEmpty(descsend)){
return;
}
AddNotes(titlesend,descsend);
}
private void AddNotes(String titlesend, String descsend)
{
String id=mDatabase.push().getKey();
Listdata listdata = new Listdata(id,titlesend, descsend);
mDatabase.child("Notes").child(id).setValue(listdata).
addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(AddNotesActivity.this, "Notes Added", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),NotesActivity.class));
}
});
}
}
NotesActivity.java
public class NotesActivity extends AppCompatActivity {
// Firebase instance variables
private FirebaseAuth mFirebaseAuth;
private FirebaseUser mFirebaseUser;
//HomeScreen variables
RecyclerView recyclerView;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
List<Listdata> list =new ArrayList<>();
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes);
recyclerView=findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(NotesActivity.this);
recyclerView.setLayoutManager(layoutManager);
// Initialize Firebase Auth
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
// Notes Screen
final NotesAdapter notesAdapter=new NotesAdapter(list,this);
recyclerView.setAdapter(notesAdapter);
FloatingActionButton fab = findViewById(R.id.fab);
firebaseDatabase=FirebaseDatabase.getInstance();
databaseReference=firebaseDatabase.getReference("Notes");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1: dataSnapshot.getChildren())
{
Listdata listdata=dataSnapshot1.getValue(Listdata.class);
list.add(listdata);
}
notesAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), AddNotesActivity.class));
}
});
// end NotesScreen
}
#Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mFirebaseAuth.getCurrentUser();
if(currentUser == null){
sendToStart();
}
}
private void sendToStart() {
Intent startIntent = new Intent(NotesActivity.this, LoginActivity.class);
startActivity(startIntent);
finish();
}
Please I need help on how should I modify my code to display the notes for a specific user when they create them. documentation links will be much appreciated.
you simply need to change this line of code from AddNotesActivity.java
mDatabase.child("Notes").child(id)
to
mDatabase.child("Users").child(userID).child("Notes").child(id)
and don't forget to retrieve the data in NotesActivity.java
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(userID).child("Notes");

I need to get user image from firebase to show it on ViewHolder after user uplaoded thier image in profile activity

I have a profile activity that user upload their profile images, user uploads 2 images ( back and front) the images are showing fine in the profile activity, but I also want to show one of this image (back or front) in another activity ( ViewHolder activity ). I have tried many things but couldn't figure out as i am only testing how firebase works, I really appreciate if someone can help me here.
Here is my profile activity where user upload images to firebase.
public class ProfileActivity extends AppCompatActivity implements View.OnClickListener{
private ImageView backimage;
private CircleImageView profileimage;
TextView totalscore,correctattempts,totalattempts,user_name,java_score,python_score,php_score,android_score,phone_number;
private Uri filepath;
private final int PICK_IMAGE_REQUEST = 71;
private int id;
StorageReference storageReference;
DatabaseReference users,defaultimages,scoretbl;
String Storage_Path = "All_Image_Uploads/";
// Root Database Name for Firebase Database.
public static final String Database_Path = "All_Image_Uploads_Database";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_profile);
storageReference = FirebaseStorage.getInstance().getReference();
users = FirebaseDatabase.getInstance().getReference("Users");
defaultimages = FirebaseDatabase.getInstance().getReference("Database_Path");
java_score=findViewById(R.id.javascore);
phone_number=findViewById(R.id.user_phonenumber);
python_score=findViewById(R.id.pythonscore);
php_score=findViewById(R.id.phpscore);
android_score =findViewById(R.id.androidscore);
backimage = findViewById(R.id.header_cover_image);
profileimage=findViewById(R.id.user_profile_photo);
totalattempts=findViewById(R.id.questionsattempted);
correctattempts=findViewById(R.id.correctattempts);
totalscore=findViewById(R.id.totalscore);
user_name =findViewById(R.id.user_profile_name);
backimage.setOnClickListener(this);
profileimage.setOnClickListener(this);
user_name.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
user_name.setText(Common.currentUser.getUserName());
phone_number.setText(Common.currentUser.getEmail());
users.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
/* String score=dataSnapshot.child(Common.currentuser.getUsername()).child("totalScore").getValue().toString();
totalscore.setText(score);
String tattempts=dataSnapshot.child(Common.currentuser.getUsername()).child("questionsAttempted").getValue().toString();
totalattempts.setText(tattempts);
String cattempts=dataSnapshot.child(Common.currentuser.getUsername()).child("correctAttempts").getValue().toString();
correctattempts.setText(cattempts);
phone_number.setText(Common.currentuser.getEmail());
*/
Picasso.with(getBaseContext()).load(dataSnapshot.child(Common.currentUser.getUserName()).child("pathtobackimage").getValue().toString())
.into(backimage);
Picasso.with(getBaseContext()).load(dataSnapshot.child(Common.currentUser.getUserName()).child("pathtoprofileimage").getValue().toString())
.into(profileimage);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
/*
scoretbl.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.child("Java").exists())
java_score.setText(dataSnapshot.child("Java").child("score").getValue().toString());
if(dataSnapshot.child("Python").exists())
python_score.setText(dataSnapshot.child("Python").child("score").getValue().toString());
if(dataSnapshot.child("PHP").exists())
php_score.setText(dataSnapshot.child("PHP").child("score").getValue().toString());
if(dataSnapshot.child("Android").exists())
android_score.setText(dataSnapshot.child("Android").child("score").getValue().toString());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
*/
}
private void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST&&resultCode ==RESULT_OK
&& data !=null && data.getData()!= null){
filepath = data.getData();
if(id==R.id.header_cover_image)
Picasso.with(this).load(filepath).into(backimage);
else
Picasso.with(this).load(filepath).into(profileimage);
}
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.header_cover_image:{
id = R.id.header_cover_image;
chooseImage();
uploadImageback();
break;
}
case R.id.user_profile_photo:{
id = R.id.user_profile_photo;
chooseImage();
uploadImageprofile();
break;
}
}
}
private void uploadImageback() {
final StorageReference backref = storageReference.child("images/").
child(Common.currentUser.getUserName()+"/"+ Common.currentUser.getUserName()+"back");
if(filepath!=null){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading..");
progressDialog.show();
backref.putFile(filepath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
backref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
users.child(Common.currentUser.getUserName()).child("pathtobackimage").setValue(uri.toString());
Toast.makeText(ProfileActivity.this,"Uploaded",Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ProfileActivity.this,"Not Uploaded",Toast.LENGTH_LONG).show();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(ProfileActivity.this,"Failure",Toast.LENGTH_LONG).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Uploaded "+(int)progress+"%");
}
});
}
}
private void uploadImageprofile() {
if(filepath!=null){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading.. ");
progressDialog.show();
final StorageReference profileref = storageReference.child("images/").
child(Common.currentUser.getUserName()+"/"+ Common.currentUser.getUserName()+"profile");
profileref.putFile(filepath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
profileref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
users.child(Common.currentUser.getUserName()).child("pathtoprofileimage").setValue(uri.toString());
Toast.makeText(ProfileActivity.this,"Profile Uploaded",Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ProfileActivity.this,"Profile not Uploaded",Toast.LENGTH_LONG).show();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(ProfileActivity.this,"Failure",Toast.LENGTH_LONG).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Uploaded "+(int)progress+" %");
}
});
}
}
}
and I want to show one of these image in my ViewHolder activity as you can see the text view (name and score are showing) which is coming from a ranking Fragment activity
public class RankingViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView name_text,score_text;
private ItemClickListener itemClickListener;
public RankingViewHolder(View itemView) {
super(itemView);
name_text = (TextView) itemView.findViewById(R.id.name_text);
score_text = (TextView) itemView.findViewById(R.id.score_text);
itemView.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View view) {
itemClickListener.onClick(view,getAdapterPosition(),false);
}
}
and the Fragment activity
public class RankingFragment extends Fragment {
View myFragment;
FirebaseDatabase database;
RecyclerView rankingList;
LinearLayoutManager layoutManager;
FirebaseRecyclerAdapter<Ranking,RankingViewHolder> adapter;
DatabaseReference questionScore,rankingTable;
int sum = 0; //score is default by zero
public static RankingFragment newInstance(){
RankingFragment rankingFragment = new RankingFragment();
return rankingFragment ;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
database = FirebaseDatabase.getInstance();
questionScore = database.getReference("Question_Score");
rankingTable = database.getReference("Ranking");
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
myFragment = inflater.inflate(R.layout.fragment_ranking,container,false);
rankingList = (RecyclerView) myFragment.findViewById(R.id.ranking_list);
layoutManager = new LinearLayoutManager(getActivity());
rankingList.setHasFixedSize(true);
//Using orderByChild method , this will sort the ranking in ascending order
//reverse the data by using layout manager
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
rankingList.setLayoutManager(layoutManager);
updateScore(Common.currentUser.getUserName(), new RankingCallBack<Ranking>() {
#Override
public void callBack(Ranking ranking) {
//Ranking Score update
rankingTable.child(ranking.getUserName())
.setValue(ranking);
// showRanking();
}
});
adapter = new FirebaseRecyclerAdapter<Ranking, RankingViewHolder>(
Ranking.class,
R.layout.ranking_layout,
RankingViewHolder.class,
rankingTable.orderByChild("score")
) {
#Override
protected void populateViewHolder(RankingViewHolder viewHolder, final Ranking model, int position) {
viewHolder.name_text.setText(model.getUserName());
viewHolder.score_text.setText(String.valueOf(model.getScore()));
//prevent crash when user click
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Intent scoreDetail = new Intent(getActivity(),Score_Detail.class);
scoreDetail.putExtra("viewUser",model.getUserName());
startActivity(scoreDetail);
}
});
}
};
adapter.notifyDataSetChanged();
rankingList.setAdapter(adapter);
return myFragment;
}
private void updateScore(final String userName, final RankingCallBack<Ranking> callBack) {
questionScore.orderByChild("user").equalTo(userName)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot data:dataSnapshot.getChildren())
{
Question_Score quest = data.getValue(Question_Score.class);
sum += Integer.parseInt(quest.getScore());
}
Ranking ranking = new Ranking(userName,sum);
callBack.callBack(ranking);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
and here is my Ranking class
public class Ranking {
private String userName;
private long score;
private String urlProfilePic;
public Ranking(){
}
public Ranking(String userName, long score, String pathtobackimage ) {
this.userName = userName;
this.score = score;
this.urlProfilePic = pathtobackimage;
}
public String getUrlProfilePic() {
return urlProfilePic;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public long getScore() {
return score;
}
public void setScore(long score) {
this.score = score;
}
}
Here the screen shot to help more how I wanted
I put my comment in answer field because of this restriction: 'You must have 50 reputation to comment'.
Anyway, back to your question. One solution would be to save the current user 'key' to a SharedPreference file. In your new Activity, use that 'key' to retrieve the data from Firebase.
EDIT: Added solution
Quoted: "...and I want to show one of these image in my ViewHolder activity as you can see the text view (name and score are showing) which is coming from a ranking Fragment activity..."
Solution: Search for fixme. In RankingViewHolder class, add:
public class RankingViewHolder extends ...
//...
public TextView name_text, score_text;
public ImageView profileImageView; //fixme
//...
public RankingViewHolder(View itemView) {
//...
score_text = (TextView) itemView.findViewById(R.id.score_text);
profileImageView = (ImageView) itemView.findViewById(R.id.profile_image_view); //fixme
//...
Inside populateViewHolder()
viewHolder.score_text.setText(String.valueOf(model.getScore()));
Picasso.with(getContext()) //fixme
.load(Common.currentUser.getUrlProfilePic()) //fixme
.into(viewHolder.profileImageView); //fixme
Inside RankingFragment class, since you are already using Common.currentUser.getUserName(), might as well create another variable under it to store the url link to the user's profile picture, and retrieve the link via Common.currentUser.getUrlProfilePic().
EDIT#2:
The images stored in FB storage have this links:
gs://FIXME_FIREBASE.com/images/userName/userNameback.jpeg
gs://FIXME_FIREBASE.com/images/userName/userNameprofile.jpeg
However to use in Picasso, need this kind of links:
https://firebasestorage.googleapis.com/v0/b/FIXME/o/FIXME/images/userName/userNameback.jpeg?alt=media&token=FIXME
Question is how to get that?
One solution is that after you successfully upload the image, get the download url (example below).
The tricky part is that the download url is not immediately available, and you have to use .getMetadata(), .getDownloadUrl() to do that.
Once the url is received, you have to figure out how to save this link to the user's profile in your FB database.
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
StorageMetadata storageMetadata = taskSnapshot.getMetadata();
StorageReference reference = storageMetadata.getReference();
reference.getDownloadUrl() // Get the download URL for the file
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Log.i(TAG, uri.toString()); //fixme: save this to user's profile
}
});
}
Inside populateViewHolder, you are using Ranking model that contains the username and score.
Modify that Ranking model class to add an additional String variable urlProfilePic that contains the url to the user's image (above result), and generate the getter for it called getUrlProfilePic(). Then you can use it in this way inside the populateViewHolder:
viewHolder.score_text.setText(String.valueOf(model.getScore()));
Picasso.with(getContext())
.load(model.getUrlProfilePic()) //fixme
.into(viewHolder.profileImageView);

Can not delete item that is selected, only deletes the last item added

I'm trying to delete the selected item in my RecyclerView, but when I click on my delete Button it just deletes the last item added. And after I delete the last item added I can not delete anymore. What am I missing?
MainActivity
public class MainWishActivity extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
private RecyclerView wishList;
private androidx.appcompat.widget.Toolbar mToolbar;
private ImageButton ibaddnewwishlist;
private CircleImageView NavProfileImage;
private TextView NavProfileFirstName, NavProfileLastName;
private FirebaseAuth mAuth;
private DatabaseReference UsersRef, WishListRef;
String currentUserID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_wish);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Brukere");
WishListRef = FirebaseDatabase.getInstance().getReference().child("Ønskelister").child(currentUserID);
mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle(" Dine Ønskelister");
drawerLayout = (DrawerLayout)findViewById(R.id.drawable_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(MainWishActivity.this, drawerLayout, R.string.drawer_open, R.string.drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
ibaddnewwishlist = (ImageButton)findViewById(R.id.ib_addnewwishlist);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
navigationView = (NavigationView)findViewById(R.id.navigation_view);
wishList = (RecyclerView)findViewById(R.id.rv_wishlist);
wishList.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
wishList.setLayoutManager(linearLayoutManager);
View navView = navigationView.inflateHeaderView(R.layout.navigation_header);
NavProfileImage = (CircleImageView)navView.findViewById(R.id.civ_navprofilepicture);
NavProfileFirstName = (TextView)navView.findViewById(R.id.tv_headerfirstname);
NavProfileLastName = (TextView) navView.findViewById(R.id.tv_headerlastname);
UsersRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
if (dataSnapshot.hasChild("fornavn")){
String firstname = dataSnapshot.child("fornavn").getValue().toString();
NavProfileFirstName.setText(firstname);
}
if (dataSnapshot.hasChild("etternavn")) {
String lastname = dataSnapshot.child("etternavn").getValue().toString();
NavProfileLastName.setText(lastname);
}
if (dataSnapshot.hasChild("profilbilde")){
String image = dataSnapshot.child("profilbilde").getValue().toString();
Picasso.with(MainWishActivity.this).load(image).placeholder(R.drawable.profile).into(NavProfileImage);
}
else{
Toast.makeText(MainWishActivity.this, "Profil navn finnes ikke...", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
UserMenuSelector(item);
return false;
}
});
ibaddnewwishlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SendUserToWishListActivity();
}
});
DisplayUsersWishLists();
}
private void DisplayUsersWishLists() {
FirebaseRecyclerAdapter<WishListClass, WishListViewHolder > firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<WishListClass, WishListViewHolder>
(
WishListClass.class,
R.layout.wish_list_single_layout,
WishListViewHolder.class,
WishListRef
) {
#Override
protected void populateViewHolder(WishListViewHolder viewHolder, WishListClass model, final int position) {
final String Key = getRef(position).getKey();
viewHolder.setFornavn(model.getFornavn());
viewHolder.setDate(model.getDate());
viewHolder.setTitle(model.getTitle());
viewHolder.setProfilbilde(getApplicationContext(), model.getProfilbilde());
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent profileIntent = new Intent(MainWishActivity.this, UserWishItemActivity.class);
profileIntent.putExtra("Key", Key);
startActivity(profileIntent);
}
});
}
};
wishList.setAdapter(firebaseRecyclerAdapter);
}
public static class WishListViewHolder extends RecyclerView.ViewHolder{
View mView;
public WishListViewHolder(#NonNull View itemView) {
super(itemView);
mView = itemView;
}
public void setFornavn (String fornavn){
TextView wishlist_name = (TextView) mView.findViewById(R.id.tv_firstnamelist);
wishlist_name.setText(fornavn);
}
public void setProfilbilde (Context ctx, String profilbilde){
CircleImageView image = (CircleImageView) mView.findViewById(R.id.civ_profilepicturelist);
Picasso.with(ctx).load(profilbilde).into(image);
}
public void setDate (String date){
TextView wishlist_date = (TextView) mView.findViewById(R.id.tv_publisheddatelist);
wishlist_date.setText(" " + date);
}
public void setTitle (String title){
TextView wishlist_title = (TextView) mView.findViewById(R.id.tv_wishlisttitle);
wishlist_title.setText(title);
}
}
private void SendUserToWishListActivity(){
Intent addNewPostIntent = new Intent(MainWishActivity.this, AddWishListActivity.class);
startActivity(addNewPostIntent);
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null){
SendUserToLoginActivity();
}
else
{
CheckUserExistence();
}
}
private void CheckUserExistence(){
final String current_user_id = mAuth.getCurrentUser().getUid();
UsersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(current_user_id)){
SendUserToUserInfoAcitivity();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void SendUserToUserInfoAcitivity(){
Intent setupIntent = new Intent(MainWishActivity.this, UserInfoActivity.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(setupIntent);
finish();
}
private void SendUserToLoginActivity() {
Intent loginIntent = new Intent(MainWishActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
private void SendUserToFindFriendsActivity(){
Intent findfriendsIntent = new Intent(MainWishActivity.this, FindFriendsActivity.class);
findfriendsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(findfriendsIntent);
finish();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item))
{
return true;
}
return super.onOptionsItemSelected(item);
}
private void UserMenuSelector (MenuItem item){
switch (item.getItemId()){
case R.id.navbtn_addwishlist:
SendUserToWishListActivity();
break;
case R.id.navbtn_profile:
Toast.makeText(this, "Profil", Toast.LENGTH_SHORT).show();
break;
case R.id.navbtn_home:
Toast.makeText(this, "Hjem", Toast.LENGTH_SHORT).show();
break;
case R.id.navbtn_friends:
Toast.makeText(this, "Venner", Toast.LENGTH_SHORT).show();
break;
case R.id.navbtn_findfriends:
SendUserToFindFriendsActivity();
break;
case R.id.navbtn_settings:
Toast.makeText(this, "Instillinger", Toast.LENGTH_SHORT).show();
break;
case R.id.navbtn_logout:
mAuth.signOut();
SendUserToLoginActivity();
break;
}
}
SecondActivity
public class UserWishItemActivity extends AppCompatActivity {
private TextView tvwishlisttitle;
private EditText etwishitem;
private Button btnaddwishitem;
private RecyclerView wishListitems;
private String currentUserID, databaseUserID;
private String Key, postRandomName;
private DatabaseReference WishListUsersClickRef, UsersRef, WishItemsRef, wishListRef,WishItemsRef1;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_add_wish_item);
Key = getIntent().getExtras().get("Key").toString();
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Brukere");
WishItemsRef = FirebaseDatabase.getInstance().getReference().child("Ønsker");
wishListRef = FirebaseDatabase.getInstance().getReference().child("Ønskelister").child(currentUserID).child(Key);
tvwishlisttitle = (TextView)findViewById(R.id.tv_userwishlisttitle);
etwishitem = (EditText)findViewById(R.id.et_wishitem);
btnaddwishitem = (Button)findViewById(R.id.btn_addwishitem);
btnaddwishitem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CreateWishlist();
}
});
wishListitems = (RecyclerView)findViewById(R.id.rv_wishlistitems);
wishListitems.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
wishListitems.setLayoutManager(linearLayoutManager);
WishListUsersClickRef = FirebaseDatabase.getInstance().getReference("Ønskelister").child(currentUserID).child(Key);
WishListUsersClickRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
String title = dataSnapshot.child("title").getValue().toString();
databaseUserID = dataSnapshot.child("uid").getValue().toString();
tvwishlisttitle.setText(title);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
DisplayWishListItems();
}
private void DisplayWishListItems() {
FirebaseRecyclerAdapter<WishItemClass, WishListItemsViewHolder > firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<WishItemClass, WishListItemsViewHolder>
(
WishItemClass.class,
R.layout.wish_list_item_layout,
WishListItemsViewHolder.class,
WishItemsRef.child(Key)
) {
#Override
protected void populateViewHolder(final WishListItemsViewHolder viewHolder, final WishItemClass model, final int position) {
viewHolder.setWishitemname(model.getWishitemname());
viewHolder.m1View.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(UserWishItemActivity.this);
LayoutInflater inflater = getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.endreslettjobb_dialog, null);
dialogBuilder.setView(dialogView);
dialogBuilder.setTitle(model.getWishitemname());
final AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
final Button btndelete = (Button)dialogView.findViewById(R.id.btn_delete);
btndelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
WishItemsRef.removeValue();
}
});
return false;
}
});
}
};
wishListitems.setAdapter(firebaseRecyclerAdapter);
}
public static class WishListItemsViewHolder extends RecyclerView.ViewHolder{
View m1View;
public WishListItemsViewHolder(#NonNull View itemView) {
super(itemView);
m1View = itemView;
}
public void setWishitemname (String wishitemname){
TextView wishitem_name = (TextView) m1View.findViewById(R.id.tv_wishitemname);
wishitem_name.setText(wishitemname);
}
public void setUid (String uid){
}
}
private void CreateWishlist() {
postRandomName = String.valueOf(new Date().getTime());
final String wishlist = etwishitem.getText().toString().trim();
etwishitem.setText("");
wishListRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
HashMap postMap = new HashMap();
postMap.put("uid", currentUserID);
postMap.put("wishitemname", wishlist);
WishItemsRef.child(Key).child(postRandomName).updateChildren(postMap)
.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
AddItemActivity
private Spinner spwishlisttitle;
private Button btnsavewishlist;
private DatabaseReference UsersRef, wishListRef;
private FirebaseAuth mAuth;
private String saveCurrentDate, currentUserID, postRandomName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_wish_list);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Brukere");
wishListRef = FirebaseDatabase.getInstance().getReference().child("Ønskelister");
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
spwishlisttitle = (Spinner) findViewById(R.id.sp_wishlisttitle);
btnsavewishlist = (Button) findViewById(R.id.btn_savewishlist);
btnsavewishlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CreateWishlist();
}
});
}
private void CreateWishlist() {
Calendar calFordDate = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
saveCurrentDate = currentDate.format(calFordDate.getTime());
postRandomName = String.valueOf(new Date().getTime());
final String wishlist = spwishlisttitle.getSelectedItem().toString().trim();
UsersRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String userFirstname = dataSnapshot.child("fornavn").getValue().toString();
String userProfileImage = dataSnapshot.child("profilbilde").getValue().toString();
HashMap postMap = new HashMap();
postMap.put("uid", currentUserID);
postMap.put("date", saveCurrentDate);
postMap.put("title", wishlist);
postMap.put("profilbilde", userProfileImage);
postMap.put("fornavn", userFirstname);
wishListRef.child(currentUserID).child(currentUserID + postRandomName).updateChildren(postMap)
.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
SendUserToMainActivity();
Toast.makeText(AddWishListActivity.this, "Ønskeliste opprettet", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(AddWishListActivity.this, "Error ocurred", Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(AddWishListActivity.this, MainWishActivity.class);
startActivity(mainIntent);
}
}
I have edited my question with my code.
Hope this is helpful.

Recyclerview keeps re-populating data from Firebase DB when new child is created

I am currently working on a chat application and have come across an issue. My Chat Fragment contains my Recyclerview which populates data from Firebase DB. I am able to obtain the data, but I am running into an issue. When I open my Chat Activity and send a message, a new push id is created with the information stored in the child. The data obtained by my recyclerview is it gets the last push id and retrieves the last message that was sent. The problem is, when I go back into my fragment, the recyclerview re-populates and adds the new push id last message that was created, and creates another item instead of just refreshing the original item.
So essentially, I will load my app, go into the Chat Fragment, my recyclerview will display the other user and the last message that was sent, no problem, then I will click on that item, open the chat activity, send a message then go back. Now when I am back into the chat fragment I will have two or three or however many messages that were sent displaying in the recyclerview. Not sure on how to fix this, my code is below:
DATABASE STRUCTURE
Chat Fragment
public class Fragment_MatchChats extends Fragment {
private RecyclerView mRecyclerView, mRecyclerViewChat;
private RecyclerView.Adapter mMatchesAdapter, mChatAdapter;
private String currentUserID;
private DatabaseReference mDatabaseChat;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.frag_match_chat, container, false);
currentUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();
mDatabaseChat = FirebaseDatabase.getInstance().getReference().child("Chat");
LinearLayoutManager layoutManagerChat = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
mRecyclerViewChat = (RecyclerView) v.findViewById(R.id.recyclerViewChat);
mRecyclerViewChat.setHasFixedSize(true);
mRecyclerViewChat.setLayoutManager(layoutManagerChat);
mChatAdapter = new RecyclerViewChatAdapter(getDataSetChat(), getContext());
getUserMatchId();
return v;
}
//this method will get the user ID in the database that you matched with. It will run through the matches child and get all the user IDs
private void getUserMatchId() {
DatabaseReference matchDB = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID).child("swipes").child("matches");
matchDB.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
for(DataSnapshot match : dataSnapshot.getChildren()){
CheckChatID(match.getKey());
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void CheckChatID(final String chat) {
DatabaseReference ChatDB = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID).child("swipes").child("matches")
.child(chat).child("ChatID");
ChatDB.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
String ChatID = dataSnapshot.getValue().toString();
ChatIDExist(ChatID, chat);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void ChatIDExist(final String chatID, final String oppUserID) {
final DatabaseReference ChatDB = mDatabaseChat.child(chatID);
final Query lastQuery = ChatDB.orderByKey().limitToLast(1);
ChatDB.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
lastQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot child: dataSnapshot.getChildren()){
String key = child.child("text").getValue().toString();
FetchChatInfo(oppUserID,key);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void FetchChatInfo(String key, final String chatID) {
DatabaseReference userDB = FirebaseDatabase.getInstance().getReference().child("Users").child(key);
userDB.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
String matched_userID = dataSnapshot.getKey();
String matches_userName = "";
String matches_userProPic = "";
String match_CHATID = chatID;
if(dataSnapshot.child("name").getValue() != null){
matches_userName = dataSnapshot.child("name").getValue().toString();
}
if(dataSnapshot.child("profilePicURL").getValue() != null){
matches_userProPic = dataSnapshot.child("profilePicURL").getValue().toString();
}
RecyclerViewChatReference chat_obj = new RecyclerViewChatReference(matched_userID, matches_userName, matches_userProPic, match_CHATID);
resultsChats.add(chat_obj);
mRecyclerViewChat.setAdapter(mChatAdapter);
mChatAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private ArrayList<RecyclerViewChatReference> resultsChats = new ArrayList<RecyclerViewChatReference>();
private List<RecyclerViewChatReference> getDataSetChat() {
return resultsChats;
}
Chat Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
matchId = getIntent().getExtras().getString("matchID");
currentUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();
mDatabaseUser = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID)
.child("swipes").child("matches").child(matchId).child("ChatID");
mDatabaseChat = FirebaseDatabase.getInstance().getReference().child("Chat");
getChatId();
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setNestedScrollingEnabled(false);
mRecyclerView.setHasFixedSize(false);
mChatLayoutManager = new LinearLayoutManager(ChatActivity.this);
mRecyclerView.setLayoutManager(mChatLayoutManager);
mChatAdapter = new ChatAdapter(getDataSetChat(), ChatActivity.this);
mRecyclerView.setAdapter(mChatAdapter);
mSendEditText = findViewById(R.id.message);
mSendButton = findViewById(R.id.send);
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendMessage();
}
});
}
private void sendMessage() {
String sendMessageText = mSendEditText.getText().toString();
if(!sendMessageText.isEmpty()){
DatabaseReference newMessageDb = mDatabaseChat.push();
Map newMessage = new HashMap();
newMessage.put("createdByUser", currentUserID);
newMessage.put("text", sendMessageText);
newMessageDb.setValue(newMessage);
}
mSendEditText.setText(null);
}
private void getChatId(){
mDatabaseUser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
chatId = dataSnapshot.getValue().toString();
mDatabaseChat = mDatabaseChat.child(chatId);
getChatMessages();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void getChatMessages() {
mDatabaseChat.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if(dataSnapshot.exists()){
String message = "";
String createdByUser = "";
if(dataSnapshot.child("text").getValue()!=null){
message = dataSnapshot.child("text").getValue().toString();
}
if(dataSnapshot.child("createdByUser").getValue()!=null){
createdByUser = dataSnapshot.child("createdByUser").getValue().toString();
}
if(message!=null && createdByUser!=null){
Boolean currentUserBoolean = false;
if(createdByUser.equals(currentUserID)){
currentUserBoolean = true;
}
ChatObject newMessage = new ChatObject(message, currentUserBoolean);
resultsChat.add(newMessage);
mChatAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private ArrayList<ChatObject> resultsChat = new ArrayList<ChatObject>();
private List<ChatObject> getDataSetChat() {
return resultsChat;
}
}

The items not appear in recyclerview

I face a problem when I send a comment, that comment does not appear in RecyclerView, I have to go back and reopen Activity again to see my reply.
BlogSingleActivity.java
public class BlogSingleActivity extends AppCompatActivity {
private String mPost_key = null;
DatabaseReference mDatabase;
private ImageView mBlogSingleImage;
private TextView mBlogSingleTitle;
private TextView mBlogSingleDesc;
private TextView mBlogSingleUsername, mNumbersOfComments;
private TextView mBlogSingleDate;
private DatabaseReference ReplayDatabase;
private RecyclerView mReplayBlogList;
private TextView emptyView;
FirebaseRecyclerAdapter<Blog, BlogViewHolder> mAdapter;
private EditText mReplayText;
private FirebaseAuth mAuth;
private FirebaseUser mCurrentUser;
private DatabaseReference mDatabaseUser;
private Uri mImagUri = null;
private static final int GALLERY_REQUEST = 2;
private StorageReference mStorage;
private ImageButton mselectImage;
Button sendBTN;
private ProgressDialog mProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blog_single);
mPost_key = getIntent().getExtras().getString("blog_id");
mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
ReplayDatabase = FirebaseDatabase.getInstance().getReference().child("Replay");
mBlogSingleDesc = findViewById(R.id.singleBlogDesc);
mBlogSingleTitle = findViewById(R.id.post_Tittle);
mBlogSingleImage = findViewById(R.id.singleBlogImage);
mBlogSingleUsername = findViewById(R.id.singleBlogUsername);
mBlogSingleDate = findViewById(R.id.singleBlogDate);
mNumbersOfComments = findViewById(R.id.numberofcomments);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mReplayBlogList = findViewById(R.id.replay_blog_list);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
mReplayBlogList.setLayoutManager(layoutManager);
mReplayBlogList.setNestedScrollingEnabled(false);
emptyView = findViewById(R.id.empty_view);
chickitem();
mAuth = FirebaseAuth.getInstance();
mCurrentUser = mAuth.getCurrentUser();
mDatabaseUser = FirebaseDatabase.getInstance().getReference().child("Users").child(mCurrentUser.getUid());
mReplayText = findViewById(R.id.ReplayField);
mStorage = FirebaseStorage.getInstance().getReference();
mselectImage = findViewById(R.id.replayImageSelect);
sendBTN = findViewById(R.id.send_BTN);
getfirebaseData();
mProgress = new ProgressDialog(this);
mselectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GALLERY_REQUEST);
}
});
sendBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startReplay();
getfirebaseData();;
disappearKeyboard();
mReplayText.getText().clear();
mselectImage.setImageResource(R.mipmap.add_btn);
mselectImage.setBackgroundColor(getResources().getColor(R.color.image_background_color));
}
});
mDatabase.child(mPost_key).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String post_title = (String) dataSnapshot.child("tittle").getValue();
String post_desc = (String) dataSnapshot.child("desc").getValue();
String post_image = (String) dataSnapshot.child("image").getValue();
String post_username = (String) dataSnapshot.child("username").getValue();
Object post_date = dataSnapshot.child("date").getValue();
Blog timeStamp = new Blog();
timeStamp.setDate(post_date);
if (timeStamp.getDate() != null) {
String datee = timeStamp.getDate().toString();
long time = Long.parseLong(datee);
String timeAgo = TimeAgo.getTimeAgo(time);
mBlogSingleDate.setText(timeAgo);
}
mBlogSingleTitle.setText(post_title);
mBlogSingleDesc.setText(post_desc);
mBlogSingleUsername.setText(post_username);
Picasso.with(BlogSingleActivity.this)
.load(post_image)
.into(mBlogSingleImage);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void disappearKeyboard() {
InputMethodManager inputManager =
(InputMethodManager) this.
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(
this.getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
private void startReplay() {
{
final String replay_val = mReplayText.getText().toString().trim();
//send date to firebase database
if (!TextUtils.isEmpty(replay_val) && mImagUri != null) {
mProgress.setMessage("جاري الإرسال....");
mProgress.show();
StorageReference filepath = mStorage.child("Replay_Images").child(mImagUri.getLastPathSegment());
filepath.putFile(mImagUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
if (mAuth.getCurrentUser() != null) {
#SuppressWarnings("VisibleForTests") final Uri downloadUrl = taskSnapshot.getDownloadUrl();
final DatabaseReference newPost = ReplayDatabase.child(mPost_key).push();
mDatabaseUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
newPost.child("replayimage").setValue(downloadUrl.toString());
newPost.child("replay").setValue(replay_val);
newPost.child("replaydate").setValue(ServerValue.TIMESTAMP);
newPost.child("uid").setValue(mCurrentUser.getUid());
newPost.child("replayname").setValue(dataSnapshot.child("name").getValue()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
chickitem();
mAdapter.notifyDataSetChanged();
}
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mProgress.dismiss();
}
}
});
} else if ((!TextUtils.isEmpty(replay_val))) {
mProgress.setMessage("جاري الإرسال....");
mProgress.show();
if (mAuth.getCurrentUser() != null) {
final DatabaseReference newPost = ReplayDatabase.child(mPost_key).push();
mDatabaseUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
newPost.child("replay").setValue(replay_val);
newPost.child("replaydate").setValue(ServerValue.TIMESTAMP);
newPost.child("uid").setValue(mCurrentUser.getUid());
newPost.child("replayname").setValue(dataSnapshot.child("name").getValue()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
chickitem();
mAdapter.notifyDataSetChanged();
}
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mProgress.dismiss();
}
}
}
}
private void getfirebaseData() {
mAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(
Blog.class,
R.layout.replay_row,
BlogViewHolder.class,
ReplayDatabase.child(mPost_key)
) {
#Override
protected void populateViewHolder(final BlogViewHolder viewHolder, final Blog model, int position) {
viewHolder.setReplay(model.getReplay());
viewHolder.setReplayname(model.getReplayname());
viewHolder.setReplaydate(model.getReplaydate());
viewHolder.setReplayimage(getApplicationContext(), model.getReplayimage());
}
};
mReplayBlogList.setAdapter(mAdapter);
}
public static class BlogViewHolder extends RecyclerView.ViewHolder {
View mView;
ImageView replay_imagee;
TextView recive_replay, post_replayname, post_replaydate;
public BlogViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setReplay(String replay) {
recive_replay = mView.findViewById(R.id.replay_text);
recive_replay.setText(replay);
}
public void setReplayname(String replayname) {
post_replayname = mView.findViewById(R.id.replayer_name_field);
post_replayname.setText(replayname);
}
public void setReplaydate(Object relaydate) {
post_replaydate = mView.findViewById(R.id.post_replaydate);
Blog timeStamps = new Blog();
timeStamps.setDate(relaydate);
if (timeStamps.getDate()!=null){
String dateee = timeStamps.getDate().toString();
long times = Long.parseLong(dateee);
String timeAgoo = TimeAgo.getTimeAgo(times);
post_replaydate.setText(timeAgoo);
}
}
public void setReplayimage(final Context ctx, final String replayimage) {
replay_imagee = mView.findViewById(R.id.replay_image);
Picasso.with(ctx).load(replayimage).networkPolicy(NetworkPolicy.OFFLINE).into(replay_imagee, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(ctx).load(replayimage).into(replay_imagee);
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK) {
Uri imageUri = data.getData();
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
mImagUri = result.getUri();
mselectImage.setImageURI(mImagUri);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
private void chickitem() {
final AtomicInteger count = new AtomicInteger();
ReplayDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long numChildren = dataSnapshot.child(mPost_key).getChildrenCount();
if (numChildren == 0) {
emptyView.setVisibility(View.VISIBLE);
emptyView.setText("لا توجد تعليقات");
mReplayBlogList.setVisibility(View.INVISIBLE);
mNumbersOfComments.setText("لا توجد تعليقات");
} else {
mNumbersOfComments.setText("" + numChildren);
emptyView.setVisibility(View.VISIBLE);
emptyView.setText("التعليقات...");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onStart(){
super.onStart();
getfirebaseData();
}
#Override
public void onResume(){
super.onResume();
getfirebaseData();
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
The screen looks like .
There are two comments. To see these comment I have to go back and reopen this Activity.
I'm not 100% sure about this, but I think you're missing the mReplayBlogList.notifyDataSetChanged(); after the line mReplayBlogList.setAdapter(mAdapter); in getfirebaseData().
Maybe you could give it a try. Let me know if it solved :)

Categories

Resources