Android app crashes while scrolling down - android

I am developing a blogging app for android and I am using firebase for the backend. The app is working fine but the when I scroll down to the last post, the app crashes. I have working on finding the solution from a quite a long but couldn't possibly find any.
Here is the activity which is facing the problem
public class UserActivity extends AppCompatActivity {
private RecyclerView mStatusView;
private DatabaseReference mDatabase;
private DatabaseReference mDatabaseUsers;
private DatabaseReference mDatabaseLike;
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
String userID = "";
private Boolean exit = false;
private Boolean mProcessLike = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
mFirebaseAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() == null) {
Intent loginIntent = new Intent(UserActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginIntent);
}
}
};
mDatabase = FirebaseDatabase.getInstance().getReference().child("Status");
mDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("Users");
mDatabaseLike = FirebaseDatabase.getInstance().getReference().child("Likes");
mDatabaseUsers.keepSynced(true);
mDatabaseLike.keepSynced(true);
mDatabase.keepSynced(true);
mStatusView = findViewById(R.id.status_list);
mStatusView.setHasFixedSize(true);
mStatusView.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart() {
super.onStart();
checkUserExists();
mFirebaseAuth.addAuthStateListener(mAuthListener);
// Creating a Firebase recycle Adapter
FirebaseRecyclerAdapter<Status, StatusViewHolder> firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<Status, StatusViewHolder>(
Status.class,
R.layout.status_row,
StatusViewHolder.class,
mDatabase
) {
#Override
protected void populateViewHolder(StatusViewHolder viewHolder, Status model, int position) {
final String postKey = getRef(position).getKey();
viewHolder.setTitle(model.getTitle());
viewHolder.setDescription((model.getDescription()));
viewHolder.setImage(getApplicationContext(), model.getImage());
viewHolder.mNumberOfLikesTextView.setVisibility(View.GONE);
viewHolder.setLikeButton(postKey);
viewHolder.mLikeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mProcessLike = true;
mDatabaseLike.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessLike) {
if (dataSnapshot.child(postKey).hasChild(mFirebaseAuth.getCurrentUser().getUid())) {
mDatabaseLike.child(postKey).child(mFirebaseAuth.getCurrentUser().getUid()).removeValue();
mProcessLike = false;
Toast.makeText(UserActivity.this, "Like removed", Toast.LENGTH_SHORT).show();
} else {
mDatabaseLike.child(postKey).child(mFirebaseAuth.getCurrentUser().getUid()).setValue("RandomValue");
mProcessLike = false;
Toast.makeText(UserActivity.this, "Liked", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
};
mStatusView.setAdapter(firebaseRecyclerAdapter);
}
private void checkUserExists() {
try {
userID = mFirebaseAuth.getCurrentUser().getUid();
} catch (NullPointerException e) {
e.printStackTrace();
}
mDatabaseUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(userID)) {
Intent registerIntent = new Intent(UserActivity.this,
RegisterActivity.class);
registerIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(registerIntent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
// Setting up Recycler View
public static class StatusViewHolder extends RecyclerView.ViewHolder {
View mView;
ImageButton mLikeButton;
TextView mNumberOfLikesTextView;
DatabaseReference mDataBaseLike;
FirebaseAuth mAuth;
public StatusViewHolder(View itemView) {
super(itemView);
mView = itemView;
mLikeButton = itemView.findViewById(R.id.like_button);
mNumberOfLikesTextView = itemView.findViewById(R.id.number_of_likes_text_view);
mDataBaseLike = FirebaseDatabase.getInstance().getReference().child("Likes");
mAuth = FirebaseAuth.getInstance();
mDataBaseLike.keepSynced(true);
}
public void setLikeButton(final String postKey) {
mDataBaseLike.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(postKey).hasChild(mAuth.getCurrentUser().getUid())) {
mLikeButton.setImageResource(R.drawable.ic_thumb_up_blue_24dp);
} else {
mLikeButton.setImageResource(R.drawable.ic_thumb_up_black_24dp);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
// Setting the title
public void setTitle(String title) {
TextView statusTitle = mView.findViewById(R.id.status_title_textView);
statusTitle.setText(title);
}
public void setDescription(String desc) {
TextView statusDescription = mView.findViewById(R.id.status_description_textView);
statusDescription.setText(desc);
}
public void setImage(Context context, String image) {
ImageView statusImage = mView.findViewById(R.id.status_image);
Picasso.with(context).load(image).into(statusImage);
}
}
}
And here is the log for the problem I'm getting
FATAL EXCEPTION: main
Process: com.example.akash.iametderick, PID: 12384
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.Long to type com.example.akash.iametderick.Status
at com.google.android.gms.internal.zzdzr.zzb(Unknown Source:842)
at com.google.android.gms.internal.zzdzr.zza(Unknown Source:0)
at com.google.firebase.database.DataSnapshot.getValue(Unknown Source:10)
at com.firebase.ui.database.ClassSnapshotParser.parseSnapshot(ClassSnapshotParser.java:22)
at com.firebase.ui.database.ObservableSnapshotArray.getObject(ObservableSnapshotArray.java:160)
at com.firebase.ui.database.CachingObservableSnapshotArray.getObject(CachingObservableSnapshotArray.java:40)
at com.firebase.ui.database.FirebaseRecyclerAdapter.getItem(FirebaseRecyclerAdapter.java:180)
at com.firebase.ui.database.FirebaseRecyclerAdapter.onBindViewHolder(FirebaseRecyclerAdapter.java:217)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6482)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6515)
at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5458)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5724)
at android.support.v7.widget.GapWorker.prefetchPositionWithDeadline(GapWorker.java:285)
at android.support.v7.widget.GapWorker.flushTaskWithDeadline(GapWorker.java:342)
at android.support.v7.widget.GapWorker.flushTasksWithDeadline(GapWorker.java:358)
at android.support.v7.widget.GapWorker.prefetch(GapWorker.java:365)
at android.support.v7.widget.GapWorker.run(GapWorker.java:396)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
I've been trying to solve the problem from quite a long but couldn't find any solution.
This is my status node:
Status {
-L10rFvy6N-t7RiF7FJ6 {
date: ...;
description: ...;
image: ...;
title: ...''
}
date: ...;
description: ...;
image: ...;
title: ...''
}

The issue is with your data saved on firebase.
Your Node Status is a Object and you may have saved its value as long for that particular node in your database.
So check you database and compare it with other node . Specially the node which is having the problem will be in last as you said when I scroll down to the last pos so check your last node

Related

Does anyone know how to apply "isAdded" in API level 29 or plus?

I am trying to fix a bug in an app I am developing with the help of some tutorials, and in these videos people share my error and they found the answer using "isAdded()", but the problem for me is that I am using API level 29, and in the official website says that this was deprecated in level 28. I dont want to change my project target to API level 28 because that could make it crash, so anyone know how I could solve this?
It should look this way, isAdded is highlighted in red.
public class MessageActivity extends AppCompatActivity {
CircleImageView profile_image;
TextView username;
FirebaseUser fuser;
DatabaseReference reference;
ImageButton button_send;
EditText text_sent;
MessageAdapter messageAdapter;
List<Chat> mchat;
RecyclerView recyclerView;
Intent intent;
ValueEventListener seenListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MessageActivity.this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
//finish();
}
});
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
profile_image = findViewById(R.id.profile_image);
username = findViewById(R.id.username);
button_send = findViewById(R.id.button_send);
text_sent = findViewById(R.id.text_sent);
intent = getIntent();
final String userid = intent.getStringExtra("userid");
fuser = FirebaseAuth.getInstance().getCurrentUser();
button_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String msg = text_sent.getText().toString();
if (!msg.equals("")) {
sendMessage(fuser.getUid(), userid, msg);
}
else {
Toast.makeText(MessageActivity.this, "You can´t send empty messages", Toast.LENGTH_SHORT).show();
}
text_sent.setText("");
}
});
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (isAdded()) { //HERE
User user = dataSnapshot.getValue(User.class);
username.setText(user.getUsername());
if (user.getImageURL().equals("default")) {
profile_image.setImageResource(R.mipmap.ic_launcher);
}
else {
Glide.with(getApplicationContext()).load(user.getImageURL()).into(profile_image);
}
readMessages(fuser.getUid(), userid, user.getImageURL());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
seenMessage(userid);
}
private void seenMessage(final String userid) {
reference = FirebaseDatabase.getInstance().getReference("Chats");
seenListener = reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Chat chat = snapshot.getValue(Chat.class);
if (chat.getReceiver().equals(fuser.getUid()) && chat.getSender().equals(userid)) {
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("isseen", true);
snapshot.getRef().updateChildren(hashMap);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void sendMessage(String sender, String receiver, String message){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
final String userid = intent.getStringExtra("userid");
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("sender", sender);
hashMap.put("receiver", receiver);
hashMap.put("message", message);
hashMap.put("isseen", false);
reference.child("Chats").push().setValue(hashMap);
final DatabaseReference chatRef = FirebaseDatabase.getInstance().getReference("Chatlist")
.child(fuser.getUid())
.child(userid);
chatRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
chatRef.child("id").setValue(userid);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void readMessages(final String myid, final String userid, final String imageurl) {
mchat = new ArrayList<>();
reference = FirebaseDatabase.getInstance().getReference("Chats");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mchat.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Chat chat = snapshot.getValue(Chat.class);
if (chat.getReceiver().equals(myid) && chat.getSender().equals(userid) ||
chat.getReceiver().equals(userid) && chat.getSender().equals(myid)) {
mchat.add(chat);
}
messageAdapter = new MessageAdapter(MessageActivity.this, mchat, imageurl);
recyclerView.setAdapter(messageAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void status(String status) {
reference = FirebaseDatabase.getInstance().getReference("Users").child(fuser.getUid());
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("status", status);
reference.updateChildren(hashMap);
}
#Override
protected void onResume() {
super.onResume();
status("online");
}
#Override
protected void onPause() {
super.onPause();
reference.removeEventListener(seenListener);
status("offline");
}
}
Edit: You can remove isAdded() condition because you're using an Activity and not a Fragment.
Original answer:
android.app.Fragment class was deprecated in API 28.
Instead use this androidx.fragment.app.Fragment class from AndroidX.
Declare this dependency in your build.gradle file and use androidx.fragment.app.Fragment import in your fragment class instead of android.app.Fragment

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.

How do I store a data into the firebase database without updating it? and also retrieving the data

I am currently working on a project that might be useful in a store for the ordering of foods. The device can already store some data and retrieve but there are problems that I have been dealing with.
Problem 1#: First off is that every time I store a data it usually looks like this:
For some reason I tried to use child "02" because it displays in the recycler view if I do something like "Ordering" as a child it does not seem to be showing in the display. How do I add more data to it like example in the child 02 I can still add like milkshakes or candy bars? This is the code I have done for storing.
public class Detailsoforder extends AppCompatActivity {
private static final String TAG = "AddToDatabase";
private TextView titles;
private TextView increase;
private int count = 0;
//add Firebase
private FirebaseDatabase mFirebaseDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference myRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailsoforder);
titles = findViewById(R.id.Order);
increase = findViewById(R.id.Increase);
String title = getIntent().getStringExtra("title");
titles.setText(title);
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
}
};
// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Object value = dataSnapshot.getValue();
Log.d(TAG,"Value is"+value);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void onIncreaseClick(View view) {
count++;
increase.setText(String.valueOf(count));
}
public void onOrderNow(View view) {
String value = increase.getText().toString();
if (value.equals("1")) {
Toast.makeText(Detailsoforder.this,"The order must be above 1", Toast.LENGTH_LONG).show();
}
else {
Log.d(TAG, "onClick: Attempting to add object to database.");
String newFood = titles.getText().toString();
if (!newFood.equals("")) {
FirebaseUser user = mAuth.getCurrentUser();
String userID = user.getUid();
myRef.child(userID).child("02").child("food").setValue(newFood);
myRef.child(userID).child("02").child("order").setValue(value);
Toast.makeText(Detailsoforder.this,"Adding " + newFood + " to database...", Toast.LENGTH_LONG).show();
//reset the text
titles.setText("");
Intent intent = new Intent(Detailsoforder.this, Placeorder.class);
startActivity(intent);
}
}
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
How do I store many data and not needing for updating it?
Problem 2#: Retrieving of the data. The problem is that I can only seem to get only 1 data. I wanted to fix the store part first so that I could check if I could get the many information. This is my code for retrieving of the data.
public class Vieworders extends AppCompatActivity {
private RecyclerView mRecyclerView1;
private ViewHolder1 mAdapter1;
private DatabaseReference mDatabaseReference1;
private List<Model1> mModel1;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vieworders);
mRecyclerView1= findViewById(R.id.recyclerview1);
mRecyclerView1.setHasFixedSize(true);
mRecyclerView1.setLayoutManager(new LinearLayoutManager(this));
mModel1 = new ArrayList<>();
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
String userID = user.getUid();
mAdapter1=new ViewHolder1(Vieworders.this, mModel1);
mRecyclerView1.setAdapter(mAdapter1);
mDatabaseReference1= FirebaseDatabase.getInstance().getReference(userID);
mDatabaseReference1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot:dataSnapshot.getChildren())
{
Model1 model1=postSnapshot.getValue(Model1.class);
mModel1.add(model1);
}
mAdapter1.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(Vieworders.this, databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
Can someone help me, please? I really need this to be done.
I think you are able to send data to fire and able to store these datas.
Now ,this is my snipshots of fetching data from Firebase .You can take help from this code.
private RecyclerView recyclerView;
private List<RoomRentData> firebaselist;
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
private DualProgressView progressView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_rent_activity);
firebaselist=new ArrayList<>();
recyclerView=findViewById(R.id.rent_item);
progressView=findViewById(R.id.progressbar);
progressView.setVisibility(View.VISIBLE);
recyclerView.setLayoutManager(new GridLayoutManager(getApplicationContext(),1));
recyclerView.setItemAnimator( new DefaultItemAnimator());
recyclerView.hasFixedSize();
final Calendar today = Calendar.getInstance();
String year=Integer.toString(today.get(Calendar.YEAR));
mFirebaseInstance = FirebaseDatabase.getInstance();
mFirebaseDatabase = mFirebaseInstance.getReference("room_rent").child(year);
mFirebaseDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
progressView.setVisibility(View.GONE);
System.out.println("1");
RoomRentData user = dataSnapshot.getValue(RoomRentData.class);
if (user == null) {
System.out.println("2");
Toast.makeText(ShowRentActivity.this,"No data found",Toast.LENGTH_LONG).show();
return;
}else {
for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){
System.out.println("datasnapshot 1"+dataSnapshot1);
System.out.println("3");
RoomRentData userdetails = dataSnapshot1.getValue(RoomRentData.class);
System.out.println("userdetails 1"+userdetails);
RoomRentData listdata = new RoomRentData();
String month=userdetails.getMonth();
String year=userdetails.getYear();
String cuRead=userdetails.getCurrentRead();
String prevRead=userdetails.getPrevUnit();
String totalRent=userdetails.getTotalRoomRent();
String perPersonCost=userdetails.getPerpersonCost();
String totalPeron=userdetails.getTotalPerson();
String paidOn=userdetails.getCurrentTimeAndDate();
String description=userdetails.getDescription();
System.out.println("description 1"+description);
System.out.println("month"+month);
listdata.setMonth(month);
listdata.setYear(year);
listdata.setCurrentRead(cuRead);
listdata.setPrevUnit(prevRead);
listdata.setTotalRoomRent(totalRent);
listdata.setPerpersonCost(perPersonCost);
listdata.setTotalPerson(totalPeron);
listdata.setCurrentTimeAndDate(paidOn);
listdata.setDescription(description);
firebaselist.add(listdata);
}
rentAdapter firebaseListAdapter=new rentAdapter(getApplicationContext(),firebaselist);
recyclerView.setAdapter(firebaseListAdapter);
}
}
#Override
public void onCancelled(DatabaseError error) {
progressView.setVisibility(View.GONE);
System.out.println(error);
System.out.println("error");
}
});
}
}
I have create a Model Class named RoomRentData.class.I have added this data to the RecyclerView using this model.
And This is my Model Class Code.
public class RoomRentData {
private String month;
private String year;
private String roomRent;
private String perUnitCost;
private String PrevUnit;
private String CurrentRead;
private String totalUnitCostt;
private String totalRoomRent;
private String totalPerson;
private String perpersonCost;
private String description;
private String currentTimeAndDate;
public String getCurrentRead() {
return CurrentRead;
}
public String getCurrentTimeAndDate() {
return currentTimeAndDate;
}
public String getDescription() {
return description;
}
public String getMonth() {
return month;
}
public String getPerpersonCost() {
return perpersonCost;
}
public String getPerUnitCost() {
return perUnitCost;
}
public String getPrevUnit() {
return PrevUnit;
}
public String getRoomRent() {
return roomRent;
}
public String getTotalPerson() {
return totalPerson;
}
public String getTotalRoomRent() {
return totalRoomRent;
}
public String getTotalUnitCostt() {
return totalUnitCostt;
}
public String getYear() {
return year;
}
public void setCurrentRead(String currentRead) {
CurrentRead = currentRead;
}
public void setCurrentTimeAndDate(String currentTimeAndDate) {
this.currentTimeAndDate = currentTimeAndDate;
}
public void setDescription(String description) {
this.description = description;
}
public void setMonth(String month) {
this.month = month;
}
public void setPerpersonCost(String perpersonCost) {
this.perpersonCost = perpersonCost;
}
public void setPerUnitCost(String perUnitCost) {
this.perUnitCost = perUnitCost;
}
public void setPrevUnit(String prevUnit) {
PrevUnit = prevUnit;
}
public void setRoomRent(String roomRent) {
this.roomRent = roomRent;
}
public void setTotalPerson(String totalPerson) {
this.totalPerson = totalPerson;
}
public void setTotalRoomRent(String totalRoomRent) {
this.totalRoomRent = totalRoomRent;
}
public void setTotalUnitCostt(String totalUnitCostt) {
this.totalUnitCostt = totalUnitCostt;
}
public void setYear(String year) {
this.year = year;
}
}

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;
}
}

