how to view text di viewHolder - android

I want to display a text in my view holder but it doesn't appear, only the email text appears while the others don't. how to make it appear?
this is my view holder adapter
public TextView teksemail;
public TextView namanya;
public TextView golongannya;
ItemClickListener itemClickListener;
public listOnlineViewHolder(#NonNull View view) {
super(view);
teksemail = (TextView) view.findViewById(R.id.teksemail);
namanya = (TextView) view.findViewById(R.id.namanya);
golongannya = (TextView) view.findViewById(R.id.golongan);
view.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View v) {
itemClickListener.onClick(v, getAdapterPosition());
}
this is my information class
public class information {
public String email;
public String nama;
public String nalamat;
public String noTelpon;
public String golDar;
public String imageUrl;
public information() {
}
public information(String email, String nama, String nalamat, String noTelpon, String golDar, String imageUrl) {
this.email = email;
this.nama = nama;
this.nalamat = nalamat;
this.noTelpon = noTelpon;
this.golDar = golDar;
this.imageUrl = imageUrl;
}
public String getEmail() {
return email;
}
public String getNama() {
return nama;
}
public String getNalamat() {
return nalamat;
}
public String getNoTelpon() {
return noTelpon;
}
public String getGolDar() {
return golDar;
}
and this is my code viewholder in my activity
private FusedLocationProviderClient fused;
public TextView goldar, nama, telpon, alamat;
DatabaseReference onlineRef, currentUserRef, counterRef, locationsDatabase,databaseReference;
FirebaseRecyclerAdapter<information, listOnlineViewHolder> firebaseRecyclerAdapter;
int waktu = 3000;
RecyclerView list;
RecyclerView.LayoutManager layoutManager;
private FirebaseUser firebaseUser;
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_online);
list = (RecyclerView) findViewById(R.id.listonline);
list.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
list.setLayoutManager(layoutManager);
nama = findViewById(R.id.teksnama);
alamat = findViewById(R.id.teksalamat);
telpon = findViewById(R.id.tekstelpon);
goldar = findViewById(R.id.teksgoldar);
firebaseAuth = FirebaseAuth.getInstance();
if (firebaseAuth.getCurrentUser() != null) {
fused = LocationServices.getFusedLocationProviderClient(this);
//databaseReference = FirebaseDatabase.getInstance().getReference().child(firebaseUser.getUid()).child("data");
locationsDatabase = FirebaseDatabase.getInstance().getReference("locations");
onlineRef = FirebaseDatabase.getInstance().getReference().child(".info/connected");
counterRef= FirebaseDatabase.getInstance().getReference("lastOnline");
currentUserRef = FirebaseDatabase.getInstance().getReference("lastOnline").
child(FirebaseAuth.getInstance().getCurrentUser().getUid());
databaseReference = FirebaseDatabase.getInstance().getReference(firebaseAuth.getCurrentUser().getUid()).child("data");
//load user info
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String namanya = dataSnapshot.child("nama").getValue(String.class);
String addnya = dataSnapshot.child("alamat").getValue(String.class);
String nonya = dataSnapshot.child("noTelpon").getValue(String.class);
String goldarnya = dataSnapshot.child("golDar").getValue(String.class);
nama.setText(namanya);
alamat.setText(addnya);
telpon.setText(nonya);
goldar.setText(goldarnya);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
displayLocation();
if (ActivityCompat.checkSelfPermission(listOnline.this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && (ActivityCompat.checkSelfPermission
(listOnline.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(listOnline.this, new String[] {
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
},MY_PERMISSION_REQUEST_CODE);
} else {
if (checkPlayService()) {
buildGoogleApiClient();
createLocationRequest();
displayLocation();
}
}
}
}, waktu);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
setUpSystem();
//load all user from firebase
updateList();
}
}, waktu);
} else {
Toast.makeText(this, "Hai Resipienku!", Toast.LENGTH_SHORT).show();
if (ActivityCompat.checkSelfPermission(listOnline.this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && (ActivityCompat.checkSelfPermission
(listOnline.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(listOnline.this, new String[] {
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
},MY_PERMISSION_REQUEST_CODE);
fused.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
Toast.makeText(listOnline.this, "get your location!", Toast.LENGTH_SHORT).show();
}
});
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
setUpSystemResipien();
//load all user from firebase
updateList();
}
}, waktu);
}
}
/* private void loadUserInfo(String email) {
Query userLocation = locationsDatabase.orderByChild("email").equalTo(email);
userLocation.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
/*for (DataSnapshot posSnapshot:dataSnapshot.getChildren()) {
information track = posSnapshot.getValue(information.class);
String namanya = track.getNama();
nama.setText(track.getNama());
alamat.setText(track.getNalamat());
goldar.setText(track.getGolDar());
telpon.setText(track.getNoTelpon());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
*/
private void getLastLocation () {
fused.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
locationsDatabase.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(new tracking(
FirebaseAuth.getInstance().getCurrentUser().getEmail()
,FirebaseAuth.getInstance().getCurrentUser().getUid()
, String.valueOf(location.getLatitude())
, String.valueOf(location.getLongitude())
, nama.getText().toString()
, alamat.getText().toString().trim()
,goldar.getText().toString().trim()
,telpon.getText().toString().trim()));
Toast.makeText(listOnline.this, "get location", Toast.LENGTH_LONG).show();
}
});
}
private void updateList() {
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<information, listOnlineViewHolder>(
information.class, R.layout.user_online,
listOnlineViewHolder.class,
counterRef) {
#Override
protected void populateViewHolder(final listOnlineViewHolder viewHolder, final information model, int position) {
viewHolder.teksemail.setText(model.getEmail());
viewHolder.namanya.setText(model.getNama());
// Query userInfromation = databaseReference.orderByChild("email").equalTo(model.getEmail());
/* userInfromation.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot posSnapshot:dataSnapshot.getChildren()) {
information info = posSnapshot.getValue(information.class);
String name = dataSnapshot.child("nama").getValue(String.class);
String goldar = dataSnapshot.child("golDar").getValue(String.class);
viewHolder.namanya.setText(name);
viewHolder.golongannya.setText(goldar);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
*/
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position) {
fused.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
Intent map = new Intent(listOnline.this, trackingMaps.class);
map.putExtra("email", model.getEmail());
map.putExtra("lat", location.getLatitude());
map.putExtra("lnt", location.getLongitude());
startActivity(map);
}
});
// }
}
});
}
};
firebaseRecyclerAdapter.notifyDataSetChanged();
list.setAdapter(firebaseRecyclerAdapter);
}
//buat setup untuk resipien
private void setUpSystem() {
onlineRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue(Boolean.class)) {
currentUserRef.onDisconnect().removeValue();
counterRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).
setValue(new user(FirebaseAuth.getInstance().getCurrentUser().getEmail(), "online"
,nama.getText().toString(),goldar.getText().toString()));
firebaseRecyclerAdapter.notifyDataSetChanged();
}
counterRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot:dataSnapshot.getChildren()) {
user us = postSnapshot.getValue(user.class);
// Log.d("LOG", ""+us.getEmail()+"is"+us.getNamadia());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
I have tried to find a solution but could not find it. I really hope you can help me. thank you!
this is my XML which is contained your textviews
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardElevation="10dp"
android:layout_margin="16dp"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp">
<TextView
android:layout_weight="8"
android:textSize="24sp"
android:text="test#gmail.com"
android:id="#+id/teksemail"
android:textColor="#000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/namanya"
android:text="nama"
android:textSize="16dp"
android:layout_below="#+id/teksemail"
android:textColor="#000"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/golongan"
android:text="golongan"
android:textSize="16dp"
android:layout_below="#+id/namanya"
android:textColor="#000"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:src="#mipmap/ic_launcher"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>

Related

Recycler view duplicates newly added item every time you load the activity again

I am building a chatting app. and in it i have a messaging system powered by firebase. and to load them on the front end I am using recycler view however every time I leave the activity and come back it is still fine but when I add a new message after coming back I duplicates
if that seemed hard to understand here is a video showing what is happening
Recycler View Adapter
public List<Chat> chatList;
public FirebaseAuth mAuth;
public DatabaseReference reference;
public DatabaseReference dbRef;
public String userid;
public MessageAdapter(List<Chat> chat, String userId) {
this.chatList = chat;
this.userid = userId;
}
public class MessageViewHolder extends RecyclerView.ViewHolder {
public TextView senderMessage, ReceiverMessage, sender_image_time, receiver_image_time, sender_name, receiver_name, sender_audio_time, receiver_audio_time;
public ImageView messageSenderPicture,messageReceiverPicture;
public CircleImageView receiver_profile_image, sender_profile_image, sender_audio_image, receiver_audio_image;
public SeekBar sender_audio_bar, receiver_audio_bar;
public ImageButton sender_audio_play, receiver_audio_play, sender_audio_pause, receiver_audio_pause;
public ImageView sender_imageView, receiverImageView;
public ConstraintLayout sender_audio_layout, receiver_audio_layout;
public MediaPlayer mediaPlayer;
public Handler handler = new Handler();
public Runnable runnable;
public MessageViewHolder(#NonNull View itemView) {
super(itemView);
senderMessage = itemView.findViewById(R.id.senderText);
ReceiverMessage = itemView.findViewById(R.id.receiverText);
messageReceiverPicture = itemView.findViewById(R.id.message_receiver_image_view);
messageSenderPicture = itemView.findViewById(R.id.message_sender_image_view);
sender_image_time = itemView.findViewById(R.id.sender_time_image);
receiver_image_time = itemView.findViewById(R.id.receiver_time_image);
receiver_profile_image = itemView.findViewById(R.id.receiver_profile_image);
sender_profile_image = itemView.findViewById(R.id.sender_profile_image);
sender_name = itemView.findViewById(R.id.sender_name);
receiver_name = itemView.findViewById(R.id.receiver_name);
sender_audio_layout = itemView.findViewById(R.id.sender_audio_layout);
receiver_audio_layout = itemView.findViewById(R.id.receiver_audio_layout);
sender_audio_image = itemView.findViewById(R.id.sender_image_audio);
receiver_audio_image = itemView.findViewById(R.id.receiver_image_audio);
sender_audio_bar = itemView.findViewById(R.id.seekBar);
receiver_audio_bar = itemView.findViewById(R.id.receiver_seekBar);
sender_audio_play = itemView.findViewById(R.id.sender_play);
receiver_audio_play = itemView.findViewById(R.id.receiver_play);
sender_audio_time = itemView.findViewById(R.id.sender_audio_time);
receiver_audio_time = itemView.findViewById(R.id.receiver_audio_time);
sender_imageView = itemView.findViewById(R.id.imageView4);
receiverImageView = itemView.findViewById(R.id.receiver_imageView4);
sender_audio_pause = itemView.findViewById(R.id.sender_pause);
receiver_audio_pause = itemView.findViewById(R.id.receiver_pause);
mediaPlayer = new MediaPlayer();
}
}
#NonNull
#Override
public MessageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.custom_meeage_layout, parent, false);
mAuth = FirebaseAuth.getInstance();
return new MessageViewHolder(view);
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull final MessageViewHolder holder, final int position) {
String messageSenderId = Objects.requireNonNull(mAuth.getCurrentUser()).getUid();
final Chat chat = chatList.get(position);
String fromUserID = chat.getSender();
String userID = chat.getReceiver();
String fromMessageType = chat.getType();
reference = FirebaseDatabase.getInstance().getReference().child("Users").child(fromUserID);
dbRef = FirebaseDatabase.getInstance().getReference().child(userID);
holder.senderMessage.setVisibility(View.GONE);
holder.ReceiverMessage.setVisibility(View.GONE);
holder.messageSenderPicture.setVisibility(View.GONE);
holder.messageReceiverPicture.setVisibility(View.GONE);
holder.receiver_image_time.setVisibility(View.GONE);
holder.sender_image_time.setVisibility(View.GONE);
holder.sender_profile_image.setVisibility(View.GONE);
holder.receiver_profile_image.setVisibility(View.GONE);
holder.sender_name.setVisibility(View.GONE);
holder.receiver_name.setVisibility(View.GONE);
holder.sender_audio_layout.setVisibility(View.GONE);
holder.receiver_audio_layout.setVisibility(View.GONE);
if (fromMessageType.equals("text")) {
if (fromUserID.equals(messageSenderId)) {
holder.senderMessage.setVisibility(View.VISIBLE);
holder.senderMessage.setBackgroundResource(R.drawable.sender_layout);
holder.senderMessage.setText(chat.getMessage() + "\n" + " " + chat.getTime());
} else {
holder.senderMessage.setVisibility(View.INVISIBLE);
holder.ReceiverMessage.setVisibility(View.VISIBLE);
holder.ReceiverMessage.setBackgroundResource(R.drawable.receiver_layout);
holder.ReceiverMessage.setText(chat.getMessage() + "\n" + " " + chat.getTime());
}
}else if (fromMessageType.equals("image")) {
if (fromUserID.equals(messageSenderId)) {
holder.messageSenderPicture.setVisibility(View.VISIBLE);
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("Users").child(messageSenderId).child("name").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
String name = snapshot.getValue().toString();
holder.sender_name.setText(name);
} else {}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
holder.sender_name.setVisibility(View.VISIBLE);
ref.child("Users").child(messageSenderId).child("image").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
String imageUrl = snapshot.getValue().toString();
Picasso.get().load(imageUrl).into(holder.sender_profile_image);
} else {}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
holder.sender_profile_image.setVisibility(View.VISIBLE);
Picasso.get().load(chat.getMessage()).into(holder.messageSenderPicture);
holder.sender_image_time.setVisibility(View.VISIBLE);
holder.sender_image_time.setText(chat.getTime());
} else {
holder.messageReceiverPicture.setVisibility(View.VISIBLE);
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("Users").child(userid).child("name").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
String name = snapshot.getValue().toString();
holder.receiver_name.setText(name);
} else {}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
holder.receiver_name.setVisibility(View.VISIBLE);
ref.child("Users").child(userid).child("image").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
String imageUrl = snapshot.getValue().toString();
Picasso.get().load(imageUrl).into(holder.receiver_profile_image);
} else {}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
holder.receiver_profile_image.setVisibility(View.VISIBLE);
Picasso.get().load(chat.getMessage()).into(holder.messageReceiverPicture);
holder.receiver_image_time.setVisibility(View.VISIBLE);
holder.receiver_image_time.setText(chat.getTime());
}
} else if(fromMessageType.equals("audio")) {
if (fromUserID.equals(messageSenderId)) {
holder.sender_audio_layout.setVisibility(View.VISIBLE);
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("Users").child(messageSenderId).child("image").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
String imageUrl = snapshot.getValue().toString();
Picasso.get().load(imageUrl).into(holder.sender_audio_image);
} else {}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
holder.sender_audio_time.setText(chat.getTime());
final MediaPlayer mediaPlayer = new MediaPlayer();
holder.sender_audio_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.sender_audio_play.setVisibility(View.INVISIBLE);
holder.sender_audio_pause.setVisibility(View.VISIBLE);
try {
mediaPlayer.setDataSource(chat.getMessage());
mediaPlayer.prepare();
mediaPlayer.start();
holder.sender_audio_bar.setProgress(mediaPlayer.getCurrentPosition());
} catch (IOException e) {
e.printStackTrace();
}
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
holder.sender_audio_play.setVisibility(View.VISIBLE);
holder.sender_audio_pause.setVisibility(View.INVISIBLE);
holder.sender_audio_bar.setProgress(mediaPlayer.getCurrentPosition());
}
});
holder.sender_audio_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.sender_audio_play.setVisibility(View.VISIBLE);
holder.sender_audio_pause.setVisibility(View.INVISIBLE);
mediaPlayer.pause();
mediaPlayer.reset();
holder.sender_audio_bar.setProgress(mediaPlayer.getCurrentPosition());
}
});
} else {
holder.receiver_audio_layout.setVisibility(View.VISIBLE);
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("Users").child(userid).child("image").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
String imageUrl = snapshot.getValue().toString();
Picasso.get().load(imageUrl).into(holder.receiver_audio_image);
} else {}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
holder.receiver_audio_time.setText(chat.getTime());
final MediaPlayer mediaPlayer = new MediaPlayer();
holder.receiver_audio_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.receiver_audio_play.setVisibility(View.INVISIBLE);
holder.receiver_audio_pause.setVisibility(View.VISIBLE);
try {
mediaPlayer.setDataSource(chat.getMessage());
mediaPlayer.prepare();
mediaPlayer.start();
holder.receiver_audio_bar.setProgress(mediaPlayer.getCurrentPosition());
} catch (IOException e) {
e.printStackTrace();
}
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
holder.receiver_audio_play.setVisibility(View.VISIBLE);
holder.receiver_audio_pause.setVisibility(View.INVISIBLE);
holder.receiver_audio_bar.setProgress(mediaPlayer.getCurrentPosition());
}
});
holder.receiver_audio_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.receiver_audio_play.setVisibility(View.VISIBLE);
holder.receiver_audio_pause.setVisibility(View.INVISIBLE);
mediaPlayer.pause();
mediaPlayer.reset();
holder.receiver_audio_bar.setProgress(mediaPlayer.getCurrentPosition());
}
});
}
} else {
if (fromUserID.equals(messageSenderId)) {
holder.messageSenderPicture.setVisibility(View.VISIBLE);
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("Users").child(messageSenderId).child("image").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
String imageUrl = snapshot.getValue().toString();
Picasso.get().load(imageUrl).into(holder.sender_profile_image);
} else {}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
holder.sender_profile_image.setVisibility(View.VISIBLE);
holder.messageSenderPicture.setBackgroundResource(R.drawable.file);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(chatList.get(position).getMessage()));
holder.itemView.getContext().startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(holder.itemView.getContext(), "Your Current Device Doesn't have the application to preview this file", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
});
} else {
holder.messageReceiverPicture.setVisibility(View.VISIBLE);
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("Users").child(userid).child("image").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
String imageUrl = snapshot.getValue().toString();
Picasso.get().load(imageUrl).into(holder.receiver_profile_image);
} else {}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
holder.receiver_profile_image.setVisibility(View.VISIBLE);
holder.messageReceiverPicture.setBackgroundResource(R.drawable.file);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(chatList.get(position).getMessage()));
holder.itemView.getContext().startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(holder.itemView.getContext(), "Your Current Device Doesn't have the application to preview this file", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
});
}
}
}
#Override
public int getItemCount() {
return chatList.size();
}
}
My Chat Activity
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#SuppressLint("ShowToast")
#Override
protected void onStart() {
super.onStart();
Toast.makeText(SarimPage.this, fUser.getUid(), Toast.LENGTH_SHORT); // Validate Id
Global global = new Global();
global.updateUserStatus("Active Now");
reference.child("Users").child(Objects.requireNonNull(getIntent().getStringExtra("userID"))).child("userState")
.addValueEventListener(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
String status21 = Objects.requireNonNull(snapshot.child("state").getValue()).toString();
String time = Objects.requireNonNull(snapshot.child("time").getValue()).toString();
if (status21.equals("offline")) {
status2.setVisibility(View.VISIBLE);
userStatus.setText("Last Seen " + time);
}
if(status21.equals("online")) {
status2.setVisibility(View.INVISIBLE);
status.setVisibility(View.VISIBLE);
userStatus.setText(status21);
}
if(status21.equals("Active Now")){
status2.setVisibility(View.INVISIBLE);
status.setVisibility(View.VISIBLE);
userStatus.setText(status21);
}
if(status21.equals("typing...")){
status2.setVisibility(View.INVISIBLE);
status.setVisibility(View.VISIBLE);
userStatus.setText(status21);
}
if (status21.equals("away")) {
status3.setVisibility(View.VISIBLE);
userStatus.setText(status21);
}
} else {}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
reference.child("Messages").addChildEventListener(new ChildEventListener() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onChildAdded(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
Chat chats = snapshot.getValue(Chat.class);
assert chats != null;
if(chats.getReceiver().equals(currentUser) && chats.getSender().equals(userID)
|| chats.getReceiver().equals(userID) && chats.getSender().equals(currentUser)) {
chatList.add(chats);
}
messageAdapter.notifyDataSetChanged();
messageList.smoothScrollToPosition(Objects.requireNonNull(messageList.getAdapter()).getItemCount());
}
#Override
public void onChildChanged(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot snapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected void onUserLeaveHint() {
Global global = new Global();
global.updateUserStatus("offline");
chatList.clear();
super.onUserLeaveHint();
}
#Override
protected void onStop() {
super.onStop();
chatList.clear();
}
#Override
protected void onDestroy() {
super.onDestroy();
chatList.clear();
}
Sorry there is way too much code in this activity so i am only showing methods i think will be usefull such as what i am doing on acitivty start stop or pause.
Chat Model
public class Chat {
private String sender;
private String receiver;
private String message;
private String time;
private String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Chat() {}
public Chat(String sender, String receiver, String message) {
this.message = message;
this.receiver = receiver;
this.sender = sender;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
(Also when i do this i want all the previous chat history to still be displayed)
I'm not really sure if this is the main source of your problems, but it seems like the ChildEventListener you're adding on Messages reference is being called every time the activity is launched or relaunched. This has the effect of adding multiple listener to the Messages reference (multiple time the lates child added to your RecyclerView), what you should do is to maybe move the
reference.child("Messages").addChildEventListener(new ChildEventListener() {...}
inside onCreate or make sure there is only one ChildEventListener listening to your Messages reference when launching your activity.
Hope this will help, have a good day :)
Get same firebase instance when you reopen app.
FirebaseDatabase database;
//always use this getFirebaseDatabase() method when you need database instance.
public FirebaseDatabase getFirebaseDatabase() {
if(database==null){
database=FirebaseDatabase.getInstance();
}
return database;
}

RecyclerView items not Displayed in my MainActivity

I'm building a chat app which have post feature, When I create a post in NewPostActivity, the image and text are uploaded (because I can see them in firebase Database tree) but The problem is nothing is shown in my MainActivity which is supposed to display my posts.
I used Firebase UI for the Rv but I'm not sure is the problem lies in NewPostActivity or the MainActivity.
I tried to run the debugger to see but there is no error or null point exception.
NewPostActivity.java
btnPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startPosting();
}
});
}
private void startPosting() {
progressDialog=new ProgressDialog(NewPostActivity.this);
progressDialog.setTitle("Uploading Image");
progressDialog.setMessage("Please Wait while we process the image");
progressDialog.setCanceledOnTouchOutside(false);
final String desc_val=mPostDesc.getText().toString().trim();
if(!TextUtils.isEmpty(desc_val) && mImageUri!=null){
progressDialog.show();
String random_name= random();
StorageReference filepath = storageReference.child("Blog_Images").child(random_name);
filepath.putFile(mImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
Task<Uri> uriTask = task.getResult().getStorage().getDownloadUrl();
while (!uriTask.isComplete());
final Uri downloadUrl = uriTask.getResult();
final DatabaseReference newPost = mRootRef.child("Blog").push();
final String user_id= mCurrentUser.getUid();
mRootRef.child("Users").child(user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
newPost.child("desc").setValue(desc_val);
newPost.child("image").setValue(downloadUrl.toString());
newPost.child("user_id").setValue(user_id);
newPost.child("timestamp").setValue(ServerValue.TIMESTAMP);
newPost.child("username").setValue(dataSnapshot.child("name").getValue());
newPost.child("thumb_image").setValue(dataSnapshot.child("thumb_image").getValue());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
progressDialog.dismiss();
startActivity(new Intent(NewPostActivity.this,MainActivity.class));
finish();
}
});
}
}
MainActivity.java
Query conversationQuery = mDatabase.orderByChild("timestamp");
FirebaseRecyclerOptions<Blog> options = new FirebaseRecyclerOptions.Builder<Blog>()
.setQuery(conversationQuery, Blog.class)
.build();
FirebaseRecyclerAdapter<Blog, BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(options) {
#NonNull
#Override
public BlogViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.post_single_layout, parent, false);
mAuth = FirebaseAuth.getInstance();
return new BlogViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull final BlogViewHolder viewHolder, int position, #NonNull final Blog model) {
viewHolder.setContext(getApplicationContext());
final String list_blog_id = getRef(position).getKey();
viewHolder.setLikeBtns(list_blog_id);
Query lastMessageQuery = mDatabase.child(list_blog_id).limitToLast(1);
lastMessageQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
viewHolder.setDesc(model.getDesc());
viewHolder.setImage(model.getImage());
viewHolder.setUsername(model.getUsername());
viewHolder.setStatus(model.getStatus());
viewHolder.setPostImage(model.getThumb_image());
viewHolder.setTime(model.getTimestamp());
userID = model.getUid();
}
#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) {
}
});
viewHolder.postImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent imageFullScreen = new Intent(getApplicationContext(), PhotoActivity.class);
imageFullScreen.putExtra("uid", list_blog_id);
imageFullScreen.putExtra("from", "RequestsFragment");
startActivity(imageFullScreen);
}
});
viewHolder.mLikeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProcessLike = true;
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessLike) {
if (dataSnapshot.child(list_blog_id).hasChild(mAuth.getCurrentUser().getUid())) {
mDatabaseLike.child(list_blog_id).child(mAuth.getCurrentUser().getUid()).removeValue();
mProcessLike = false;
} else {
mDatabaseLike.child(list_blog_id).child(mAuth.getCurrentUser().getUid()).setValue("Lliked");
mProcessLike = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
};
mBlogList.setAdapter(firebaseRecyclerAdapter);
}
There is some parts of your code that are not shown, also as I don't see a screenshot of your database I don't know if I will give a correct answer, but obviously you need to start listening to the database before you get the data with firebase UI.
So before this:
mBlogList.setAdapter(firebaseRecyclerAdapter);
Add this:
firebaseRecyclerAdapter.startListening();
Refer to this to know more about how to set your firebase UI.

