as I was coding through making an activity log for lock and unlock times, I came across a very unusual problem that I can't fix. The activity log is displayed fine, however the default linear layout is also displayed. I don't understand why. Anyone feel free to help
This is my ActivityLog activity
package com.smartLock.sujitha.boltSmartLock;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.smartLock.sujitha.boltSmartLock.Pack.ListItem;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class ActivityLog extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<ListItem> listItems;
SwipeRefreshLayout swipe;
DatabaseReference database;
LinearLayout lLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recycle);
recyclerView.setHasFixedSize(true);
// SharedPreferences preferences=getSharedPreferences(LOCK_PREFS,MODE_PRIVATE);
database = FirebaseDatabase.getInstance().getReference("Activity Log/device321");
swipe = findViewById(R.id.swiper);
listItems = new ArrayList<>();
database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot usersnapshot : dataSnapshot.getChildren()) {
Map<String, String> map = (Map<String, String>) usersnapshot.getValue();
for (Map.Entry<String, String> entry : map.entrySet()) {
listItems.add(new ListItem(entry.getKey(), entry.getValue(),usersnapshot.child("Time").getValue().toString()
));
}
}
recyclerView.setAdapter(new MyAdapter(getApplicationContext(),listItems));
adapter = new MyAdapter(listItems, ActivityLog.this);
recyclerView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot usersnapshot : dataSnapshot.getChildren()) {
Map<String, String> map = (Map<String, String>) usersnapshot.getValue();
for (Map.Entry<String, String> entry : map.entrySet()) {
listItems.add(new ListItem(entry.getKey(), entry.getValue(),usersnapshot.child("Time").getValue().toString()
));
}
}
recyclerView.setAdapter(new MyAdapter(getApplicationContext(),listItems));
adapter = new MyAdapter(listItems, ActivityLog.this);
recyclerView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
swipe.setRefreshing(false);
}
},2000);
listItems.clear();
}
});
}
}
This is my adapter
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{
private List<ListItem> listItems;
private Context context;
public MyAdapter(List<ListItem> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}
public MyAdapter(Context applicationContext, List<ListItem> listItems) {
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
ListItem listItem = listItems.get(position);
String key = listItem.getHead();
if(key.equals("LockTime"))
{
holder.textViewHead.setText(listItem.getTime());
holder.textViewDesc.setText(listItem.getDesc());
holder.layout.setBackground(ContextCompat.getDrawable(context, R.drawable.red_gradient));
holder.image1.setImageResource(R.drawable.lockwhite);
holder.image2.setImageResource(R.drawable.lockwhite);
}
else if(key.equals("UnlockTime")){
holder.textViewHead.setText(listItem.getTime());
holder.textViewDesc.setText(listItem.getDesc());
holder.layout.setBackground(ContextCompat.getDrawable(context, R.drawable.green_gradient));
holder.image1.setImageResource(R.drawable.unlockwhite);
holder.image2.setImageResource(R.drawable.unlockwhite);
}
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView textViewHead;
public TextView textViewDesc;
public RelativeLayout layout;
public ImageView image1;
public ImageView image2;
public ViewHolder(View itemView) {
super(itemView);
textViewHead = (TextView) itemView.findViewById(R.id.textViewHead);
textViewDesc = (TextView) itemView.findViewById(R.id.textViewDesc);
layout= (RelativeLayout) itemView.findViewById(R.id.relativelayout);
image1 = itemView.findViewById(R.id.padlock1);
image2 = itemView.findViewById(R.id.padlock2);
}
}
}
Any help would be greatly appreciated!
This is my default linear layout
Here is a screenshot that appears on my phone
Related
Cart Activity(Here I want to show this hashmap data in Recycler View...Any Help will be Highly Appreciated)
package com.example.silkenscoops;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Pair;
import java.util.HashMap;
public class CartActivity extends AppCompatActivity {
private HashMap<String, Pair<String,String>> cartMap=new HashMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cart_view);
cartMap= (HashMap<String, Pair<String, String>>) getIntent().getSerializableExtra("h");
}
}
My Adapter class
package com.example.silkenscoops;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import java.util.HashMap;
public class MainAdapter extends FirebaseRecyclerAdapter<Items, MainAdapter.myViewHolder> {
private HashMap<String, Pair<String,String>> cartMap=new HashMap<>();
public MainAdapter(#NonNull FirebaseRecyclerOptions<Items> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull myViewHolder holder, int position, #NonNull Items model) {
holder.Price.setText(model.getPrice());
holder.Product.setText(model.getProduct());
holder.Stock.setText(model.getStock());
holder.increment.setVisibility(View.GONE);
holder.decrement.setVisibility(View.GONE);
holder.add.setOnClickListener(new View.OnClickListener() {
int count=0;
#Override
public void onClick(View v) {
holder.increment.setVisibility(View.VISIBLE);
holder.decrement.setVisibility(View.VISIBLE);
if(count<Integer.parseInt(model.getStock())) {
count++;
holder.add.setText(String.valueOf(count));
cartMap.put(model.getProduct(),new Pair<String,String>(String.valueOf(count),model.getPrice()));
}
holder.decrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(count>0) {
count--;
holder.add.setText(String.valueOf(count));
cartMap.put(model.getProduct(),new Pair<String,String>(String.valueOf(count),model.getPrice()));
}
if(count<=0){
holder.add.setText("ADD");
holder.increment.setVisibility(View.GONE);
holder.decrement.setVisibility(View.GONE);
cartMap.remove(model.getProduct());
}
}
});
}
});
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.display,parent,false);
return new MainAdapter.myViewHolder(view);
}
class myViewHolder extends RecyclerView.ViewHolder{
TextView Product, Price, Stock,add;
ImageView decrement,increment;
public myViewHolder(#NonNull View itemView) {
super(itemView);
Price=itemView.findViewById(R.id.Price);
Product=itemView.findViewById(R.id.Product);
Stock=itemView.findViewById(R.id.Stock);
add=itemView.findViewById(R.id.add);
increment=itemView.findViewById(R.id.increment);
decrement=itemView.findViewById(R.id.decrement);
}
}
public HashMap<String, Pair<String, String>> getCartMap() {
return cartMap;
}
}
My MainActivity(Actually it is the menu list..)
package com.example.silkenscoops;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.util.Pair;
import android.view.View;
import android.widget.ImageView;;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import java.util.HashMap;
public class MainItems extends AppCompatActivity {
private RecyclerView recyclerView;
private ImageView cart_btn;
MainAdapter adapter;
DatabaseReference databasereference;
private HashMap<String, Pair<String,String>> cartMap=new HashMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_display);
getSupportActionBar().hide();
cart_btn=findViewById(R.id.cart_btn);
databasereference = FirebaseDatabase.getInstance().getReference();
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//This is the right Query that should be passed to the setQuery() method
//The fields should stay as in the Items class (I capital)
Query query = FirebaseDatabase.getInstance().getReference().child("Cups");
FirebaseRecyclerOptions<Items> options = new FirebaseRecyclerOptions.Builder<Items>()
.setQuery(query, Items.class)
.build();
adapter = new MainAdapter(options);
recyclerView.setAdapter(adapter);
cart_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cartMap=adapter.getCartMap();
Intent intent = new Intent(MainItems.this, CartActivity.class);
intent.putExtra("list", cartMap);
startActivity(intent);
}
});
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
There is no error , but how am I supposed to pass my hashmap from ActivityMain to Cart Activity and show it in recycler View...I have no idea now and after working and thinking for 10-15 days I'm asking here..Please help me..
Thanks
I want to get an int value from my adapter class to my activity but I am getting nothing while using this code:
Here is my adapter:
package com.capi.ccecommerceapp.Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.capi.ccecommerceapp.Model.Cart;
import com.capi.ccecommerceapp.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.List;
public class CartAdapter extends RecyclerView.Adapter<CartAdapter.ViewHolder>
{
private Context context;
private List<Cart> cartList;
private String productImage;
public int overTotalPrice = 0;
public CartAdapter(Context context, List<Cart> cartList ) {
this.context = context;
this.cartList = cartList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.cart_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
holder.cartName.setText(cartList.get(position).getProductName());
holder.cartPrice.setText(cartList.get(position).getProductPrice());
holder.cart_qty.setText(String.valueOf(cartList.get(position).getProductQuantity()));
int oneTypeProductTPrice = ((Integer.parseInt(cartList.get(position).getProductPrice()))) * cartList.get(position).getProductQuantity();
overTotalPrice = overTotalPrice + oneTypeProductTPrice;
/*FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();*/
/* holder.cartPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (cartQty<10)
{
cartQty++;
}
}
});
holder.cartMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (cartQty>1)
{
cartQty--;
}
}
});
holder.cart_qty.setText(cartQty);
holder.deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
cartList.remove(cartList.get(position));
}
});*/
/* holder.wishlistBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.wishlistBtn.getTag().equals("add"))
{
holder.wishlistBtn.setImageResource(R.drawable.ic_love_fill);
holder.wishlistBtn.setTag("added");
}
else
{
holder.wishlistBtn.setImageResource(R.drawable.love);
holder.wishlistBtn.setTag("add");
}
}
});*/
DatabaseReference reference = FirebaseDatabase.getInstance().getReference()
.child("Products")
.child(cartList.get(position).getProductId())
.child("productImage");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot)
{
if (snapshot.exists()) {
productImage = snapshot.getValue(String.class);
Glide.with(context).load(productImage).into(holder.cartImage);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public int getItemCount() {
return cartList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
ImageView cartImage;
TextView cartName;
TextView cartPrice;
ImageView wishlistBtn;
ImageView deleteBtn;
ImageView cartPlus;
ImageView cartMinus;
TextView cart_qty;
public ViewHolder(#NonNull View itemView) {
super(itemView);
cartImage = itemView.findViewById(R.id.cart_image);
cartName = itemView.findViewById(R.id.cart_name);
cartPrice = itemView.findViewById(R.id.cart_price);
wishlistBtn = itemView.findViewById(R.id.add_to_wishlist);
deleteBtn = itemView.findViewById(R.id.delete_cart);
cartPlus = itemView.findViewById(R.id.cart_add);
cartMinus = itemView.findViewById(R.id.cart_minus);
cart_qty = itemView.findViewById(R.id.cart_quantity);
}
}
}
and here is my activity code where I want to set it in textView:
package com.capi.ccecommerceapp.Fragment;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.capi.ccecommerceapp.Adapter.CartAdapter;
import com.capi.ccecommerceapp.address.ShiptoActivity;
import com.capi.ccecommerceapp.Model.Cart;
import com.capi.ccecommerceapp.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class CartFragment extends Fragment
{
private RecyclerView cartRecyclerView;
private List<Cart> cartList;
private CartAdapter cartAdapter;
private Button next;
private FirebaseAuth auth;
private FirebaseUser user;
private TextView subtotal;
private TextView items;
private TextView shipping;
private TextView totalPrice;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_cart, container, false);
cartRecyclerView = view.findViewById(R.id.cartRecycler);
next = view.findViewById(R.id.checkout_btn);
auth = FirebaseAuth.getInstance();
user = auth.getCurrentUser();
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getContext(), ShiptoActivity.class));
}
});
subtotal = view.findViewById(R.id.subtotal_price);
items = view.findViewById(R.id.items);
shipping = view.findViewById(R.id.shipping_price);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
cartRecyclerView.setLayoutManager(layoutManager);
cartList = new ArrayList<>();
cartAdapter = new CartAdapter(getContext(), cartList);
cartRecyclerView.setAdapter(cartAdapter);
loadCart();
return view;
}
private void loadCart()
{
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Cart")
.child(user.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren())
{
Cart cart = dataSnapshot.getValue(Cart.class);
cartList.add(cart);
}
cartAdapter.notifyDataSetChanged();
subtotal.setText("$" + cartAdapter.overTotalPrice);
items.setText("Items("+cartAdapter.getItemCount()+")");
int shippingPrice = (cartAdapter.overTotalPrice / 20);
shipping.setText("$" + shippingPrice);
/*int totalPriceFinal = shippingPrice + cartAdapter.getOverTotalPrice();
totalPrice.setText("$" + totalPriceFinal);*/
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
I want to get this int:public int overTotalPrice = 0;
And I am getting it as:subtotal.setText("$"+cartAdapter.overTotalPrice);
Anyone have a solution?
???????????????????????
????????????????????
??????????????????????
So, I'm not sure about the title of this question but here it goes. I have a recyclerview for my chat room. The first time the activity started it has no problem displaying the messages but after pressing the back button back to the main activity showing all chat rooms then click the same chat room again it displays nothing. Then, after sent a message it can display all the messages again. I'm not sure what happened, help, please. Oh, I already tried a few things and browse the internet but because I'm not sure what the keyword is, so I'm quite stuck now
Okay, here is the thing
First main activity, (ignore the other 2 tabs, it's empty)
Main Activity
Then open a chat room
First time open chat room fine
Then press back button, back to MainActivity, then open the same room and no chat displayed
chat room not displaying anything
Then it displays messages again after sending a new messages
new message
I have tried to place notifyDataSetChanged() on various event like onStart, onCreate etc but nothing works;
here is my chat activity
package com.divistant.chat.ui.chat;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.divistant.chat.R;
import com.divistant.signup.UserModel;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class ChatActivity extends AppCompatActivity {
LinearLayout layout;
ImageView send;
EditText message;
ScrollView scrollView;
DatabaseReference refrence1;
DatabaseReference refrence2;
RecyclerView rv;
List<ChatModel> chats = new ArrayList<>();
ChatActivityAdapter adapter;
FirebaseUser cUser;
UserModel target;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Log.w("EVENT","ON Create");
Intent intent = getIntent();
target = (new Gson()).fromJson(intent.getStringExtra("target"),UserModel.class);
send = (ImageView)findViewById(R.id.sendButton);
message = (EditText)findViewById(R.id.messageArea);
scrollView = (ScrollView)findViewById(R.id.scrollView);
rv = (RecyclerView) findViewById(R.id.main_chat_rv);
cUser = FirebaseAuth.getInstance().getCurrentUser();
adapter = new ChatActivityAdapter(chats);
final LinearLayoutManager manager = new LinearLayoutManager(ChatActivity.this,
LinearLayoutManager.VERTICAL, false);
rv.setLayoutManager(manager);
refrence1 = FirebaseDatabase.getInstance()
.getReference()
.child("messages")
.child(cUser.getUid() + "_" + target.getUserId());
refrence2 = FirebaseDatabase.getInstance()
.getReference()
.child("messages")
.child(target.getUserId() + "_" + cUser.getUid());
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.w("SEND","send message");
if(message.getText().toString().length() > 0){
ChatModel chat = new ChatModel();
chat.setSender(cUser.getEmail());
chat.setMessage(message.getText().toString());
chat.setReceiver(target.getEmailAddress());
chat.setSenderUid(cUser.getUid());
chat.setReceiverUid(target.getUserId());
chat.setTimestamp((new Date()).getTime());
DatabaseReference ref1 = refrence1.push();
ref1.setValue(chat);
DatabaseReference ref2 = refrence2.push();
ref2.setValue(chat);
message.setText("");
}
}
});
refrence1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
chats.clear();
for(DataSnapshot snapshot :dataSnapshot.getChildren()){
ChatModel chat = new ChatModel();
chat.setSender(snapshot.child("sender").getValue(String.class));
chat.setMessage(snapshot.child("message").getValue(String.class));
chat.setReceiver(snapshot.child("receiver").getValue(String.class));
chat.setSenderUid(snapshot.child("senderUid").getValue(String.class));
chat.setReceiverUid(snapshot.child("receiverUid").getValue(String.class));
chat.setTimestamp(1592455659978L);
chats.add(chat);
}
adapter.setmChats(chats);
adapter.notifyDataSetChanged();
rv.scrollToPosition(adapter.getItemCount()-1);
Log.e("[CH]","DATACHANGE " + chats.size());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.e("[CH]","CANCEL");
}
});
refrence1.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
chats.clear();
adapter.notifyDataSetChanged();
rv.scrollToPosition(adapter.getItemCount()-1);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Log.e("[CH]","DB CHANGE");
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
Log.e("[CH]","DB REMOVE");
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Log.e("[CH]","Child Moved");
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.e("[CH]","DB ERROR");
}
});
rv.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
Log.e("[CH]","" + adapter.getItemCount());
}
}
Then, here is my ChatActivityAdapter
package com.divistant.chat.ui.chat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.divistant.chat.R;
import com.google.firebase.auth.FirebaseAuth;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class ChatActivityAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private static final int VIEW_TYPE_ME = 1;
private static final int VIEW_TYPE_OTHER = 2;
List<ChatModel> mChats;
public void setmChats(List<ChatModel> mChats) {
this.mChats = mChats;
}
public ChatActivityAdapter(List<ChatModel> mChats) {
this.mChats = mChats;
Log.e("ADAPTER","CONSTRUCTED " + mChats.size());
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
RecyclerView.ViewHolder viewHolder = null;
switch (viewType) {
case VIEW_TYPE_ME:
View viewChatMine = layoutInflater.inflate(R.layout.chat_item, parent, false);
viewHolder = new MyChatViewHolder(viewChatMine);
break;
case VIEW_TYPE_OTHER:
View viewChatOther = layoutInflater.inflate(R.layout.chat_item_other, parent, false);
viewHolder = new OtherChatViewHolder(viewChatOther);
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
if (TextUtils.equals(mChats.get(position).senderUid,
FirebaseAuth.getInstance().getCurrentUser().getUid())) {
configureMyChatViewHolder((MyChatViewHolder) holder, position);
} else {
configureOtherChatViewHolder((OtherChatViewHolder) holder, position);
}
}
private void configureMyChatViewHolder(final MyChatViewHolder myChatViewHolder, int position) {
ChatModel chat = mChats.get(position);
SimpleDateFormat sfd = new SimpleDateFormat("hh:mm a");
String date=sfd.format(new Date(chat.timestamp).getTime());
myChatViewHolder.senderMsgTime.setText(date);
myChatViewHolder.txtChatMessage.setText(chat.getMessage());
}
private void configureOtherChatViewHolder(final OtherChatViewHolder otherChatViewHolder, int position) {
final ChatModel chat = mChats.get(position);
SimpleDateFormat sfd = new SimpleDateFormat("hh:mm a");
String date=sfd.format(new Date(chat.timestamp).getTime());
otherChatViewHolder.receiverMsgTime.setText(date);
otherChatViewHolder.txtChatMessage.setText(chat.getMessage());
}
#Override
public int getItemCount() {
return mChats.size();
}
#Override
public int getItemViewType(int position) {
if (TextUtils.equals(mChats.get(position).senderUid,
FirebaseAuth.getInstance().getCurrentUser().getUid())) {
return VIEW_TYPE_ME;
} else {
return VIEW_TYPE_OTHER;
}
}
private static class MyChatViewHolder extends RecyclerView.ViewHolder {
private TextView txtChatMessage, txtUserAlphabet;
private TextView senderMsgTime;
public MyChatViewHolder(View itemView) {
super(itemView);
txtChatMessage = (TextView) itemView.findViewById(R.id.text_view_chat_message);
txtUserAlphabet = (TextView) itemView.findViewById(R.id.text_view_user_alphabet);
senderMsgTime=(TextView) itemView.findViewById(R.id.senderMsgTime);
}
}
private static class OtherChatViewHolder extends RecyclerView.ViewHolder {
private TextView txtChatMessage, txtUserAlphabet;
private TextView receiverMsgTime;
public OtherChatViewHolder(View itemView) {
super(itemView);
txtChatMessage = (TextView) itemView.findViewById(R.id.text_view_chat_message_ot);
txtUserAlphabet = (TextView) itemView.findViewById(R.id.text_view_user_alphabet_ot);
receiverMsgTime=(TextView) itemView.findViewById(R.id.receiverMsgTime_ot);
}
}
}
Thanks
Thats because you are clearing the list on childevent listener and not adding the new child in list and not passing the list to the adapter.
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
chats.clear();
adapter.notifyDataSetChanged();
rv.scrollToPosition(adapter.getItemCount()-1);
}
Now change the code by adding the lines
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
chats.clear();
for(DataSnapshot snapshot :dataSnapshot.getChildren()){
ChatModel chat = new ChatModel();
chat.setSender(snapshot.child("sender").getValue(String.class));
chat.setMessage(snapshot.child("message").getValue(String.class));
chat.setReceiver(snapshot.child("receiver").getValue(String.class));
chat.setSenderUid(snapshot.child("senderUid").getValue(String.class));
chat.setReceiverUid(snapshot.child("receiverUid").getValue(String.class));
chat.setTimestamp(1592455659978L);
chats.add(chat);
}
adapter.setmChats(chats);
adapter.notifyDataSetChanged();
rv.scrollToPosition(adapter.getItemCount()-1);
}
in my case i used onResume()
#Override
protected void onResume() {
super.onResume();
adapter.notifyDataSetChanged();
}
Can you put rv.setAdapter(adapter) after rv.setLayoutManager(manager);?
And you verify if the method onDataChange(...) its always called??
You can use the following code in the adapter where you want to refresh recyclerview, for example in #Override public void onBackPressed(){} function. If your chats array changed, you should refresh this adapter.
mAdapter = new ChatActivityAdapter(context, chats.get(chats.size() - 1), chats);
recyclerView.setAdapter(mAdapter);
I got a problem with the date of my SharedPreferences. I am using 5 Fragment wher you can dynamically add item to a RecyclerView. The Problem is that when ever I save my data on a particular fragment and reload the app the value that has been saved loads into every single Fragment of mine.It actually save the data to the Fragment it is on.I am using Gson to save my ArrayList of items
This is my Fragment (Fragment0 from 5 in total, the others are just copied and refactored)
package com.example.barryblack;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import static android.content.Context.MODE_PRIVATE;
public class FragmentPage0 extends Fragment {
private ExampleAdapter mAdapter;
private EditText editTask;
ArrayList<MyItem> items;
private Button insertbtn;
private Button stateButton;
private TextView taskText;
private String task;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable
Bundle savedInstanceState) {
CreateExampleList();
View view = inflater.inflate(R.layout.page_fragment0, container, false);
loadData();
RecyclerView recyclerView = view.findViewById(R.id.listRecyclerView);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
new ItemTouchHelper(itemTouchHelperCallback).attachToRecyclerView(recyclerView);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemViewCacheSize(500);
mAdapter = new ExampleAdapter(items);
recyclerView.setAdapter(mAdapter);
taskText = view.findViewById(R.id.tv_country);
insertbtn = view.findViewById(R.id.button_insert);
editTask = view.findViewById(R.id.editTask);
stateButton = view.findViewById(R.id.tv_button);
insertbtn.setEnabled(false);
editTask.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String taskInput = editTask.getText().toString().trim();
insertbtn.setEnabled(!taskInput.isEmpty());
}
#Override
public void afterTextChanged(Editable s) {
task = editTask.getText().toString().trim();
}
});
insertbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InsertItem();
SaveData();
editTask.setText(null);
}
});
return view;
}
private void SaveData() {
SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("shared
preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(items);
editor.putString("task list", json);
editor.apply();
}
private void loadData() {
SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("shared
preferences", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("task list", null);
Type type = new TypeToken<ArrayList<MyItem>>() {
}.getType();
items = gson.fromJson(json, type);
if (items == null) {
items = new ArrayList();
}
}
public void InsertItem() {
items.add(new MyItem(task, stateButton));
mAdapter.notifyItemInserted(items.size());
}
private void CreateExampleList() {
items = new ArrayList<MyItem>();
}
ItemTouchHelper.SimpleCallback itemTouchHelperCallback = new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder
viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
items.remove(viewHolder.getAdapterPosition());
mAdapter.notifyItemRemoved(viewHolder.getAdapterPosition());
SaveData();
}
};
}
This is my Adapter. I think the problem is inside the OnCreateViewHolder but im not quiet sure
package com.example.barryblack;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private ArrayList<MyItem> mExampleList;
public static class ExampleViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView;
private EditText topicName;
public Button mButton;
private int clicks = 1;
public static final String SHARED_PREFS = "sharedPrefs";
public static final String TOPIC = "topic";
public static final String CLICKS = "clicks";
public ExampleViewHolder(View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.tv_country);
mButton = itemView.findViewById(R.id.tv_button);
topicName = itemView.findViewById(R.id.editText);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicks++;
if (clicks % 2 == 0) {
mButton.setBackgroundResource(R.drawable.button_green);
}else
mButton.setBackgroundResource(R.drawable.button_red);
}
});
}
}
public ExampleAdapter(ArrayList<MyItem> exampleList) {
mExampleList = exampleList;
}
#Override
public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.example_item, parent, false);
ExampleViewHolder evh = new ExampleViewHolder(v);
return evh;
}
#Override
public void onBindViewHolder(ExampleViewHolder holder, int position) {
MyItem currentItem = mExampleList.get(position);
holder.mTextView.setText(currentItem.getTaskText());
}
#Override
public int getItemCount() {
return mExampleList.size();
}
}
Use this for your fragments. So every fragment has his own SharedPreferences
private static final String SHARED_PREFS_FRAGMENT_A = "fragmentA";
private static final String SHARED_PREFS_FRAGMENT_B = "fragmentB";
...
SharedPreferences sharedPreferences = getActivity().getSharedPreferences(SHARED_PREFS_FRAGMENT_A , MODE_PRIVATE);
I want to get list of all keys in recyclerview, tried everything but getting nothing, I do not want attributes of keys. Once I get a list of all keys in recyclerview then I will make it clickable and then I want attributes of that key which is clicked please help my this my Final year Project.
I did not use the method setFname of my POJO class because I put my data manually in Firebase.
package com.fyp.phasse_4;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class foodBasketFragment extends Fragment {
private ArrayList<FoodsModel> foodsModels;
private DatabaseReference foodRef;
private FirebaseAuth mAuth;
private String currentUserID;
RecyclerView recyclerView;
String p;
public foodBasketFragment() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable final ViewGroup container,
#Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_food_basket, container, false);
foodRef = FirebaseDatabase.getInstance().getReference().child("FoodData");
mAuth = FirebaseAuth.getInstance();
FoodsModel model = new FoodsModel()
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
currentUserID = mAuth.getCurrentUser().getUid();
foodsModels = new ArrayList<>();
return view;
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerOptions options = new FirebaseRecyclerOptions.Builder<FoodsModel>()
.setQuery(foodRef, FoodsModel.class)
.build();
FirebaseRecyclerAdapter<FoodsModel, myViewHolder> adapter = new
FirebaseRecyclerAdapter<FoodsModel, myViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final myViewHolder holder, final int position,
#NonNull final FoodsModel model) {
foodRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
}
holder.name.setText();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.foods_list, parent,
false);
return new myViewHolder(view);
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
public static class myViewHolder extends RecyclerView.ViewHolder
{
TextView name;
public myViewHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.txtName);
}
}
}
This is my POJO class,
package com.fyp.phasse_4;
public class FoodsModel {
public String fName;
public FoodsModel() {
}
public FoodsModel(String fName) {
this.fName = fName;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
}
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
String key = dataSnapshot1.getKey();
System.out.println(key);
}