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) {
}
});
}
Related
I am making an application in which products are inserted into the database and I am inserting the 1 product once. it is working fine. But when I delete a specific node/ product from Database. deletion code is also working fine but at the same time product is again adding into the database.
Main Fragment Code;
public class Products_fragment extends Fragment {
FloatingActionButton fab_addproduct;
RecyclerView recyclerView;
EditText searchview;
BottomSheetDialog bottomSheetDialog;
FirebaseDatabase firebaseDatabase;
ArrayList<Product_model> DatabaseProductlist;
FirebaseAuth auth;
CircularDotsLoader ProgressBar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_products_fragment, container, false);
setviews(view);
setInitilization();
setclicks();
setadapter();
return view;
}
private void setInitilization() {
DatabaseProductlist = new ArrayList<>();
}
private void setadapter() {
FirebaseDatabase database = FirebaseDatabase.getInstance();
FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
assert currentFirebaseUser != null;
String UID = currentFirebaseUser.getUid();
DatabaseReference reference = database.getReference("Users").child(UID).child("Products");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
ProgressBar.setVisibility(View.GONE);
DatabaseProductlist.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Product_model model = dataSnapshot.getValue(Product_model.class);
DatabaseProductlist.add(model);
}
Product_Adapter product_adapter = new Product_Adapter(DatabaseProductlist);
recyclerView.setAdapter(product_adapter);
product_adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
ToastUtility.showErrorToast(getContext(), error.getMessage());
}
});
}
private void setclicks() {
fab_addproduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bottomSheetDialog = new BottomSheetDialog(getContext(), R.style.AppBottomSheetDialogTheme);
bottomSheetDialog.setContentView(R.layout.productadd_bottom_sheet);
TextInputEditText product_id = bottomSheetDialog.findViewById(R.id.product_id);
TextInputEditText product_name = bottomSheetDialog.findViewById(R.id.product_name);
TextInputEditText product_quantity = bottomSheetDialog.findViewById(R.id.product_quantity);
MaterialButton add_btn = bottomSheetDialog.findViewById(R.id.add_btn);
TextInputEditText product_price = bottomSheetDialog.findViewById(R.id.product_price);
add_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Objects.requireNonNull(product_name.getText()).toString().isEmpty() || product_id.getText().toString().isEmpty() || product_price.getText().toString().isEmpty() || product_quantity.getText().toString().isEmpty()) {
ToastUtility.showErrorToast(getContext(), "Please Fill all Fields");
} else {
Product_model model = new Product_model(Integer.parseInt(product_id.getText().toString()), Integer.parseInt(product_quantity.getText().toString()), Integer.parseInt(product_price.getText().toString()), product_name.getText().toString());
firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference reference = firebaseDatabase.getReference("Users");
FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
assert currentFirebaseUser != null;
String UID = currentFirebaseUser.getUid();
reference.child(UID).child("Products").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.child(product_name.getText().toString().trim()).exists()) {
ToastUtility.showErrorToast(getContext(),"Product Already Exists!");
}
else{
reference.child(UID).child("Products").child(product_name.getText().toString().trim()).setValue(model).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
ToastUtility.showSuccessToast(getContext(),"Successfully Added");
setadapter();
}
else{
ToastUtility.showErrorToast(getContext(), Objects.requireNonNull(task.getException()).getMessage());
}
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
ToastUtility.showErrorToast(getContext(),error.getMessage());
}
});
}
}
});
bottomSheetDialog.show();
}
});
}
private void setviews(View view) {
recyclerView = view.findViewById(R.id.recyclerView);
fab_addproduct = view.findViewById(R.id.fab_addproduct);
searchview = view.findViewById(R.id.searchview);
ProgressBar = view.findViewById(R.id.progressbar);
}
}
Adapter Code:
public class Product_Adapter extends RecyclerView.Adapter<Product_Adapter.myviewholder> {
ArrayList<Product_model> dataholder;
public Product_Adapter(ArrayList<Product_model> dataholder) {
this.dataholder = dataholder;
}
#NonNull
#Override
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.singlerow_product, parent, false);
return new myviewholder(view); }
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull myviewholder holder, int position) {
holder.idtv.setText("" + dataholder.get(position).getId());
holder.pnametv.setText("" + dataholder.get(position).getProduct_name());
holder.pqtytv.setText("" + dataholder.get(position).getProduct_quantity());
holder.ppritv.setText("" + dataholder.get(position).getProduct_price());
holder.delimg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseDatabase db = FirebaseDatabase.getInstance();
FirebaseUser curUser = FirebaseAuth.getInstance().getCurrentUser();
assert curUser != null;
String UID = curUser.getUid();
String productname = dataholder.get(holder.getAdapterPosition()).getProduct_name();
DatabaseReference reference = db.getReference("Users").child(UID).child("Products");
reference.child(productname).setValue(null).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
ToastUtility.showSuccessToast(view.getContext(),"Suucessfully Deleted");
notifyItemRemoved(holder.getAdapterPosition());
}
else
{
ToastUtility.showErrorToast(view.getContext(),"Product is not deleting ");
}
}
});
}
});
}
#Override
public int getItemCount() {
return dataholder.size();
}
static class myviewholder extends RecyclerView.ViewHolder{
TextView idtv, pnametv, pqtytv, ppritv, delimg, edit_img;
public myviewholder(#NonNull View itemView) {
super(itemView);
idtv = itemView.findViewById(R.id.idtv);
pnametv = itemView.findViewById(R.id.pnametv);
pqtytv = itemView.findViewById(R.id.pqtytv);
ppritv = itemView.findViewById(R.id.ppritv);
delimg = itemView.findViewById(R.id.delimg);
edit_img = itemView.findViewById(R.id.edit_img);
}
}
}
When you click delete, shouldn't you remove your item from the list before notifying data changed:
//this code belongs to the part where you click the delete
.........
reference.child(productname).setValue(null).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
ToastUtility.showSuccessToast(view.getContext(),"Suucessfully Deleted");
//here remove the item from your list
dataholder.remove(holder.getAdapterPosition());
//then notify the adapter
notifyItemRemoved(holder.getAdapterPosition());
}
It is like social media app,This fragment should display the chat list, But it isn't, Here is the codes:
DirectMessagesFragment:
public class DirectMessagesFragment extends Fragment{
FirebaseAuth firebaseAuth;
FirebaseUser currentUser;
AdapterChatlist adapterChatlist;
DatabaseReference ref;
RecyclerView recyclerViewChatter;
List<ModelChatter> chatterList ;
List<ModelChatlist> chatlistList ;
public DirectMessagesFragment(){}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
setHasOptionsMenu(true);
View view = inflater.inflate(R.layout.fragment_direct_messages, container, false);
firebaseAuth = FirebaseAuth.getInstance();
currentUser = FirebaseAuth.getInstance().getCurrentUser();
recyclerViewChatter = view.findViewById(R.id.chatter_recyclerview);
chatlistList = new ArrayList<>();
ref = FirebaseDatabase.getInstance().getReference("Chatlist").child(currentUser.getUid());
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
chatlistList.clear();
for (DataSnapshot ds:snapshot.getChildren()){
ModelChatlist chatlist = ds.getValue(ModelChatlist.class);
chatlistList.add(chatlist);}
loadChats();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
});
return view;
}
private void loadChats() {
chatterList = new ArrayList<>();
ref = FirebaseDatabase.getInstance().getReference("Users");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
chatterList.clear();
for (DataSnapshot ds:snapshot.getChildren()){
ModelChatter chatter = ds.getValue(ModelChatter.class);
for(ModelChatlist chatlist: chatlistList){
if(chatter.getUid() != null && chatter.getUid().equals(chatlist.getId())){
chatterList.add(chatter);
break;
}}
adapterChatlist = new AdapterChatlist(getContext(), chatterList);
recyclerViewChatter.setAdapter(adapterChatlist);
}}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
});
}}
In ChatActivity:
//create chat list in firebase
DatabaseReference ref1 =
FirebaseDatabase.getInstance().getReference("ChatList")
.child(uid).child(hisUid);
ref1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(!snapshot.exists()){
ref1.child("id").setValue(hisUid);
}}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
});
DatabaseReference ref2 = FirebaseDatabase.getInstance().getReference("ChatList")
.child(hisUid).child(uid);
ref2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(!snapshot.exists()){
ref2.child("id").setValue(uid);
}}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
});}
#Override
public void afterTextChanged(Editable s) {
}
};
/////////
}
ModelChatlist only contain id.
ModelChatter contain name, image, uid.
AdapterChatlist:
public class AdapterChatlist extends RecyclerView.Adapter<AdapterChatlist.MyHolder>{
Context context;
List<ModelChatter> chattersList;
public AdapterChatlist(Context context, List<ModelChatter> chattersList) {
this.context = context;
this.chattersList = chattersList;
}
#NonNull
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.row_dm, parent, false);
return new MyHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyHolder holder, int position) {
String userImage = chattersList.get(position).getImage();
String userName = chattersList.get(position).getName();
String hisUid = chattersList.get(position).getUid();
holder.chatter_name.setText(userName);
try {
Picasso.with(context).load(userImage).placeholder(R.drawable.user).into(holder.chatter_img);
} catch (Exception e){
Picasso.with(context).load(R.drawable.user).into(holder.chatter_img);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ChatActivity.class);
intent.putExtra("hisUid", hisUid);
context.startActivity(intent);
}
});}
#Override
public int getItemCount() {
return chattersList.size();}
class MyHolder extends RecyclerView.ViewHolder{
ImageView chatter_img;
TextView chatter_name;
public MyHolder(#NonNull View itemView) {
super(itemView);
chatter_img = itemView.findViewById(R.id.chatter_img);
chatter_name = itemView.findViewById(R.id.chatter_name);
}}}}
fragment_direct_messages layout contain the recyclerview, row_dm contain the cardview
Any help will be appreciated..
Pass chat list into your method
for (DataSnapshot ds:snapshot.getChildren()){
ModelChatlist chatlist = ds.getValue(ModelChatlist.class);
chatlistList.add(chatlist);
}
loadChats(chatlistList);
private void loadChats(List<ModelChatlist> chatlist) {
//your code
}
Try adding filters (like logging the data received) to check where the actual problem persists. It's difficult to go through so much code.
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 am using RecyclerView to show data that is fetching from firebase Realtime Database. When I am opening recycler view activity it is showing nothing but when I go to previous activity come again then it is showing.
THIS IS THE ACTIVITY IN WHICH DATA HAS TO BE SHOWN-
public class BrakesItemActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private FloatingActionButton floatingActionButton;
private FirebaseDatabase database;
private DatabaseReference BrakestransactionDb, brakesDb;
private FirebaseRecyclerOptions<Transaction> options;
private FirebaseRecyclerAdapter<Transaction, TransactionViewHolder> adapter;
int sumofbrakescost = 0;
String sumofbrakescostvalue;
BottomAppBar bottomAppBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_last2);
bottomAppBar = findViewById(R.id.bottom_app_bar);
recyclerView = findViewById(R.id.recycler_view);
floatingActionButton = findViewById(R.id.floating_button);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
setSupportActionBar(bottomAppBar);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(BrakesItemActivity.this, BInputActivity.class);
startActivity(intent);
}
});
database = FirebaseDatabase.getInstance();
BrakestransactionDb = database.getReference().child("Brakes Items Transaction");
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(BrakesItemActivity.this));
BrakestransactionDb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Map<String, Object> map = (Map<String, Object>) ds.getValue();
Object totalcost = map.get("totalcoststring");
int totalcostvalue = Integer.parseInt(String.valueOf(totalcost));
sumofbrakescost += totalcostvalue;
sumofbrakescostvalue = String.valueOf(sumofbrakescost);
}
brakesDb = database.getReference().child("Department").child("Brakes").child("Cost");
brakesDb.setValue(sumofbrakescostvalue);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
showTask();
}
private void showTask() {
options = new FirebaseRecyclerOptions.Builder<Transaction>().setQuery(BrakestransactionDb, Transaction.class).build();
adapter = new FirebaseRecyclerAdapter<Transaction, TransactionViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull TransactionViewHolder holder, int position, #NonNull Transaction model) {
holder.item_name_card.setText(model.getNameofitemstring());
holder.bought_by_card.setText(model.getBoughtbystring());
holder.bought_from_card.setText(model.getBoughtfromstring());
holder.date_card.setText(model.getDatestring());
holder.time_card.setText(model.getTimestring());
holder.cost_of_one_item_card.setText(model.getCostofoneitemstring());
holder.number_of_items_card.setText(model.getNumberofitemstring());
holder.total_cost_card.setText(model.getTotalcoststring());
}
#NonNull
#Override
public TransactionViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.transaction_row, parent, false);
return new TransactionViewHolder(itemView);
}
};
recyclerView.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
#Override
public boolean onContextItemSelected(#NonNull MenuItem item) {
if (item.getTitle().equals("Delete")) {
deleteTransaction(adapter.getRef(item.getOrder()).getKey());
}
return super.onContextItemSelected(item);
}
private void deleteTransaction(String key) {
BrakestransactionDb.child(key).removeValue();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.bottommenu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.delete_all) {
BrakestransactionDb.removeValue();
}
if (item.getItemId() == R.id.home_button) {
Intent intent = new Intent(this, NavActivity.class);
finish();
startActivity(intent);
if (item.getItemId() == R.id.back_item_activity) {
Intent intent1 = new Intent(this, Department.class);
finish();
startActivity(intent1);
}
}
return super.onOptionsItemSelected(item);
}
}
THIS IS THE MODEL CLASS I MADE-
package com.example.android.zfr.Model;
public class Transaction {
private String nameofitemstring,boughtbystring,boughtfromstring,costofoneitemstring,datestring,
timestring,totalcoststring,numberofitemstring;
public String getNameofitemstring() { return nameofitemstring; }
public void setNameofitemstring(String nameofitemstring) { this.nameofitemstring = nameofitemstring; }
public String getBoughtbystring() {return boughtbystring; }
public void setBoughtbystring(String bought string) {
this.boughtbystring = boughtbystring;
}
public String getBoughtfromstring() { return boughtfromstring; }
public void setBoughtfromstring(String boughtfromstring) { this.boughtfromstring = boughtfromstring; }
public String getCostofoneitemstring() {
return costofoneitemstring;
}
public void setCostofoneitemstring(String costofoneitemstring) { this.costofoneitemstring = costofoneitemstring; }
public String getDatestring() { return datestring; }
public void setDatestring(String datestring) { this.datestring = datestring; }
public String getTimestring() { return timestring; }
public void setTimestring(String timestring) { this.timestring = timestring; }
public String getTotalcoststring() { return totalcoststring; }
public void setTotalcoststring(String totalcoststring) { this.totalcoststring = totalcoststring; }
public String getNumberofitemstring() { return numberofitemstring; }
public void setNumberofitemstring(String numberofitemstring) { this.numberofitemstring = numberofitemstring; }
public Transaction() { }
public Transaction(String nameofitemstring,String boughtbystring,String boughtfromstring,String costofoneitemstring, String timestring,
String datestring ,String totalcoststring , String numberofitemstring ){
this.nameofitemstring=nameofitemstring;
this.boughtbystring=boughtbystring;
this.boughtfromstring=boughtfromstring;
this.costofoneitemstring=costofoneitemstring;
this.datestring=datestring;
this.timestring=timestring;
this.numberofitemstring=numberofitemstring;
this.totalcoststring=totalcoststring;
}
}
THIS THE VIEWHOLDER CLASS-
package com.example.android.zfr.ViewHolder;
import android.view.ContextMenu;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.android.zfr.R;
import com.facebook.shimmer.ShimmerFrameLayout;
public class TransactionViewHolder extends RecyclerView.ViewHolder implements
View.OnCreateContextMenuListener{
public TextView item_name_card,bought_by_card,bought_from_card,date_card,
time_card,cost_of_one_item_card,number_of_items_card,total_cost_card;
public TransactionViewHolder(#NonNull View itemView) {
super(itemView);
item_name_card=itemView.findViewById(R.id.item_name_card);
bought_by_card=itemView.findViewById(R.id.bought_by_card);
bought_from_card=itemView.findViewById(R.id.bought_from_card);
date_card=itemView.findViewById(R.id.date_card);
time_card=itemView.findViewById(R.id.time_card);
cost_of_one_item_card=itemView.findViewById(R.id.cost_of_one_item_card);
number_of_items_card=itemView.findViewById(R.id.number_of_items_card);
total_cost_card=itemView.findViewById(R.id.total_cost_card);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{ menu.add(0,0,getAdapterPosition(),"Delete"); }
}
Please help.
you need to realize that Firebase is Asynchronous, meaning that your showTask() gets called even before your database is able to send you the data. To avoid this issue, you need to put your showTask() inside your addValueEventListener. Try this:
BrakestransactionDb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Map<String, Object> map = (Map<String, Object>) ds.getValue();
Object totalcost = map.get("totalcoststring");
int totalcostvalue = Integer.parseInt(String.valueOf(totalcost));
sumofbrakescost += totalcostvalue;
sumofbrakescostvalue = String.valueOf(sumofbrakescost);
}
brakesDb = database.getReference().child("Department").child("Brakes").child("Cost");
brakesDb.setValue(sumofbrakescostvalue);
showTask();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
It worked by putting
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(BrakesItemActivity.this));
in onDatachange method like this:
BrakestransactionDb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Map<String, Object> map = (Map<String, Object>) ds.getValue();
Object totalcost = map.get("totalcoststring");
int totalcostvalue = Integer.parseInt(String.valueOf(totalcost));
sumofbrakescost += totalcostvalue;
sumofbrakescostvalue = String.valueOf(sumofbrakescost);
}
brakesDb = database.getReference().child("Department").child("Brakes").child("Cost");
brakesDb.setValue(sumofbrakescostvalue);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(BrakesItemActivity.this));
}
I am doing work on the geofencing app as I have an activity named Location history logs where I want to retrieve each data node of date (20-Mar-2019) from location logs in a separate card view and (21-Mar-2019) from location logs in a separate card view and so on to the current date how can I do it?
here is a link of my firebase database:
Here is my Model class:
public class locationHistoryModel {
private String Address, Key;
private long Entered, Exited;
public locationHistoryModel() {
}
public locationHistoryModel(String address_child, String key, long entered) {
this.Address = address_child;
Key = key;
Entered = entered;
}
public String getAddress() {
return this.Address;
}
public void setAddress(String address) {
this.Address = address;
}
public String getKey() {
return Key;
}
public void setKey(String key) {
Key = key;
}
public long getEntered() {
return Entered;
}
public void setEntered(long entered) {
Entered = entered;
}
public long getExited() {
return Exited;
}
public void setExited(long exited) {
Exited = exited;
}
}
Here is my Adapter class:
public class LocationhistoryAdapter extends RecyclerView.Adapter<LocationhistoryAdapter.MyViewHolder>{
private Context mctx;
private ArrayList<locationHistoryModel> locationHistories;
public LocationhistoryAdapter(Context context, ArrayList<locationHistoryModel> locationHistoryArrayList )
{
mctx = context;
locationHistories = locationHistoryArrayList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
return new LocationhistoryAdapter.MyViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_location_historyadapter,viewGroup,false));
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.Addresstxt.setText(locationHistories.get(i).getAddress());
myViewHolder.EnterTimeTxt.setText(String.valueOf(locationHistories.get(i).getEntered()));
myViewHolder.location.setText(locationHistories.get(i).getKey());
}
#Override
public int getItemCount() {
return locationHistories.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder
{
TextView Addresstxt,EnterTimeTxt,location;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
Addresstxt = itemView.findViewById(R.id.Address_child);
EnterTimeTxt = itemView.findViewById(R.id.Entered_timestamp);
location = itemView.findViewById(R.id.Location_child);
}
}
}
Here is my MainActivity class:
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
ArrayList<locationHistoryModel> locationHistoryList;
DatabaseReference databaseReference;
DatabaseReference databaseReference1;
DatabaseReference databaseReference2;
DatabaseReference databaseReference3;
String date;
String location;
locationHistoryModel historyModel;
LocationhistoryAdapter locationAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.childsRecycler);
locationHistoryList = new ArrayList<>();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.scrollToPosition(0);
databaseReference = FirebaseDatabase.getInstance().getReference("Child");
databaseReference1 = databaseReference.child("+923452267601")
.child("03326325635")
.child("LocationLogs");
databaseReference1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
date = dataSnapshot1.getKey();
System.out.println(date + "dateee keeeeeyyyyy");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
databaseReference2 = databaseReference.child("+923452267601")
.child("03326325635")
.child("Locations");
databaseReference2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
location = dataSnapshot1.getKey();
System.out.println(location + "Location Key");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
System.out.println("03326325635");
databaseReference3 = databaseReference.child("+923452267601")
.child("03326325635")
.child("LocationLogs");
databaseReference3.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
historyModel = dataSnapshot.child(date).child(location).getValue(locationHistoryModel.class);
historyModel.setKey(location);
locationHistoryList.add(historyModel);
System.out.println(historyModel.getAddress() + "haha" + historyModel.getKey() + "" + historyModel.getEntered());
locationAdapter = new LocationhistoryAdapter(MainActivity.this, locationHistoryList);
recyclerView.setAdapter(locationAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}