android :button not working after i go to the activity again

i have a button in an activity to send a message by it
the problem is if the person entered the page the button send the message
but if he exit from the page and opened it again .. the button not working
its like became disabled
and the solutions that i used
1 - i disabled the butterknife library and used
setOnClickListener
2 - i added
android:clickable="true"
android:focusable="false"
android:focusableInTouchMode="false"
but it didnt work
and i used the log as a test
.. and its like the button became disabled
although
another page have a similar code
and the button working perfectly in it
and this is the activity xml code
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:windowSoftInputMode="adjustPan"
android:layoutDirection="rtl"
android:textDirection="rtl"
android:layout_height="match_parent"
android:background="#color/colorPrimary"
tools:context=".Activities.SentMessagesActivity">
<include layout="#layout/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tb_sent_Messages"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<android.support.v4.widget.SwipeRefreshLayout
android:layout_width="match_parent"
android:layout_height="#dimen/dp_0"
app:layout_constraintBottom_toTopOf="#+id/et_sent_messages"
app:layout_constraintTop_toBottomOf="#id/tb_sent_Messages"
android:layout_marginBottom="#dimen/dp_10"
android:id="#+id/srl_sent">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="#dimen/dp_0"
android:background="#drawable/new_background"
android:isScrollContainer="false"
android:id="#+id/rv_sent_messages"
android:padding="#dimen/dp_10" />
</android.support.v4.widget.SwipeRefreshLayout>
<Button
android:id="#+id/ib_sent_messages_send"
android:layout_height="#dimen/dp_40"
android:layout_width="#dimen/dp_40"
android:layout_margin="#dimen/dp_10"
android:layout_marginStart="8dp"
android:background="#drawable/sent"
android:clickable="true"
android:focusable="false"
android:focusableInTouchMode="false"
app:layout_constraintStart_toEndOf="#id/et_sent_messages"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<EditText
android:id="#+id/et_sent_messages"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/dp_10"
android:background="#drawable/edittextborders"
android:hint="#string/write_ypur_message"
android:maxHeight="#dimen/dp_70"
android:padding="#dimen/dp_10"
android:onClick="openKeyboard"
app:layout_constraintEnd_toStartOf="#+id/ib_sent_messages_send"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintBottom_toBottomOf="parent">
<requestFocus />
</EditText>
and the Java code
public class SentMessagesActivity extends AppCompatActivity {
Button mSend;
#BindView(R.id.tb_sent_Messages)
Toolbar mToolbar;
#BindView(R.id.rv_sent_messages)
RecyclerView mMessagesList;
#BindView(R.id.et_sent_messages)
EditText mMessage;
#BindView(R.id.srl_sent)
SwipeRefreshLayout mRefresh;
TinyDB db;
private FirebaseRecyclerAdapter<Message, MessagesHolder> mAdapter;
private ActionBar mActionBar;
private FirebaseAuth mAuth;
private DatabaseReference mFriendContacts;
private DatabaseReference mMyMessagesRef;
private DatabaseReference mFriendMessagesRef;
private DatabaseReference mFriendRef;
private DatabaseReference mMyRef;
private DatabaseReference mReference;
private int count;
private int mCurrentPage = 1;
private String myImage;
private Dialog mProgressDialoge;
private String myId;
private String friendId = "";
private String Image = "";
private Long State;
private String Name = "";
private TextView mToolTitle ,mToolState;
private TimeAgo timeAgo;
private String myName = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sent_messages);
ButterKnife.bind(this);
mProgressDialoge = new Dialog(SentMessagesActivity.this);
friendId = getIntent().getStringExtra(App_Constants.FRIEND_ID);
mAuth = FirebaseAuth.getInstance();
myId = mAuth.getUid();
db = new TinyDB(this);
mSend = findViewById(R.id.ib_sent_messages_send);
mReference = FirebaseDatabase.getInstance().getReference().child(App_Constants.USERS_CELL).child(myId).child(App_Constants.USER_INFO_CELL);
mReference.keepSynced(true);
mMyMessagesRef = FirebaseDatabase.getInstance().getReference().child(App_Constants.USERS_CELL).child(myId).child(App_Constants.MESSAGES_CELL).child(App_Constants.SENT_CELL).child(friendId);
mMyMessagesRef.keepSynced(true);
mFriendMessagesRef = FirebaseDatabase.getInstance().getReference().child(App_Constants.USERS_CELL).child(friendId).child(App_Constants.MESSAGES_CELL).child(App_Constants.RECEIVED).child(myId);
mFriendMessagesRef.keepSynced(true);
mFriendRef = FirebaseDatabase.getInstance().getReference().child(App_Constants.USERS_CELL).child(friendId).child(App_Constants.USER_INFO_CELL);
mFriendRef.keepSynced(true);
mMyRef = FirebaseDatabase.getInstance().getReference().child(App_Constants.USERS_CELL).child(myId).child(App_Constants.CONTACTS_CELL).child(App_Constants.SENT_CELL);
mMyRef.keepSynced(true);
mFriendContacts = FirebaseDatabase.getInstance().getReference().child(App_Constants.USERS_CELL).child(friendId).child(App_Constants.CONTACTS_CELL).child(App_Constants.RECEIVED);
mFriendContacts.keepSynced(true);
App_Utilities.initializingProgress(mProgressDialoge);
mProgressDialoge.show();
mReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
myImage= dataSnapshot.child(App_Constants.USER_IMAGE_CELL).getValue().toString();
myName = dataSnapshot.child(App_Constants.USER_NAME_CELL).getValue().toString();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
mMyMessagesRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
count = (int) dataSnapshot.getChildrenCount();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("");
mActionBar = getSupportActionBar();
mActionBar.setDisplayHomeAsUpEnabled(true);
mActionBar.setDisplayShowCustomEnabled(true);
initializingActionBar();
intitializingRecyclerView();
mRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mCurrentPage++;
intitializingRecyclerView();
}
});
refreshingLayout();
mSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String Text = mMessage.getText().toString().trim();
Toast.makeText(SentMessagesActivity.this, "Clicked", Toast.LENGTH_SHORT).show();
if (!TextUtils.isEmpty(Text))
{
message(Text.trim());
}
}
});
}
#Override
protected void onStart() {
super.onStart();
if (mAuth.getCurrentUser() == null)
{
App_Utilities.startEndActivity(SentMessagesActivity.this,StartActivity.class);
mProgressDialoge.dismiss();
}
mAdapter.startListening();
mProgressDialoge.show();
new CountDownTimer(1000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
if (count > 15)
{
mMessagesList.scrollToPosition(App_Constants.TOTAL_ITEMS_TO_LOAD - 1);
} else
{
mMessagesList.scrollToPosition(count - 1);
}
mProgressDialoge.hide();
}
}.start();
mFriendMessagesRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if ((boolean)dataSnapshot.child(App_Constants.SEEN).getValue() == false)
{
mFriendMessagesRef.child(dataSnapshot.getKey()).child(App_Constants.SEEN).setValue(true);
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
protected void onPause() {
super.onPause();
db.putBoolean(App_Constants.ISWORKING,false);
}
// public void onClickImage(View view) {
//
//
// }
#Override
protected void onResume() {
super.onResume();
db.putBoolean(App_Constants.ISWORKING,true);
}
private void refreshingLayout()
{
mMyMessagesRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if (count > 15)
{
mMessagesList.scrollToPosition(App_Constants.TOTAL_ITEMS_TO_LOAD - 1);
} else
{
mMessagesList.scrollToPosition(count - 1);
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void message(String Text) {
final HashMap map = new HashMap();
map.put(App_Constants.MESSAGES_CELL,Text);
map.put(App_Constants.FROM,myId);
map.put(App_Constants.SEEN,false);
map.put(App_Constants.TYPE,App_Constants.SENT_CELL);
mMyMessagesRef.push().setValue(map).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
{
map.put(App_Constants.TYPE,App_Constants.RECEIVED);
mFriendMessagesRef.push().setValue(map).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
{
mMessage.setText("");
if (count > 15)
{
mMessagesList.scrollToPosition((App_Constants.TOTAL_ITEMS_TO_LOAD * mCurrentPage )- 1);
} else
{
mMessagesList.scrollToPosition(count - 1);
}
}
else
{
Toast.makeText(SentMessagesActivity.this, R.string.failed_to_send, Toast.LENGTH_SHORT).show();
}
}
});
}else
{
Toast.makeText(SentMessagesActivity.this, R.string.failed_to_send, Toast.LENGTH_SHORT).show();
}
}
});
}
private void initializingActionBar()
{
LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = mInflater.inflate(R.layout.messages_toolbar,null);
mActionBar.setCustomView(view);
mToolTitle = findViewById(R.id.tv_toolbar_name);
mToolState = findViewById(R.id.tv_toolbar_state);
mFriendRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Name = dataSnapshot.child(App_Constants.USER_NAME_CELL).getValue().toString();
Image = dataSnapshot.child(App_Constants.USER_IMAGE_CELL).getValue().toString();
State = (Long) dataSnapshot.child(App_Constants.ONLINE_CELL).getValue();
mToolTitle.setText(Name);
mToolTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openProfile();
}
});
if (State == App_Constants.ZERO)
{
mToolState.setText(R.string.online);
} else
{
mToolState.setText(TimeAgo.getTimeAgo(State,getApplicationContext()));
}
mProgressDialoge.hide();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void intitializingRecyclerView()
{
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setStackFromEnd(true);
mMessagesList.setLayoutManager(layoutManager);
mMessagesList.setHasFixedSize(true);
Query mQuery = mMyMessagesRef.limitToLast(mCurrentPage * App_Constants.TOTAL_ITEMS_TO_LOAD);
FirebaseRecyclerOptions mOptions = new FirebaseRecyclerOptions.Builder<Message>()
.setQuery(mQuery,Message.class).build();
mAdapter = new FirebaseRecyclerAdapter<Message, MessagesHolder>(mOptions) {
#Override
protected void onBindViewHolder(#NonNull MessagesHolder holder, int position, #NonNull Message model) {
if (model.getFrom().equals(myId))
{
holder.fillSentMessage(myImage,model.getMessages(),myName);
} else if (model.getFrom().equals(friendId))
{
holder.fillReceivedMessage(Image,model.getMessages(),Name);
}
}
#NonNull
#Override
public MessagesHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_sent_message,parent,false);
return new MessagesHolder(view,parent.getContext());
}
};
mMessagesList.setAdapter(mAdapter);
mAdapter.startListening();
mRefresh.setRefreshing(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.block_menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case R.id.bt_menu_block:
blockUser();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void blockUser() {
new AlertDialog.Builder(SentMessagesActivity.this)
.setTitle(getString(R.string.block_this_person))
.setMessage(R.string.would_u_like_to_block)
.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
yesBlock();
}
})
.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
private void yesBlock() {
mMyRef.child(friendId).child(App_Constants.TYPE).setValue(App_Constants.BLOCKED_FROMME).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
{
mFriendContacts.child(myId).child(App_Constants.TYPE).setValue(App_Constants.BLOCKED).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
{
mMyMessagesRef.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
{
mFriendMessagesRef.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
App_Utilities.startEndActivity(SentMessagesActivity.this,MainActivity.class);
}
});
}
}
});
}
}
});
}
}
});
}
private void openProfile()
{
Intent intent = new Intent(SentMessagesActivity.this,UserActivity.class);
intent.putExtra(App_Constants.FRIEND_ID,friendId);
startActivity(intent);
}
public void openKeyboard(View view)
{
((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE))
.showSoftInput(mMessage, InputMethodManager.SHOW_FORCED);
}
}
this is happening on some mobiles like samsung
but working fine in others
Add your
Button mSend;
#BindView(R.id.tb_sent_Messages)
Toolbar mToolbar;
#BindView(R.id.rv_sent_messages)
RecyclerView mMessagesList;
#BindView(R.id.et_sent_messages)
EditText mMessage;
#BindView(R.id.srl_sent)
SwipeRefreshLayout mRefresh;
Put the logic above or initialize the widgets and button without butterknife, in the onCreate() function

