I retrieved data from firebase database in recylerview. But I have in post node "postimg" has a another list item.
For this I use one more listener in onBindViewHolder. But this does not seem right to me.
So how to do all this works in mainactivity and pass in adapter?
Here is my code:
#Override
public void onBindViewHolder(#NonNull final PostHolder postHolder, final int i) {
postHolder.setData(mPost.get(i));
final String PostKey=mPost.get(i).getPostid();
FirebaseAuth mAuth=FirebaseAuth.getInstance();
final String currentUserID=mAuth.getCurrentUser().getUid();
final DatabaseReference post=FirebaseDatabase.getInstance().getReference().child("Posts");
post.child(PostKey).child("postimg").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
if (dataSnapshot.exists())
{
for (DataSnapshot dataSnapshot1:dataSnapshot.getChildren())
{
String postimagelink =dataSnapshot1.getValue().toString();
postimagelist.add(postimagelink);
}
String[] urls =postimagelist.toArray(new String[postimagelist.size()]);
postHolder.mPager.setAdapter(new SlidingImage_Adapter(mContext,urls));
postHolder.indicator.setViewPager(postHolder.mPager);
final float density = mContext.getResources().getDisplayMetrics().density;
postHolder.indicator.setRadius(5 * density);
postHolder.NUM_PAGES = urls.length;
postHolder.indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
#Override
public void onPageSelected(int position) {
postHolder.currentPage = position;
}
#Override
public void onPageScrolled(int pos, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int pos) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
this my query in MainActivity.
mAdapter = new PostAdapter(MainActivity.this);
query = PostRef
.orderByChild("timestamp")
.limitToLast(mPostsPerPage);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<Post> userModels = new ArrayList<>();
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
String o=userSnapshot.getKey();
userModels.add(userSnapshot.getValue(Post.class));
//Here I want to retrieve no of "postimg"child and its value and pass in adapter//
}
mAdapter.addAll(userModels);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Related
I have an algorithm looking for Firebase data but it doesn't work and records an error to me, I want to register into Edittext Value and it will bring me the appropriate card
I use the recylerView
recyclerView= findViewById(R.id.recycleview);
getmRootFLY = FirebaseDatabase.getInstance().getReference("FLY");
list = new ArrayList<>();
arrayList = new ArrayList<>();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
myAdapter = new MyAdapter(this,list);
recyclerView.setAdapter(myAdapter);
getmRootFLY.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot: snapshot.getChildren())
{
Fly fly = dataSnapshot.getValue(Fly.class);
list.add(fly);
}
myAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
databaseReference = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
mRootRef = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid()).child("First Name");
mRootRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String name = dataSnapshot.getValue().toString();
TextView myLoginTextFromDB = (TextView)findViewById(R.id.hello_name_from_db);
myLoginTextFromDB.setText(name);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
EditText editTextTextPersonName = (EditText) findViewById(R.id.editTextTextPersonName);
editTextTextPersonName.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
Query query = databaseReference.child("FLY").equalTo(editable.toString());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
{
list.clear();
for (DataSnapshot dss: snapshot.getChildren())
{
final Fly fly = dss.getValue(Fly.class);
list.add(fly);
}
MyAdapter myAdapter1 = new MyAdapter(getApplicationContext(),list);
recyclerView.setAdapter(myAdapter1);
myAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
}
It is important to note Getmrootfly adds the card to the array and basically shows me the data available in Firebase
And all code that appears as an edittexttexteonname is a code that needs to look for the data
I'm currently making a booking app for some football fields. I have two recycler views: active bookings and cancelled bookings. I also have a custom recycler view adapter. Both of the recycler views use the same adapter.
What I want to do: if I click on a button inside my active bookings recycler view, I want to remove the booking from the active bookings and put it into my cancelled bookings. I'm gonna leave my custom adapter with the mention that I use Firebase in order to get my booking status (active or cancelled).
public class RecyclerViewAdapterRezervare extends RecyclerView.Adapter<RecyclerViewAdapterRezervare.RecycleViewHolder> {
private List<Rezervare> rezervari;
private Context context;
private LayoutInflater inflater;
private String numeUtilizator;
private String status;
private Rezervare rezervare = new Rezervare();
private DatabaseReference reff;
public RecyclerViewAdapterRezervare(List<Rezervare> rezervari, Context context, String numeUtilizator) {
this.rezervari = rezervari;
this.context = context;
this.numeUtilizator = numeUtilizator;
this.inflater = LayoutInflater.from(context);
}
#NonNull
#Override
public RecycleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.rezervari_layout, parent, false);
return new RecycleViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecycleViewHolder holder, int position) {
rezervare = rezervari.get(position);
reff = FirebaseDatabase.getInstance().getReference();
List<String> listaOre = rezervare.getOre();
Map<String, Object> mapOre = new HashMap<>();
for(String ora : listaOre){
mapOre.put(ora, false);
}
// this will return the status ("activa" is the booking is active, or "anulata" is it's cancelled)
getStatus(rezervare, new StatusCallback() {
#Override
public void onCallback(String value) {
status = value;
holder.btn_anuleaza.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v("status", status);
new AlertDialog.Builder(view.getContext()).setTitle("Anulare rezervare").setMessage("Sunteti sigur ca doriti anularea rezervarii?")
.setPositiveButton(R.string.da, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// if the cancel button is clicked, i update my database so the status of the booking will be "anulata" - cancelled reff.child("Users").child(numeUtilizator).child("rezervari").child(rezervare.getData()).child(rezervare.getNumeTeren()).child("status").setValue("anulata");
reff.child("Rezervari").child(rezervare.getData()).child("Fotbal").child(rezervare.getNumeTeren()).updateChildren(mapOre);
rezervare.setEsteAnulata(false);
Toast.makeText(view.getContext(), "Anulare cu succes!", Toast.LENGTH_LONG).show();
}
}).setNegativeButton(R.string.nu, null).show();
}
});
}
});
}
#Override
public int getItemCount() {
return rezervari.size();
}
// i have updated my code with the delete and insert a booking
public void stergeRezervare(int position){
rezervari.remove(position);
notifyDataSetChanged();
}
public void adaugaRezervare(Rezervare rezervare){
rezervari.add(rezervare);
notifyDataSetChanged();
}
This is the function that gets me the bookings from firebase
i have 3 separate lists for active bookings, cancelled and past bookings.
public interface RezervariListCallback {
void onCallback(List<Rezervare> rezervariActuale, List<Rezervare> rezervariTrecute, List<Rezervare> rezervariAnulate);
}
public void getRezervari(String nume, RezervariListCallback myCallback){
reff.child("Users").child(nume).child("rezervari").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot data : snapshot.getChildren()){
String dataRezervare = data.getKey();
dateRezervari.add(dataRezervare);
reff.child("Users").child(nume).child("rezervari").child(dataRezervare).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot data : snapshot.getChildren()){
String numeTeren = data.getKey();
reff.child("Users").child(nume).child("rezervari").child(dataRezervare).child(numeTeren).child("ore").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
List<String> ore = new ArrayList<>();
for(DataSnapshot data : snapshot.getChildren()){
String ora = data.getKey();
ore.add(ora);
}
getAdresa(nume, dataRezervare, numeTeren, new AdresaCallback() {
#Override
public void onCallbackAdresa(String value) {
Rezervare rezervare = new Rezervare(numeTeren, ore, dataRezervare, value);
String dataAzi = getDataAzi();
reff.child("Users").child(nume).child("rezervari").child(dataRezervare).child(numeTeren).child("status").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String status = (String) snapshot.getValue();
if(comparaData(dataAzi, rezervare.getData())){
if(status.equals("activa")){
rezervariActive.add(rezervare);
} else {
rezervariAnulate.add(rezervare);
}
} else {
rezervariTrecute.add(rezervare);
}
myCallback.onCallback(rezervariActive, rezervariTrecute, rezervariAnulate);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
and this is where i set the adapters
public void updateRezervari(View view, RecyclerView activeBookingsRecycler, RecyclerView pastBookingsRecycler, RecyclerView cancelledBookingsRecycler){
AsyncTask.execute(new Runnable() {
#Override
public void run() {
getRezervari(numeUtilizator, new RezervariListCallback() {
#Override
public void onCallback(List<Rezervare> rezervariActuale, List<Rezervare> rezervariTrecute, List<Rezervare> rezervariAnulate) {
if(rezervariActuale.size()>0){
tvFaraRezervariActive.setEnabled(false);
tvFaraRezervariAnulate.setEnabled(false);
tvFaraRezervariTrecute.setEnabled(false);
}
Log.v("rezAc", rezervariActuale.toString());
Log.v("rezTr", rezervariTrecute.toString());
RecyclerViewAdapterRezervare adapter = new RecyclerViewAdapterRezervare(rezervariActuale, view.getContext(), numeUtilizator);
activeBookingsRecycler.setAdapter(adapter);
adapter = new RecyclerViewAdapterRezervare(rezervariTrecute, view.getContext(), numeUtilizator);
pastBookingsRecycler.setAdapter(adapter);
adapter = new RecyclerViewAdapterRezervare(rezervariAnulate, view.getContext(), numeUtilizator);
cancelledBookingsRecycler.setAdapter(adapter);
}
});
}
});
}
Can you give me a few tips on how to move from one recycler view to another? Thank you!
Since you are using Firebase to fetch status of a booking, you can update the status to cancelled in your firebase database and then you will get a callback from your firebase listener where you can update your arraylists and call notifyDataSetChanged().
I want to add onScroll Listener, but recyclerview's addonScrollListner() method is not doing anything, I want to fetch next ten items on every recyclerview's scroll.
At first time the data is fetching fine, but when i am scrolling recyclerview then nothing is happening, i am not able to find out why is this happening.
It is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = findViewById(R.id.adView_con);
progressBar = findViewById(R.id.contentprogressbar);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
recyclerView = findViewById(R.id.listview);
mSwipeRefreshLayout = findViewById(R.id.swipeContainer);
textView = findViewById(R.id.emptylist);
backbtncontent = findViewById(R.id.backbtncntent);
backbtncontent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ContentActivity.this, HomeActivity.class);
startActivity(i);
}
});
classname = getIntent().getStringExtra("classname");
if (classname.equals("A")) {
content = getIntent().getStringExtra("jokecontent");
} else if (classname.equals("B")) {
content = getIntent().getStringExtra("shayaricontent");
}
getLastKeyFromFirebase();
final LinearLayoutManager layoutManager= new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), layoutManager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);
arrayAdapter = new NewAdapterContent(contentname,this);
recyclerView.setAdapter(arrayAdapter);
getUsers();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
total_item = layoutManager.getItemCount();
last_visible_item = layoutManager.findLastCompletelyVisibleItemPosition();
if(!isLoading && total_item<=((last_visible_item+ITEM_LOAD_COUNT))){
getUsers();
isLoading = true;
}
}
});
}
private void getUsers()
{
if (!isMaxData) {
Query query;
if (classname.equals("A")) {
if (TextUtils.isEmpty(last_nodes)) //wait content to aa n raehre
query = FirebaseDatabase.getInstance().getReference("ContentJokes")
.orderByChild("subcategory")
.equalTo(content)
.limitToFirst(ITEM_LOAD_COUNT);
else
query = FirebaseDatabase.getInstance().getReference("ContentJokes")
.orderByChild("subcategory")
//.equalTo(content)
.startAt(last_nodes)
.limitToFirst(ITEM_LOAD_COUNT);
//1 sec wait cll ari kisi ki
query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if (!dataSnapshot.exists()) {
//hello ?
isLoading = false;
isMaxData = true;
// progressBar.setVisibility(View.GONE);
Toast.makeText(ContentActivity.this, "There is no jokes present under this category", Toast.LENGTH_SHORT).show();
} else {
String contentdisplay = dataSnapshot.child("content").getValue(String.class);
String key = dataSnapshot.child("content").getKey();
ContentModel contentModel = new ContentModel(contentdisplay, key);
contentname.add(0, contentModel);
arrayAdapter.notifyDataSetChanged();
progressBar.setVisibility(View.GONE);
arrayAdapter.notifyItemInserted(0);
last_nodes = contentname.get(contentname.size() - 1).getId();
if (!last_nodes.equals(last_key)) {
} else
last_nodes = last_key;
isLoading = false;
}
}
#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) {
}
});
} else if(classname.equals("B")){
if (TextUtils.isEmpty(last_nodes)) //wait content to aa n raehre
query = FirebaseDatabase.getInstance().getReference("ContentShayari")
.orderByChild("subcategory")
.equalTo(content)
.limitToFirst(ITEM_LOAD_COUNT);
else
query = FirebaseDatabase.getInstance().getReference("ContentShayari")
.orderByChild("subcategory")
.equalTo(content)
.startAt(last_nodes)
.limitToFirst(ITEM_LOAD_COUNT);
query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if (!dataSnapshot.exists()) {
isLoading = false;
isMaxData = true;
// progressBar.setVisibility(View.GONE);
Toast.makeText(ContentActivity.this, "There is no jokes present under this category", Toast.LENGTH_SHORT).show();
} else {
String contentdisplay = dataSnapshot.child("content").getValue(String.class);
String key = dataSnapshot.child("content").getKey();
ContentModel contentModel = new ContentModel(contentdisplay, key);
contentname.add(0, contentModel);
arrayAdapter.notifyDataSetChanged();
// progressBar.setVisibility(View.GONE);
arrayAdapter.notifyItemInserted(0);
last_nodes = contentname.get(contentname.size() - 1).getId();
if (!last_nodes.equals(last_key)) {
} else
last_nodes = last_key;
isLoading = false;
}
}
#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 getLastKeyFromFirebase() {
Query getLastKey;
if (classname.equals("A")) {
getLastKey = FirebaseDatabase.getInstance().getReference()
.child("ContentJokes")
.orderByChild("subcategory").equalTo(content)
.limitToLast(1);
getLastKey.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot lastKey : dataSnapshot.getChildren()) {
last_key = lastKey.getKey();
Toast.makeText(ContentActivity.this, String.valueOf(last_key), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(ContentActivity.this, "cannot get last key", Toast.LENGTH_SHORT).show();
}
});
} else if (classname.equals("B")) {
getLastKey = FirebaseDatabase.getInstance().getReference()
.child("ContentShayari")
.orderByChild("subcategory").equalTo(content)
.limitToLast(1);
getLastKey.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot lastKey : dataSnapshot.getChildren()) {
last_key = lastKey.getKey();
Toast.makeText(ContentActivity.this, String.valueOf(last_key), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(ContentActivity.this, "cannot get last key", Toast.LENGTH_SHORT).show();
}
});
}
}
RecyclerAdapter Code:
public class NewAdapterContent extends RecyclerView.Adapter<NewAdapterContent.ViewHolder> {
ArrayList<ContentModel>contentModels;
Context context;
public NewAdapterContent(ArrayList<ContentModel>contentModels, Context context) {
this.contentModels = contentModels;
this.context = context;
}
public void addAll(ArrayList<ContentModel>contentModels){
int initSize = contentModels.size();
contentModels.addAll(contentModels);
notifyItemRangeChanged(initSize, contentModels.size());
}
public String getLastItemId(){
return contentModels.get(contentModels.size()-1).getId();
}
#NonNull
#Override
public NewAdapterContent.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull NewAdapterContent.ViewHolder holder, int position) {
holder.textView.setText(contentModels.get(position).getContent());
}
#Override
public int getItemCount() {
return contentModels.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView textView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.contentText);
}
}
}
Anytime of help would be appreciated. Please help.
Try it which is very easy to use that was worked for me by using the custom RecyclerView.OnScrollListener named EndlessRecyclerViewScrollListener -
EndlessRecyclerViewScrollListener scrollListener = new
EndlessRecyclerViewScrollListener(layoutManager) {
#Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
if(!isLoading){
getUsers();
isLoading = true;
}
}
};
recyclerView.addOnScrollListener(scrollListener);
I want the items to appear only when the user starts typing something on the EditText
Here's my Adapter:
#NonNull
#Override
public UserAdapter.ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.user_item, parent, false);
return new UserAdapter.ImageViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final UserAdapter.ImageViewHolder holder, final int position) {
...
}
Here's the Search Fragment:
userList = new ArrayList<>();
userAdapter = new UserSearchMessageAdapter(getContext(), userList, true);
recyclerView.setAdapter(userAdapter);
readUsers();
search_bar.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
searchUsers(charSequence.toString().toLowerCase());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
return view;
}
private void searchUsers(String s){
Query query = FirebaseDatabase.getInstance().getReference("Users").orderByChild("username")
.startAt(s)
.endAt(s+"\uf8ff");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
userList.add(user);
}
userAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void readUsers() {
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (search_bar.getText().toString().equals("")) {
userList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
userList.add(user);
}
userAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
EDIT
You can hide the recyclerview when the user hasnt typed anything in the edittext
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if(charSeqeunce.equals(""))recyclerView.setVisibility(View.GONE);
else {searchUsers(charSequence.toString().toLowerCase());
recyclerView.setVisibility(View.VISIBLE);
}
}
and you can just show an empty state image instead.
When the user types something in the edittext then you can show them the recyclerview back and hide the empty state image!
Hope this helps!
I made a button, which when clicked changes values on the database,
the status/color of the button is based on the value on the database.
How to prevent all drawables from getting refreshed on recyclerview just because one drawable had its value changed?
Result i get:
https://media.giphy.com/media/frHERBcrLUA8x14bsh/giphy.gif
public MainAdapter(Context mContext, List<Posts> mPost)
{
Log.d(TAG, "Main Adapter Start");
this.mContext = mContext;
this.mPost = mPost;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(mContext).inflate(R.layout.all_posts_layout, viewGroup, false);
return new MainAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
final Posts post = mPost.get(position);
final String Postkey = post.getPost_uid();
final String likes = Integer.toString(post.getLikes());
holder.setUpStatus(Postkey);
LikesRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
holder.LikepostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
LikeChecker = true;
LikesRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if (LikeChecker.equals(true))
{
if (dataSnapshot.child(Postkey).hasChild(currentUserID)) {
LikesRef.child(Postkey).child(currentUserID).removeValue();
PostsRef.child(Postkey).child("likes").setValue(post.getLikes()-1);
LikeChecker = false;
} else {
LikesRef.child(Postkey).child(currentUserID).setValue(true);
DisikesRef.child(Postkey).child(currentUserID).removeValue();
StoreToHistory(Postkey);
DisikesRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(currentUserID).exists())
{
PostsRef.child(Postkey).child("likes").setValue(post.getLikes()+2);
}
else {
PostsRef.child(Postkey).child("likes").setValue(post.getLikes()+1);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
LikeChecker = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}});
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
}
#Override
public int getItemCount()
{
return mPost.size();
}
ViewHolder:
public class ViewHolder extends RecyclerView.ViewHolder {
View mView;
ImageButton LikepostButton, DislikepostButton;
int countLikes, countDislikes, countComms;
public ViewHolder(View itemView) {
super(itemView);
mView = itemView;
currentUserId = FirebaseAuth.getInstance().getCurrentUser().getUid();
LikepostButton = itemView.findViewById(R.id.like_button);
DislikepostButton = itemView.findViewById(R.id.dislike);
CommentPostButton = itemView.findViewById(R.id.comment_button);
DisplayNoOfLikes = itemView.findViewById(R.id.display_number_of_likes);
DisplayNoOfDislikes = itemView.findViewById(R.id.display_number_of_dislikes);
}
public void setUpStatus(final String PostKey)
{
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Ups");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(PostKey).hasChild(currentUserID))
{
LikepostButton.setImageResource(R.drawable.upvote);
DisplayNoOfLikes.setTextColor(Color.parseColor("#f14c00"));
}
else
{
LikepostButton.setImageResource(R.drawable.upvote_novote);
}
DisikesRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(PostKey).hasChild(currentUserID))
{
DislikepostButton.setImageResource(R.drawable.downvote_orange);
DisplayNoOfLikes.setTextColor(Color.parseColor("#df3168a7"));
}
else {
DislikepostButton.setImageResource(R.drawable.downvote_novote);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
}); }
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}