Can't filter Firebase data with order by child

I want to show Firebase data filtered by userID. But the app crashes and after debugging it shows a NullPointerException on the Firebase adapter. What to do? I am implementing it in fragment. I am not pasting the imported libraries.
Here is my code:
public class MyPosts extends Fragment{
private RecyclerView postList;
private DatabaseReference mDatabase;
private DatabaseReference mDatabaseAppriciate;
private DatabaseReference mDatabaseDisgrace;
private LinearLayoutManager layoutManager;
private FirebaseAuth mAuth= FirebaseAuth.getInstance();
private DatabaseReference mDatabaseCurrentUser;
public Query mQueryCurrentUser=null;
//private static final String TAG = "MyActivity";
private boolean mProcessAppriciate=false;
private boolean mProcessDisgrace=false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
View rootView = inflater.inflate(R.layout.allposts, container, false);
mDatabase= FirebaseDatabase.getInstance().getReference().child("Posts");
mDatabaseAppriciate=FirebaseDatabase.getInstance().getReference().child("Appriciate");
mDatabaseDisgrace=FirebaseDatabase.getInstance().getReference().child("Disgrace");
mDatabase.keepSynced(true);
mDatabaseAppriciate.keepSynced(true);
mDatabaseDisgrace.keepSynced(true);
//EXPERIMENT WITH LISTVIEW STARTS
postList=(RecyclerView) rootView.findViewById(R.id.postList);
postList.setHasFixedSize(true);
layoutManager=new LinearLayoutManager(getActivity());
layoutManager.setReverseLayout(true);
postList.setHasFixedSize(true);
postList.setLayoutManager(layoutManager);
postList.getRecycledViewPool().clear();
//EXPERIMENT WITH LISTVIEW ENDS
return rootView;
}
#Override
public void onStart() {
super.onStart();
//EXP CODE STARTS
FirebaseAuth.getInstance().addAuthStateListener(new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
mDatabaseCurrentUser=FirebaseDatabase.getInstance().getReference().child("Posts");
String currentUserId=user.getUid();
mQueryCurrentUser=mDatabaseCurrentUser.orderByChild("uid").equalTo(currentUserId);
}else{
}
}
});
//EXP CODE ENDS
FirebaseRecyclerAdapter<Posts,PostViewHolder> firebaseRecyclerAdapter= new FirebaseRecyclerAdapter<Posts,PostViewHolder>(
Posts.class,
R.layout.single_post,
PostViewHolder.class,
mQueryCurrentUser
) {
#Override
protected void populateViewHolder(final PostViewHolder viewHolder, final Posts model, final int position) {
final String post_key=getRef(position).getKey();
viewHolder.setTitle(model.getTitle());
viewHolder.setDescription(model.getDescription());
viewHolder.setProfileName(model.getProfilename());
viewHolder.setImage(getContext(),model.getImage());
viewHolder.getLayoutPosition();
viewHolder.setAppriciateButton(post_key);
viewHolder.setDisgraceButton(post_key);
//Share click code below
viewHolder.Share.setOnClickListener(new View.OnClickListener() {
CallbackManager callbackManager;
ShareDialog shareDialog;
#Override
public void onClick(View v) {
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
shareDialog = new ShareDialog(MyPosts.this);
if (ShareDialog.canShow(ShareLinkContent.class)) {
ShareLinkContent content = new ShareLinkContent.Builder()
.setContentTitle(model.getTitle())
.setContentDescription(model.getDescription())
.setImageUrl(Uri.parse(model.getImage()))
.setContentUrl(Uri.parse("https://developers.facebook.com"))
.build();
shareDialog.show(content);
shareDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() {
#Override
public void onSuccess(Sharer.Result result) {
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
}
}
});
//Share click code ends above
//Appriciate button on click event below
viewHolder.Appriciate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProcessAppriciate=true;
mDatabaseAppriciate.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessAppriciate) {
if (dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())) {
mDatabaseAppriciate.child(post_key).child(mAuth.getCurrentUser().getUid()).removeValue();
mProcessAppriciate = false;
}else {
mDatabaseAppriciate.child(post_key).child(mAuth.getCurrentUser().getUid()).setValue(mAuth.getCurrentUser().getDisplayName());
mProcessAppriciate = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
//Appriciate button click event CODE ENDS
//Disgrace Button Click Event Code Starts
viewHolder.Disgrace.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProcessDisgrace=true;
mDatabaseDisgrace.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessDisgrace) {
if (dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())) {
mDatabaseDisgrace.child(post_key).child(mAuth.getCurrentUser().getUid()).removeValue();
mProcessDisgrace = false;
} else {
mDatabaseDisgrace.child(post_key).child(mAuth.getCurrentUser().getUid()).setValue(mAuth.getCurrentUser().getDisplayName());
mProcessDisgrace = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
//Disgrace Button Click code Ends
}
};
postList.setAdapter(firebaseRecyclerAdapter);
//test code
firebaseRecyclerAdapter.notifyDataSetChanged();
}
public static class PostViewHolder extends RecyclerView.ViewHolder{
View mView;
Button Appriciate;
Button Disgrace;
Button Share;
DatabaseReference mDatabaseAppriciate;
DatabaseReference mDatabaseDisgrace;
FirebaseAuth mAuth;
public PostViewHolder(View itemView) {
super(itemView);
mView=itemView;
Appriciate=(Button) mView.findViewById(R.id.appriciate);
Disgrace=(Button) mView.findViewById(R.id.disgraceful);
Share=(Button) mView.findViewById(R.id.share);
mDatabaseAppriciate=FirebaseDatabase.getInstance().getReference().child("Appriciate");
mDatabaseDisgrace=FirebaseDatabase.getInstance().getReference().child("Disgrace");
mAuth=FirebaseAuth.getInstance();
mDatabaseAppriciate.keepSynced(true);
mDatabaseDisgrace.keepSynced(true);
}
public void setAppriciateButton(final String post_key){
mDatabaseAppriciate.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())){
Appriciate.setBackgroundColor(Color.GRAY);
Appriciate.setText("Appriciated");
}else{
Appriciate.setBackgroundColor(Color.GREEN);
Appriciate.setText("APPRICIATE");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
//SET DISGRACE BUTTON CODE BELOW
public void setDisgraceButton(final String post_key){
mDatabaseDisgrace.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())){
Disgrace.setBackgroundColor(Color.GRAY);
Disgrace.setText("Disgraced");
}else{
Disgrace.setBackgroundColor(Color.RED);
Disgrace.setText("DISGRACE");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
//SET DISGRACE BUTTON CODE ENDS
//Setting the title to the AllActivity
public void setTitle(String title){
TextView postTitle=(TextView) mView.findViewById(R.id.allPostTitle);
postTitle.setText(title);
}
public void setDescription(String description){
TextView postDescription=(TextView) mView.findViewById(R.id.allPostDescription);
postDescription.setText(description);
}
//PROFILE NAME EXPERIMENT
public void setProfileName(String profilename){
TextView postName=(TextView) mView.findViewById(R.id.profileName);
postName.setText(profilename);
}
public void setImage(final Context context, final String image) {
final ImageView postImage=(ImageView) mView.findViewById(R.id.allPostImage);
with(context).load(image).networkPolicy(NetworkPolicy.OFFLINE).into(postImage, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(context).load(image).resize(500,700).into(postImage);
}
});
}
//THREADING EXPERIMENT CODE
}
}

Categories

Resources