How to get same Scroll position on Staggered Grid Layout on back pressed from another activity which was showing detail of the post

I want to know how to save scroll position and restore scroll position, if I come from another activity with onbackpressed button. I m stuck in this and tried many ways in last some days, but all went in vain. Any help will be much appreciated.
Following is my Activity.class
private ImageButton mhomebtn;
private ImageButton mexplorebtn;
private ImageButton mcamerabtn;
private ImageButton mstorebtn;
private ImageButton mprofilebtn;
private RecyclerView mexplore_page;
private StaggeredGridLayoutManager mgrid;
private DatabaseReference mdatabase;
private DatabaseReference mdatabaseLike;
private DatabaseReference mdatabaseSave;
private DatabaseReference mdatabasefollow;
private DatabaseReference mdatabasefollowers;
private boolean mProcessSave = false;
private boolean mProcessLike = false;
private FirebaseAuth mAuth;
private static final int TIME_OUT = 2000;
private String mCurrent_state;
private Animation mslide_up;
private static int mPosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_explore);
mAuth = FirebaseAuth.getInstance();
String uid = mAuth.getCurrentUser().getUid();
mdatabase = FirebaseDatabase.getInstance().getReference().child("Explores");
mdatabaseLike = FirebaseDatabase.getInstance().getReference().child("Like");
mdatabaseSave = FirebaseDatabase.getInstance().getReference().child("Saved");
mdatabasefollow = FirebaseDatabase.getInstance().getReference().child("Following");
mdatabasefollowers = FirebaseDatabase.getInstance().getReference().child("Followers");
mdatabasefollowers.keepSynced(true);
mdatabaseLike.keepSynced(true);
mdatabaseSave.keepSynced(true);
mdatabasefollow.keepSynced(true);
mhomebtn = (ImageButton) findViewById(R.id.homebtn);
mexplorebtn = (ImageButton) findViewById(R.id.explorebtn);
mcamerabtn = (ImageButton) findViewById(R.id.camerabtn);
mstorebtn = (ImageButton) findViewById(R.id.storebtn);
mprofilebtn = (ImageButton) findViewById(R.id.profilebtn);
mslide_up = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_up);
mslide_up.setAnimationListener(this);
mgrid = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
mgrid.setReverseLayout(true);
mexplore_page = (RecyclerView) findViewById(R.id.explore_page);
mexplore_page.setHasFixedSize(true);
mexplore_page.setLayoutManager(mgrid);
mCurrent_state = "not_following";
mhomebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ExploreActivity.this, HomeActivity.class));
}
});
mexplorebtn.setImageResource(R.mipmap.ic_explore_blue);
mcamerabtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ExploreActivity.this, CameraActivity.class));
}
});
mstorebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ExploreActivity.this, StoreActivity.class));
}
});
mprofilebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ExploreActivity.this, ProfileActivity.class));
}
});
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter <Explores, ExploreViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Explores, ExploreViewHolder>(
Explores.class,
R.layout.explore_row,
ExploreViewHolder.class,
mdatabase
) {
#Override
protected void populateViewHolder(final ExploreViewHolder viewHolder, Explores model, final int position) {
final String post_key = getRef(position).getKey();
mPosition = position;
viewHolder.setPostimage(getApplicationContext(), model.getPostimage());
viewHolder.setLikebtn(post_key);
viewHolder.setAddgallerybtn(post_key);
final String uid = mAuth.getCurrentUser().getUid();
mdatabase.child(post_key).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String right = dataSnapshot.child("right").getValue(String.class);
String center = dataSnapshot.child("center").getValue(String.class);
String left = dataSnapshot.child("lefttop").getValue(String.class);
final String category = dataSnapshot.child("category").getValue(String.class);
final String description = dataSnapshot.child("description").getValue(String.class);
final String heading = dataSnapshot.child("heading").getValue(String.class);
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ExploreActivity.this, DetailActivity.class));
}
});
final String post_uid = dataSnapshot.child("uid").getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
viewHolder.maddgallerybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProcessSave = true;
mdatabaseSave.child(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessSave){
if (dataSnapshot.hasChild(post_key)){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
viewHolder.mmessagetext.setVisibility(View.VISIBLE);
}
},TIME_OUT);
mProcessSave = false;
}else {
mdatabase.child(post_key).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
DatabaseReference newSaved = mdatabaseSave.child(uid).child(post_key);
newSaved.child("postimage").setValue(dataSnapshot.child("postimage").getValue());
newSaved.child("heading").setValue(dataSnapshot.child("heading").getValue()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mProcessSave = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
mdatabaseLike.child(post_key).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long likecounts = dataSnapshot.getChildrenCount();
mdatabase.child(post_key).child("likecounts").setValue(likecounts);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mdatabase.child(post_key).addValueEventListener(new ValueEventListener() {
#SuppressWarnings("ConstantConditions")
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild("likecounts")){
int count = dataSnapshot.child("likecounts").getValue(int.class);
}else {
Toast.makeText(ExploreActivity.this, "Post has been deleted successfully", Toast.LENGTH_SHORT).show();
}
String post_uid = dataSnapshot.child("uid").getValue(String.class);
viewHolder.midtext.setText(post_uid);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
viewHolder.mlikebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProcessLike = true;
mdatabaseLike.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessLike){
if (dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())){
mdatabaseLike.child(post_key).child(mAuth.getCurrentUser().getUid()).removeValue();
mProcessLike = false;
} else {
mdatabaseLike.child(post_key).child(mAuth.getCurrentUser().getUid()).setValue(mAuth.getCurrentUser().getEmail());
mProcessLike = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
};
mexplore_page.setAdapter(firebaseRecyclerAdapter);
}
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
public static class ExploreViewHolder extends RecyclerView.ViewHolder{
View mView;
ImageButton mlikebtn;
ImageButton maddgallerybtn;
TextView mmessagetext;
DatabaseReference mdatabaseLike;
DatabaseReference mdatabaseSave;
TextView midtext;
DatabaseReference mdatabasefollow;
DatabaseReference mdatabasefollowers;
FirebaseAuth mAuth;
TextView mrighttext;
TextView mcentertext;
TextView mlefttext;
TextView mheadinghere;
TextView mfollow;
TextView mdescription;
TextView mcategory;
TextView mlocation;
TextView mcameraused;
DatabaseReference mdatabase;
ScrollView mdetailscroll;
private static final int TIME_OUT = 100;
public ExploreViewHolder(View itemView) {
super(itemView);
mView = itemView;
mheadinghere = (TextView) mView.findViewById(R.id.headinghere);
mfollow = (TextView) mView.findViewById(R.id.follow);
mdescription = (TextView) mView.findViewById(R.id.deschere);
mcategory = (TextView) mView.findViewById(R.id.category);
mlocation = (TextView) mView.findViewById(R.id.location);
mcameraused = (TextView) mView.findViewById(R.id.cameraused);
mlikebtn = (ImageButton) mView.findViewById(R.id.likebtn);
maddgallerybtn = (ImageButton) mView.findViewById(R.id.addgallerybtn);
mmessagetext = (TextView) mView.findViewById(R.id.messagetext);
mdatabaseLike = FirebaseDatabase.getInstance().getReference().child("Like");
mdatabaseLike.keepSynced(true);
mdatabaseSave = FirebaseDatabase.getInstance().getReference().child("Saved");
mdatabaseSave.keepSynced(true);
midtext = (TextView) mView.findViewById(R.id.idtext);
mdatabasefollow = FirebaseDatabase.getInstance().getReference().child("Follow");
mdatabasefollow.keepSynced(true);
mdatabasefollowers = FirebaseDatabase.getInstance().getReference().child("Followers");
mdatabasefollowers.keepSynced(true);
mAuth = FirebaseAuth.getInstance();
mdatabase = FirebaseDatabase.getInstance().getReference().child("Explores");
mdetailscroll = (ScrollView) mView.findViewById(R.id.detailscroll);
}
public void setAddgallerybtn (final String post_key){
mdatabaseSave.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(mAuth.getCurrentUser().getUid()).hasChild(post_key)){
maddgallerybtn.setImageResource(R.mipmap.ic_assignment_turned_in);
}else {
maddgallerybtn.setImageResource(R.mipmap.ic_assignment_returned);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void setLikebtn (final String post_key){
mdatabaseLike.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())){
mlikebtn.setImageResource(R.mipmap.ic_favorite_red);
} else {
mlikebtn.setImageResource(R.mipmap.ic_favorite_border);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void setPostimage (final Context ctx, final String postimage){
final ImageView mpostimage = (ImageView) mView.findViewById(R.id.postimage);
Picasso.with(ctx).load(postimage).networkPolicy(NetworkPolicy.OFFLINE).into(mpostimage, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(ctx).load(postimage).into(mpostimage);
}
});
}
}
}
This is the Activity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="me.selftize.snapblink.ExploreActivity">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/explore_page"
android:layout_above="#+id/id_views">
</android.support.v7.widget.RecyclerView>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#000000"
android:id="#+id/id_views"
android:layout_above="#+id/bottomoption"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#ffffff"
android:orientation="horizontal"
android:id="#+id/bottomoption">
<ImageButton
android:id="#+id/homebtn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#android:color/transparent"
android:src="#mipmap/ic_home" />
<ImageButton
android:id="#+id/explorebtn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#android:color/transparent"
android:src="#mipmap/ic_explore" />
<ImageButton
android:id="#+id/camerabtn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#android:color/transparent"
android:src="#mipmap/ic_camera" />
<ImageButton
android:id="#+id/storebtn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#android:color/transparent"
android:src="#mipmap/ic_store" />
<ImageButton
android:id="#+id/profilebtn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#android:color/transparent"
android:src="#mipmap/ic_person" />
</LinearLayout>
</RelativeLayout>
If you want to know anything else apart than available information, please ask me and help me to achieve it.
try Overriding the following methods
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if(savedInstanceState != null) {
recyclerViewState = savedInstanceState.getParcelable("statekey");
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
recyclerViewState = mexplore_page.getLayoutManager().onSaveInstanceState();//save
outState.putParcelable("statekey", recyclerViewState);
}
and dont forget to declare
private Parcelable recyclerViewState;
and then add onResume like this
#Override
protected void onResume() {
super.onResume();
if (recyclerViewState != null) {
mexplore_page.getLayoutManager().onRestoreInstanceState(recyclerViewState);
}
}

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