I create an app which contain recyclerview and I add data in recyclerview arrayList from alertDilog and edit,delete data from AlertDilog according to the user click .It works properly but when I connect my app to firebase Database, my app doesn't work properly.
Recyclerview Adapter:
public class recyclerviewadapter extends RecyclerView.Adapter<recyclerviewadapter.Viewholder> {
ArrayList<customitem> datalist;
vonclick mclick;
#NonNull
#Override
public Viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerviewexdesign,parent,false);
return new Viewholder(v,mclick);
}
public recyclerviewadapter(ArrayList<customitem> datalist) {
this.datalist = datalist;
}
#Override
public void onBindViewHolder(#NonNull Viewholder holder, int position) {
customitem n = datalist.get(position);
holder.productname.setText(n.getproductname());
}
#Override
public int getItemCount() {
return datalist.size();
}
public class Viewholder extends RecyclerView.ViewHolder {
TextView productname;
public Viewholder(#NonNull View itemView, final vonclick listener) {
super(itemView);
productname = itemView.findViewById(R.id.titleid);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener!=null){
int possition =getAdapterPosition();
if (possition !=RecyclerView.NO_POSITION){
listener.cclick(possition);
}
}
}
});
}
}
public interface vonclick{
void cclick(int possition);
}
public void recyclerviewonclicl(vonclick possition){
mclick=possition;
}
}
and item class:
public class customitem {
String productname,size,price,box;
int kg;
public customitem(){
}
public customitem(String productname, String size,String price,String box,int kg) {
this.productname = productname;
this.size = size;
this.price = price;
this.box = box;
this.kg = kg;
}
public String getproductname() {
return productname;
}
public void setproductname(String productname) {
this.productname = productname;
}
public String getsize() {
return size;
}
public void setsize(String size) {
this.size = size;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getBox() {
return box;
}
public void setBox(String box) {
this.box = box;
}
public int getKg() {
return kg;
}
public void setKg(int kg) {
this.kg = kg;
}
}
last one main class:
public class addproduct extends AppCompatActivity {
RecyclerView recyclerView;
ArrayList<customitem> datalist =new ArrayList<customitem>();
FirebaseDatabase mdatabase;
DatabaseReference mreference;
EditText productname,price,size,b2;
Spinner sizespinner;
Button okbutton;
View mview;
ImageView cancel;
AlertDialog d;
AlertDialog.Builder alert;
recyclerviewadapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addproduct);
getSupportActionBar().setTitle("Add product");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mdatabase = FirebaseDatabase.getInstance();
//?????????????????????? my firebase referance ????????????
mreference = mdatabase.getReference().child("product");
mreference.keepSynced(true);
recyclerView = findViewById(R.id.recyclerviewid);
buildrecyclerview();
//mreference.child("product").setValue(datalist);
}
public void buildrecyclerview(){
adapter = new recyclerviewadapter(datalist);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(this,4));
recyclerView.setAdapter(adapter);
mreference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1:dataSnapshot.getChildren()){
customitem j =dataSnapshot1.getValue(customitem.class);
datalist.add(j);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
adapter.recyclerviewonclicl(new recyclerviewadapter.vonclick() {
#Override
public void cclick(final int possition) {
//?????????????? alert dilog two for delete and update data ????????????????
AlertDialog.Builder bl = new AlertDialog.Builder(addproduct.this);
View v = getLayoutInflater().inflate(R.layout.manageralertdilogtwo,null);
bl.setView(v);
d=bl.create();
d.show();
final EditText productname2 = v.findViewById(R.id.productname2);
final EditText size2 = v.findViewById(R.id.packsizeid2);
final EditText price2 = v.findViewById(R.id.priceid2);
final EditText box2 = v.findViewById(R.id.Box2);
Button okbtn = v.findViewById(R.id.okbuttonid2);
Button dltbtn = v.findViewById(R.id.deleteid);
ImageView cross =v.findViewById(R.id.cancelid2);
final Spinner sp =v.findViewById(R.id.spinnerid2);
//String pn = datalist.get(possition).getproductname();
productname2.setText(datalist.get(possition).getproductname());
size2.setText(datalist.get(possition).getsize());
price2.setText(datalist.get(possition).getPrice());
box2.setText(datalist.get(possition).getBox());
sp.setSelection(datalist.get(possition).getKg());
cross.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
}
});
okbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//?????????????? update data accroding user selectiong ??????????????
//datalist.get(possition).setproductname(productname2.getText().toString());
//datalist.get(possition).setPrice(price2.getText().toString());
//datalist.get(possition).setsize(size2.getText().toString());
//datalist.get(possition).setBox(box2.getText().toString());
//datalist.get(possition).setKg(sp.getSelectedItemPosition());
customitem m = new customitem(productname2.getText().toString(),size2.getText().toString()
,price2.getText().toString(),box2.getText().toString(),sp.getSelectedItemPosition());
mreference.child(String.valueOf(datalist.get(possition))).setValue(m);
d.dismiss();
}
});
dltbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//???????????????? delete data from recycler view accroding user selection ???????????
//datalist.remove(possition);
mreference.child(String.valueOf(datalist.get(possition))).removeValue();
// adapter.notifyDataSetChanged();
d.dismiss();
}
});
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.addproductmenu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.addproduct:
buildalert();
break;
case R.id.seedetails:
Intent n = new Intent(addproduct.this,managermain.class);
startActivity(n);
break;
}
return super.onOptionsItemSelected(item);
}
public void buildalert(){
//?????? alert dilog one for take data ???????????????
alert = new AlertDialog.Builder(addproduct.this);
mview = getLayoutInflater().inflate(R.layout.manageralertalertdilog,null);
productname = mview.findViewById(R.id.productname);
price = mview.findViewById(R.id.priceid);
alert.setCancelable(true);
size = mview.findViewById(R.id.packsizeid);
cancel = mview.findViewById(R.id.cancelid);
sizespinner = mview.findViewById(R.id.spinnerid);
okbutton = mview.findViewById(R.id.okbuttonid);
b2 = mview.findViewById(R.id.Box);
alert.setView(mview);
final AlertDialog dl = alert.create();
dl.show();
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dl.dismiss();
}
});
okbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (productnamem() && sizem()){
//add data from alert dilog
String productnm = productname.getText().toString();
String pricec = price.getText().toString();
String sizee = size.getText().toString();
int kg = sizespinner.getSelectedItemPosition();
String box= b2.getText().toString();
//?? add data in recyclerview from alert dilog ???????????????
//datalist.add(new customitem(productnm,sizee,pricec,box,kg));
customitem n = new customitem(productnm,sizee,pricec,box,kg);
mreference.child(String.valueOf(datalist.size())).setValue(n);
//adapter.notifyDataSetChanged();
//mreference.setValue(datalist);
dl.dismiss();
}
}
});
}
public boolean productnamem(){
if (productname.getText().toString().trim().isEmpty()){
productname.setError("Please fill it");
productname.setFocusable(true);
return false;
}
else {
return true;
}
}
public boolean sizem(){
if (size.getText().toString().trim().isEmpty()){
size.setError("Please fill it");
size.setFocusable(true);
return false;
}
else {
return true;
}
}
}
Related
>>>>>>>MAIN ACTIVITY XML<<<<<<<
As you can see the TextView is on the top, that's where I want to display the title of selected RecyclerView item. Most of the tutorials and blog teach to navigate to next activity when an item is clicked, but that isn't something I am looking for.
MainActivity.java
public class MainActivity extends AppCompatActivity implements ItemAdapterCallback {
private RecyclerView recyclerView;
private List<Item> itemList;
private ItemAdapter itemAdapter;
private SearchView searchView;
TextView itemname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize(savedInstanceState);
initializeLogic();
}
private void initialize(Bundle savedInstanceState) {
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
searchView = (SearchView) findViewById(R.id.searchView);
searchView.clearFocus();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
filterList(newText);
return true;
}
});
}
private void filterList(String newText) {
List<Item> filteredList = new ArrayList<>();
for (Item item : itemList) {
if (item.getItemName().toLowerCase().contains(newText.toLowerCase())){
filteredList.add(item);
}
}
if (filteredList.isEmpty()) {
Toast.makeText(this, "No Match", Toast.LENGTH_SHORT).show();
} else {
itemAdapter.setFilteredList(filteredList);
}
}
private void initializeLogic() {
RecyclerView();
}
private void RecyclerView () {
itemList = new ArrayList<>();
// Adding Data to Item List
itemList.add(new Item("Black", R.drawable.android_black));
itemList.add(new Item("Blue", R.drawable.android_blue));
itemList.add(new Item("Green", R.drawable.android_green));
itemList.add(new Item("Pink", R.drawable.android_pink));
itemList.add(new Item("Red", R.drawable.android_red));
itemList.add(new Item("Yellow", R.drawable.android_yellow));
itemList.add(new Item("Black", R.drawable.android_black));
itemList.add(new Item("Blue", R.drawable.android_blue));
itemList.add(new Item("Green", R.drawable.android_green));
itemList.add(new Item("Pink", R.drawable.android_pink));
itemList.add(new Item("Red", R.drawable.android_red));
itemList.add(new Item("Yellow", R.drawable.android_yellow));
itemAdapter = new ItemAdapter(itemList, this);
recyclerView.setAdapter(itemAdapter);
}
#Override
public void onItemClicker() {
//????????????????
}
}
Item.java
public class Item {
private String itemName;
private int itemImage;
public Item(String itemName, int itemImage) {
this.itemImage = itemImage;
this.itemName = itemName;
}
public int getItemImage() {
return itemImage;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
}
ItemAdapter.java
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemViewHolder> {
private List<Item> itemList;
int row_index = -1;
private ItemAdapterCallback callback;
public ItemAdapter(List<Item> itemList, ItemAdapterCallback callback) {
this.itemList = itemList;
this.callback = callback;
}
public void setFilteredList(List<Item> filteredList) {
this.itemList = filteredList;
notifyDataSetChanged();
}
#NonNull
#Override
public ItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.each_item, parent, false );
return new ItemViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ItemViewHolder holder, int position) {
Item item = itemList.get(position);
holder.itemNameTv.setText(item.getItemName());
holder.itemImageView.setImageResource(item.getItemImage());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
////////////////////////////
//Toast.makeText(view.getContext(), "Item is clicked" + item.getItemName(), Toast.LENGTH_SHORT).show();
}
});
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
row_index = position;
notifyDataSetChanged();
Toast.makeText(v.getContext(), "Item is clicked " + position + " " + item.getItemName(), Toast.LENGTH_SHORT).show();
callback.onItemClicker();
}
});
if (row_index == position) {
holder.cardView.setBackgroundColor(Color.LTGRAY);
} else {
holder.cardView.setBackgroundColor(Color.WHITE);
}
}
#Override
public int getItemCount() {
if (itemList == null) {
return 0;
} else {
return itemList.size();
}
}
public class ItemViewHolder extends RecyclerView.ViewHolder{
public TextView itemNameTv;
public ImageView itemImageView;
public CardView cardView;
public ItemViewHolder(#NonNull View itemView) {
super(itemView);
cardView = itemView.findViewById(R.id.eachCardView);
itemNameTv = itemView.findViewById(R.id.eachItemTextView);
itemImageView = itemView.findViewById(R.id.eachItemImageView);
}
}
}
ItemAdapterCallback (Interface)
public interface ItemAdapterCallback {
void onItemClicker();
}
You are just missing few things here.
1- if you want to get the title from the adapter you will need to pass the title in your Callback Interface
public interface ItemAdapterCallback {
void onItemClicker(String title);}
2- after this change you will override the onItemClickerCallback in your mainActivity
it will look like this
#Override
public void onItemClicker(String title) {
// your title ,
itemname.setText(title);
}
3- in onClick function of the adapter add this line
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(callback!=null){
callback.onItemClicker( item.getItemName());
}
}
});
that's all you need to do to show the title in your mainActivity from adapter.
I use Firebase to send messages between users, and I'd like to use a new unread message badge and the number of unread messages.
I want to help solve this problem so I can get the number of unread messages when they are received from the other user and displayed in the user's list
like this
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> {
public static final int MSG_TYPE_LEFT = 0;
public static final int MSG_TYPE_RIGHT = 1;
Typeface MR,MRR;
private Context mContext;
private List<Chat> mChat;
private String imageurl;
public View view_click;
FirebaseUser fuser;
public MessageAdapter(Context mContext, List<Chat> mChat, String imageurl){
this.mChat = mChat;
this.mContext = mContext;
this.imageurl = imageurl;
MRR = Typeface.createFromAsset(mContext.getAssets(), "fonts/myriadregular.ttf");
MR = Typeface.createFromAsset(mContext.getAssets(), "fonts/myriad.ttf");
}
#NonNull
#Override
public MessageAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == MSG_TYPE_RIGHT) {
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_right, parent, false);
return new MessageAdapter.ViewHolder(view);
} else {
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_left, parent, false);
return new MessageAdapter.ViewHolder(view);
}
}
#Override
public void onBindViewHolder(#NonNull MessageAdapter.ViewHolder holder, int position) {
Chat chat = mChat.get(position);
holder.show_message.setTypeface(MRR);
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
chat.setSelected(!chat.isSelected());
holder.view.setBackgroundColor(chat.isSelected() ? Color.TRANSPARENT : Color.WHITE);
FirebaseDatabase.getInstance("https://pineka-social-media-mast-da52a-default-rtdb.firebaseio.com/"
).getReference("Chats")
.child(chat.getChatid())
.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
View view;
final Snackbar snackbar = Snackbar.make(holder.lyt_parent, "", Snackbar.LENGTH_LONG);
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.snack_delete, null);
snackbar.getView().setBackgroundColor(Color.TRANSPARENT);
Snackbar.SnackbarLayout snackBarView = (Snackbar.SnackbarLayout) snackbar.getView();
snackBarView.setPadding(0, 0, 0, 0);
snackBarView.addView(view, 0);
snackbar.show();
// Toast.makeText(mContext, "Deleted! ="+chat.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
return false;
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view_click) {
// holder.delete.setVisibility(View.VISIBLE);
final Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.po);
LinearLayout copy = dialog.findViewById(R.id.copy);
LinearLayout share = dialog.findViewById(R.id.share);
LinearLayout reply = dialog.findViewById(R.id.reply);
LinearLayout delete = dialog.findViewById(R.id.remove_item);
copy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", chat.getMessage());
clipboard.setPrimaryClip(clip);
View view;
final Snackbar snackbar = Snackbar.make(holder.lyt_parent, "", Snackbar.LENGTH_LONG);
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.snack, null);
snackbar.getView().setBackgroundColor(Color.TRANSPARENT);
Snackbar.SnackbarLayout snackBarView = (Snackbar.SnackbarLayout) snackbar.getView();
snackBarView.setPadding(0, 0, 0, 0);
snackBarView.addView(view, 0);
snackbar.show();
dialog.dismiss();
}
});
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent2 = new Intent(); intent2.setAction(Intent.ACTION_SEND);
intent2.setType("text/plain");
intent2.putExtra(Intent.EXTRA_TEXT, chat.getMessage() );
mContext. startActivity(Intent.createChooser(intent2, "Share via"));
dialog.dismiss();
}
});
reply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view_click) {
FirebaseDatabase.getInstance("https://pineka-social-media-mast-da52a-default-rtdb.firebaseio.com/"
).getReference("Chats")
.child(chat.getChatid())
.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
View view;
final Snackbar snackbar = Snackbar.make(holder.lyt_parent, "", Snackbar.LENGTH_LONG);
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.snack_delete, null);
snackbar.getView().setBackgroundColor(Color.TRANSPARENT);
Snackbar.SnackbarLayout snackBarView = (Snackbar.SnackbarLayout) snackbar.getView();
snackBarView.setPadding(0, 0, 0, 0);
snackBarView.addView(view, 0);
dialog.dismiss();
snackbar.show();
// Toast.makeText(mContext, "Deleted! ="+chat.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
dialog.setCancelable(true);
dialog.show();
/*
*/
}
}
);
holder.show_message.setText(chat.getMessage());
if(chat.getTime()!=null && !chat.getTime().trim().equals("")) {
holder.time_tv.setText(holder.convertTime(chat.getTime()));
}
if (imageurl.equals("default")){
holder.profile_image.setImageResource(R.drawable.ic_profile_outline_40);
} else {
Glide.with(mContext).load(imageurl).into(holder.profile_image);
}
if (position == mChat.size()-1){
if (chat.isIsseen()){
// holder.seen.setImageResource(R.drawable.ic_baseline_check_24);
} else {
// holder.seen.setImageResource(R.drawable.ic_baseline_check_24_read);
}
} else {
// holder.seen.setVisibility(View.GONE);
}
}
#Override
public int getItemCount() {
return mChat.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView show_message;
public ImageView profile_image,seen,delete;
public TextView time_tv;
public Dialog myDialog;
public View view_click;
public LinearLayout lyt_parent;
private View view;
public ViewHolder(View itemView) {
super(itemView);
show_message = itemView.findViewById(R.id.show_message);
profile_image = itemView.findViewById(R.id.profile_image);
time_tv = itemView.findViewById(R.id.time_tv);
seen = itemView.findViewById(R.id.seen);
view = itemView;
lyt_parent= itemView.findViewById(R.id.lyt_parent);
}
public String convertTime(String time){
SimpleDateFormat formatter = new SimpleDateFormat("h:mm a");
String dateString = formatter.format(new Date(Long.parseLong(time)));
return dateString;
}
}
#Override
public int getItemViewType(int position) {
fuser = FirebaseAuth.getInstance().getCurrentUser();
if (mChat.get(position).getSender().equals(fuser.getUid())){
return MSG_TYPE_RIGHT;
} else {
return MSG_TYPE_LEFT;
}
}
}
item Uaer Massage
public class UserAdaptermsg extends RecyclerView.Adapter<UserAdaptermsg.ViewHolder> {
private Context mContext;
private List<User> mUsers;
private boolean ischat;
private OnItemClick onItemClick;
Typeface MR,MRR;
String theLastMessage;
boolean isopend ;
public UserAdaptermsg(Context mContext, OnItemClick onItemClick, List<User> mUsers, boolean ischat){
this.onItemClick = onItemClick;
this.mUsers = mUsers;
this.mContext = mContext;
this.ischat = ischat;
if(mContext!=null) {
MRR = Typeface.createFromAsset(mContext.getAssets(), "fonts/myriadregular.ttf");
MR = Typeface.createFromAsset(mContext.getAssets(), "fonts/myriad.ttf");
}
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.user_item_msg, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final User user = mUsers.get(position);
// holder.username.setTypeface(MR);
holder.last_msg.setTypeface(MRR);
holder.badg_massage.setVisibility(View.GONE);
holder.username.setText(user.getFullname());
if (user.getImageurl().equals("default")){
holder.profile_image.setImageResource(R.drawable.ic_profile_outline_40);
} else {
Glide.with(mContext).load(user.getImageurl()).into(holder.profile_image);
}
if (ischat){
lastMessage(user.getId(), holder.last_msg);
count(user.getId(),true);
// holder.badg_massage.setVisibility(View.VISIBLE);
// holder.badg_massage.setText(mUsers.size()+"");
} else {
holder.last_msg.setVisibility(View.GONE);
}
if (ischat){
if (user.getStatus().equals("online")){
holder.img_on.setVisibility(View.VISIBLE);
holder.img_off.setVisibility(View.GONE);
} else {
holder.img_on.setVisibility(View.GONE);
holder.img_off.setVisibility(View.GONE);
}
} else {
holder.img_on.setVisibility(View.GONE);
holder.img_off.setVisibility(View.GONE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, MessageActivity.class);
intent.putExtra("userid", user.getId());
mContext.startActivity(intent);
}
});
holder.profile_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClick.onItemCLick(user.getId(),view);
}
});
}
#Override
public int getItemCount() {
return mUsers.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView username;
public ImageView profile_image;
private ImageView img_on;
private ImageView img_off;
private TextView last_msg;
private TextView badg_massage;
public ViewHolder(View itemView) {
super(itemView);
username = itemView.findViewById(R.id.username);
profile_image = itemView.findViewById(R.id.profile_image);
img_on = itemView.findViewById(R.id.img_on);
img_off = itemView.findViewById(R.id.img_off);
last_msg = itemView.findViewById(R.id.last_msg);
badg_massage = itemView.findViewById(R.id.badg_massage);
}
}
//check for last message
private void lastMessage(final String userid, final TextView last_msg){
theLastMessage = "default";
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Chats");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Chat chat = snapshot.getValue(Chat.class);
if (firebaseUser != null && chat != null) {
if (chat.getReceiver().equals(firebaseUser.getUid()) && chat.getSender().equals(userid) ||
chat.getReceiver().equals(userid) && chat.getSender().equals(firebaseUser.getUid())) {
theLastMessage = chat.getMessage();
}
}
}
switch (theLastMessage){
case "default":
last_msg.setText("No Message");
break;
default:
last_msg.setText(theLastMessage);
break;
}
theLastMessage = "default";
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void count(final String userid, final Boolean count){
isopend = false;
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Chats");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Chat chat = snapshot.getValue(Chat.class);
if (firebaseUser != null && chat != null) {
if (chat.getReceiver().equals(firebaseUser.getUid()) && chat.getSender().equals(userid) ||
chat.getReceiver().equals(userid) && chat.getSender().equals(firebaseUser.getUid())) {
isopend = chat.isIsopened();
}
}
}
if (isopend == false) {
Toast.makeText(mContext, "notopent", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mContext, "isopend", Toast.LENGTH_SHORT).show();
}
isopend = true;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
model Chat
package com.Model;
public class Chat {
private String sender;
private String receiver;
private String message;
private boolean isseen;
private String chatid;
private boolean isSelected = false;
private boolean isopened;
private String time;
public Chat(String sender, String receiver, String message, boolean isseen, String chatid, boolean isopened, String time) {
this.sender = sender;
this.receiver = receiver;
this.message = message;
this.isseen = isseen;
this.chatid = chatid;
this.isopened = isopened;
this.time = time;
}
public Chat() {
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public boolean isIsseen() {
return isseen;
}
public void setIsseen(boolean isseen) {
this.isseen = isseen;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getChatid() {
return chatid;
}
public void setChatid(String chatid) {
this.chatid = chatid;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
public boolean isIsopened() {
return isopened;
}
public void setIsopened(boolean isopened) {
this.isopened = isopened;
}
}
I have 2 recycler views that have cards.They basically look the same have the same number of cards and everthing. The first one is for like viewing and other stuff and the second one is only for deleting cards. OnlongClicking a card in the first recycler view triggers the opening of the second recycler view. I wanted to add transitions in between them like what keep notes has done when a card is long clicked. Both the recycler view use the same adapter. I have set what the adapter should do based on passing context to the adapter. enter image description here this is my 1st layout having the 1st recycler view.enter image description here this is the 2nd layout having the second recycler view.I want like a seamless transition for the tool bar again just like what Google keeps has done.A simple solution would be preferred as I am very new to this stuff.
Here is the java code for the adapter.
public class Task_recycle_view_adapter extends RecyclerView.Adapter<Task_recycle_view_adapter.ViewHolder>{
private List<struct_task> task_list= new ArrayList<>();
private ArrayList<String> isSelected=new ArrayList<String>();
protected Context context1;
protected Context context2;
private String labelName;
private String taskName;
private ConstraintLayout label_menu_avatar;
public Task_recycle_view_adapter(Context context1,Context context2)
{
this.context1=context1;
this.context2=context2;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {//parent is the parent of the recycle view it is taken as an arg to use it to attach the every view to the parent view
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_task,parent,false);//to inflate a layout
ViewHolder holder= new ViewHolder(view);
return holder;
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.taskname.setText(task_list.get(position).getTask_name());
holder.taskid.setText(String.valueOf(task_list.get(position).getTask_id()));
if(context2==null && context1!=null) {
String taskName=task_list.get(position).getTask_name();
Long taskid=task_list.get(position).getTask_id();
String duedate=task_list.get(position).getDue_date();
holder.parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DataBaseHelper dataBaseHelper = new DataBaseHelper(context1);
ArrayList<SubTaskModel> subtask_list=(ArrayList<SubTaskModel>) dataBaseHelper.getAllSubTasksFor(labelName, Long.parseLong(holder.taskid.getText().toString()));
Intent intent1 =new Intent(context1,ViewTaskActivity.class);
intent1.putExtra("label_name",labelName);
intent1.putExtra("task_id",taskid);
intent1.putExtra("task_name",taskName);
intent1.putExtra("due_date",duedate);
intent1.putParcelableArrayListExtra("subtask_list", (ArrayList<? extends Parcelable>) subtask_list);
context1.startActivity(intent1);
}
});
holder.parent.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Intent intent2 = new Intent(context1, Delete_page_Activity.class);
intent2.putParcelableArrayListExtra("task_list", (ArrayList<? extends Parcelable>) task_list);
intent2.putExtra("label_name",labelName);
intent2.putExtra("selected_task",taskName);
Pair[] pairs = new Pair[1];
pairs[0]= new Pair<View,String>(label_menu_avatar,"transition1");
ActivityOptions options= ActivityOptions.makeSceneTransitionAnimation((Activity) context1,pairs);
context1.startActivity(intent2,options.toBundle());
return true;
}
});
}
if(context2!=null && context1==null)
{
if(taskName.equals(task_list.get(position).getTask_name()))
{
holder.active=1;
isSelected.add(holder.taskid.getText().toString());
holder.parent.findViewById(R.id.layout_for_every_task).setBackgroundResource(R.drawable.background_for_task_card);
}
holder.parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(holder.active==0) {
isSelected.add(holder.taskid.getText().toString());
v.findViewById(R.id.layout_for_every_task).setBackgroundResource(R.drawable.background_for_task_card);
holder.active=1;
}
else {
isSelected.remove(holder.taskid.getText().toString());
v.findViewById(R.id.layout_for_every_task).setBackgroundResource(R.drawable.background_for_task_card_transparent);
holder.active=0;
}
}
});
}
// subtasks 1 to 5
if(task_list.get(position).getSubtask1()!=null)
holder.subtask1.setText(task_list.get(position).getSubtask1());
else
holder.subtask1.setVisibility(View.GONE);
if(task_list.get(position).getSubtask2()!=null)
holder.subtask2.setText(task_list.get(position).getSubtask2());
else
holder.subtask2.setVisibility(View.GONE);
if(task_list.get(position).getSubtask3()!=null)
holder.subtask3.setText(task_list.get(position).getSubtask3());
else
holder.subtask3.setVisibility(View.GONE);
if(task_list.get(position).getSubtask4()!=null)
holder.subtask4.setText(task_list.get(position).getSubtask4());
else
holder.subtask4.setVisibility(View.GONE);
if(task_list.get(position).getSubtask5()!=null)
holder.subtask5.setText(task_list.get(position).getSubtask5());
else
holder.subtask5.setVisibility(View.GONE);
// due date
if(task_list.get(position).getDue_date()!=null)
holder.duedate.setText(task_list.get(position).getDue_date());
else
holder.duedate.setVisibility(View.GONE);
// progress
holder.progresscircle.setProgress(task_list.get(position).getProgress());
}
#Override
public int getItemCount() {
return task_list.size();
}
public void setTask_list(List<struct_task> task_list) {
this.task_list = task_list;//to refresh the data inside the recycler view
}
#Override
public int getItemViewType(int position) {
return position;
}
public String getLabelName() {
return labelName;
}
public void setLabelName(String labelName) {
this.labelName = labelName;
}
public ArrayList<String> getIsSelected() {
return isSelected;
}
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public void setLabel_menu_avatar(ConstraintLayout label_menu_avatar) {
this.label_menu_avatar = label_menu_avatar;
}
public static class ViewHolder extends RecyclerView.ViewHolder{// holds the view for every item inside the recycle view
private TextView taskname,taskid,duedate,subtask1,subtask2,subtask3,subtask4,subtask5;
private CardView parent;
private ProgressBar progresscircle;
public void setActive(int active) {
this.active = active;
}
private int active;
public ViewHolder(#NonNull View itemView) {
super(itemView);
taskid=itemView.findViewById(R.id.task_id);
taskname = itemView.findViewById(R.id.task_name);
parent = itemView.findViewById(R.id.card_for_every_task);
duedate = itemView.findViewById(R.id.due_date);
progresscircle = itemView.findViewById(R.id.progress_circular);
subtask1 = itemView.findViewById(R.id.subtask_1);
subtask2 = itemView.findViewById(R.id.subtask_2);
subtask3 = itemView.findViewById(R.id.subtask_3);
subtask4 = itemView.findViewById(R.id.subtask_4);
subtask5 = itemView.findViewById(R.id.subtask_5);
active=0;
}
}
}
Here is the code for the 1st activity i.e the 1st image:
public class TaskPageActivity extends AppCompatActivity {
private RecyclerView task_rv;//task recycler view
private FloatingActionButton addTask;
private long tasksNum;
private String labelName;
private DataBaseHelper dataBaseHelper = new DataBaseHelper(this);
private Task_recycle_view_adapter adapter= new Task_recycle_view_adapter(this,null);
private List<struct_task> tasks;
private EditText searchBar;
private ConstraintLayout search_btn;
private ConstraintLayout calendar_btn;
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_title);
getWindow().getSharedElementExitTransition();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
search_btn= findViewById(R.id.search_btn);
calendar_btn=findViewById(R.id.calendar_btn);
search_btn.setClickable(true);
search_btn.setFocusable(true);
labelName = getIntent().getExtras().getString("832715");
TextView txtLabelName = findViewById(R.id.Label_name);
txtLabelName.setText(labelName);
task_rv = findViewById(R.id.Recycle_view_task);
addTask = findViewById(R.id.add_task);
searchBar= (SearchBar) findViewById(R.id.search_bar);
tasksNum = getTasksNum(labelName, dataBaseHelper, adapter); //displays all tasks and return number of tasks
ConstraintLayout.LayoutParams params= (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
addTask.setOnClickListener(view -> {
tasksNum = getTasksNum(labelName, dataBaseHelper, adapter);
Intent intent = new Intent(TaskPageActivity.this, AddTaskPageActivity.class);
intent.putExtra("labelName", labelName);
intent.putExtra("taskID", tasksNum);
startActivity(intent);
});
search_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(searchBar.getVisibility()==View.INVISIBLE) {
search_btn.setAlpha(.5f);
searchBar.setVisibility(View.VISIBLE);
searchBar.requestFocus();
imm.showSoftInput(searchBar,InputMethodManager.SHOW_IMPLICIT);
ConstraintLayout.LayoutParams params= (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
params.verticalBias = .55f;
searchBar.setLayoutParams(params);
searchBar.requestFocus();
}
else {
searchBar.setVisibility(View.INVISIBLE);
search_btn.setAlpha(1.0f);
}
}
});
searchBar.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus) {
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
if(params.verticalBias==.9f) {
searchBar.requestFocus();
params.verticalBias = .55f;
searchBar.setLayoutParams(params);
}
searchBar.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if((event.getAction()==KeyEvent.ACTION_DOWN) && (keyCode==KeyEvent.KEYCODE_ENTER) && params.verticalBias==.55f)
{
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
searchBar.requestFocus();
params.verticalBias = .9f;
searchBar.setLayoutParams(params);
searchBar.clearFocus();
imm.hideSoftInputFromWindow(searchBar.getWindowToken(),0);
}
return false;
}
});
}
}
});
searchBar.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) {
}
#Override
public void afterTextChanged(Editable s) {
filter(s.toString());
}
});
AlertDialog alertDialog = new AlertDialog.Builder(TaskPageActivity.this).create();
calendar_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(calendar_btn.getAlpha()==1.0f) {
calendar_btn.setAlpha(.5f);
LayoutInflater inflater = getLayoutInflater();
View view1 = inflater.inflate(R.layout.dialog_calendar,null);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
alertDialog.setView(view1);
CalendarView mCalendarView= view1.findViewById(R.id.calendar);
mCalendarView.setMinDate(Calendar.getInstance().getTimeInMillis());
alertDialog.show();
}
}
});
alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
if(calendar_btn.getAlpha()==.5f)
calendar_btn.setAlpha(1.0f);
}
});
}
private void filter(String string) {
ArrayList<struct_task> filteredList = new ArrayList<>();
for(struct_task item: tasks)
{
if(item.getTask_name().contains(string) || item.getTask_name().contains(string.toUpperCase()))
{
filteredList.add(item);
}
}
if(filteredList.size()!=0) {
adapter.setTask_list(filteredList);
task_rv.setAdapter(adapter);
}
}
#Override
public void onBackPressed() {
if(searchBar.getText().toString().length()!=0) {
showAllTasks(labelName, dataBaseHelper, adapter);
searchBar.setText(null);
searchBar.setVisibility(View.INVISIBLE);
search_btn.setAlpha(1.0f);
}
else if(searchBar.getText().toString().length()==0)
{
super.onBackPressed();
}
}
#Override
protected void onResume() {
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
showAllTasks(labelName, dataBaseHelper, adapter);
if(params.verticalBias==.54f) {
searchBar.requestFocus();
params.verticalBias = .9f;
searchBar.setLayoutParams(params);
searchBar.clearFocus();
}
if(searchBar.getText().toString().length()==0) {
showAllTasks(labelName, dataBaseHelper, adapter);
}
else {
filter(searchBar.getText().toString());
}
super.onResume();
}
private void showAllTasks(String labelName, DataBaseHelper dataBaseHelper, Task_recycle_view_adapter adapter) {
tasks = dataBaseHelper.getAllTasksFor(labelName);
adapter.setLabelName(labelName);
adapter.setTask_list(tasks);
task_rv.setAdapter(adapter);
task_rv.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
}
long getTasksNum(String labelName, DataBaseHelper dataBaseHelper, Task_recycle_view_adapter adapter) {
return dataBaseHelper.getLastTaskID(labelName)+1; //to determine ID of next task
}
#Override
protected void onUserLeaveHint() {
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
params.verticalBias=.9f;
searchBar.setLayoutParams(params);
searchBar.setText(null);
searchBar.clearFocus();
super.onUserLeaveHint();
}
}
And finally for the 2nd activity which is triggered by longclicking any card
public class Delete_page_Activity extends AppCompatActivity {
private Task_recycle_view_adapter recycle_view_adapter = new Task_recycle_view_adapter(null,this);
private ArrayList<String> delete_list=new ArrayList<>();
private DataBaseHelper dataBaseHelper = new DataBaseHelper(this);
private String labelName=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delete_page);
overridePendingTransition(0,0);
Toolbar toolbar=findViewById(R.id.toolbar_bar);
ImageView close_btn=findViewById(R.id.close_btn);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
ArrayList<struct_task> task_list = getIntent().getParcelableArrayListExtra("task_list");
labelName=getIntent().getExtras().getString("label_name");
String task = getIntent().getExtras().getString("selected_task");
Log.e("test",labelName);
RecyclerView recyclerView = findViewById(R.id.delete_Recycler_View);
recycle_view_adapter.setTaskName(task);
recycle_view_adapter.setTask_list(task_list);
recyclerView.setAdapter(recycle_view_adapter);
recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
close_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar_menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId())
{
case R.id.tool_bar_item1:
delete_list = recycle_view_adapter.getIsSelected();
if(delete_list.size()==0)
{
Toast toast1= new Toast(this);
toast1.setDuration(Toast.LENGTH_SHORT);
LayoutInflater inflater= (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view= inflater.inflate(R.layout.activity_toast_msg1,null);
view.setBackgroundResource(R.drawable.background_for_calendar);
toast1.setView(view);
toast1.show();
}
else {
for (int task = 0; task < delete_list.size(); task++) {
dataBaseHelper.deleteOneTask(labelName, Long.parseLong(delete_list.get(task)));
}
finish();
}
break;
case R.id.tool_bar_item2:
Boolean flag=dataBaseHelper.deleteAllCompletedTasks(labelName);
if(flag)
finish();
else
{
Toast toast2= new Toast(this);
toast2.setDuration(Toast.LENGTH_SHORT);
LayoutInflater inflater= (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view= inflater.inflate(R.layout.activity_toast_msg2,null);
view.setBackgroundResource(R.drawable.background_for_calendar);
toast2.setView(view);
toast2.show();
}
break;
}
return true;
}
}
I have added the code related to the scene transititon which is in the adapter.
here is a gif of the problem when i add a scene transition
enter image description here
As u can see there are 2 pauses when going from 1st to 2nd activity 1st pause being longer 2nd one shorter. And also a pause when exiting the 2nd activity which seems to have the same duration as the 2nd pause.
I'm basically working on incrementing, decrementing and removing items from cart in the Recyclerview. I have a general class called CategoryItem.java whose objects I'm passing through to the Main Recyclerview in the mainactivity which show my items (without the quantity) which starts the Cart Activity on a button click and I have passed the same list of CategoryItem objects to the cart on button click. Everything else is working fine except the Cart.java and CartItemRecyclerAdapter, I'm utilizing the quantity attribute of CategoryItem objects here only, now the issue is the item quantity does get incremented/decremented/removed when I click my imageviews but does not retain the values in the textviews (Quantity goes back to 1 and the price gets to original of each item in the cart) and if I had removed the item it appears back when I return from the MainActivity. Also, help me with the carttotal, it does not update when I try to from the CartItemRecyclerAdapter.
public class MainActivity extends AppCompatActivity {
RecyclerView mainrecyclerview;
MainRecyclerAdapter mainRecyclerAdapter;
RecyclerView categoryrecyclerview;
CategoryItemRecyclerAdapter categoryItemRecyclerAdapter;
TextView menu ;
DrawerLayout drawerLayout;
NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
menu = findViewById(R.id.textView);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.drawer);
ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.navigation_drawer_open,R.string.navigation_drawer_close);
drawerToggle.setDrawerIndicatorEnabled(false);
drawerToggle.setHomeAsUpIndicator(ResourcesCompat.getDrawable(getResources(), R.drawable.ic_baseline_account_circle_24,getTheme()));
drawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
drawerLayout.openDrawer(GravityCompat.START);
}
}
});
drawerToggle.syncState();
ImageView cartViewButton = toolbar.findViewById(R.id.viewCartButton);
cartViewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),Cart.class);
startActivity(intent);
}
});
List<CategoryItem> soupItemList = new ArrayList<>();
soupItemList.add(new CategoryItem("Chicken Corn",30,R.drawable.soup1));
soupItemList.add(new CategoryItem("Hot & Sour",100,R.drawable.hotnsour));
soupItemList.add(new CategoryItem("Chinese Rice",500,R.drawable.soup3));
soupItemList.add(new CategoryItem("Chicken Noodle",800,R.drawable.soup4));
List<CategoryItem> seafoodItemList = new ArrayList<>();
seafoodItemList.add(new CategoryItem("Chilli Prawns",750,R.drawable.chilliprawn));
seafoodItemList.add(new CategoryItem("Dragon Prawns",750,R.drawable.dragonprawn));
seafoodItemList.add(new CategoryItem("Red Roast Prawns",750,R.drawable.redroastprawn));
seafoodItemList.add(new CategoryItem("Hot & Spicy Fish",750,R.drawable.hotnspicyfish));
List<CategoryItem> poultryItemList = new ArrayList<>();
List<AllCategory> allCategoryList = new ArrayList<>();
allCategoryList.add(new AllCategory("SOUPS",soupItemList));
allCategoryList.add(new AllCategory("SEAFOOD",seafoodItemList));
//allCategoryList.add(new AllCategory("Sizzlers"));
setMainrecyclerview(allCategoryList);
}
private void closeDrawer(){
drawerLayout.closeDrawer(GravityCompat.START);}
private void openDrawer(){
drawerLayout.openDrawer(GravityCompat.START);
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)){
closeDrawer();
}
super.onBackPressed();
}
private void setMainrecyclerview(List<AllCategory> allCategoryList){
mainrecyclerview = findViewById(R.id.mainCatRecycler);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
mainrecyclerview.setLayoutManager(layoutManager);
mainRecyclerAdapter = new MainRecyclerAdapter(MainActivity.this,allCategoryList);
mainrecyclerview.setAdapter(mainRecyclerAdapter);
}
}
public class Cart extends AppCompatActivity {
Toolbar toolbar;
RecyclerView cartRecyclerview;
CartItemRecyclerAdapter cartItemRecyclerAdapter;
static TextView bill;
int billtotal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
toolbar = findViewById(R.id.carttoolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Cart");
bill = findViewById(R.id.bill);
setCartRecyclerview(getArrayList("key"));
cartItemRecyclerAdapter.updatecarttotal();
bill.setText(""+cartItemRecyclerAdapter.cartTotal);
}
public List<CategoryItem> getArrayList(String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Gson gson = new Gson();
String json = prefs.getString(key, null);
Type type = new TypeToken<List<CategoryItem>>() {}.getType();
return gson.fromJson(json, type);
}
public void setCartRecyclerview(List<CategoryItem> cartitem){
cartRecyclerview = findViewById(R.id.recyclerView);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(Cart.this);
cartRecyclerview.setLayoutManager(layoutManager);
cartItemRecyclerAdapter = new CartItemRecyclerAdapter(Cart.this,cartitem);
cartRecyclerview.setAdapter(cartItemRecyclerAdapter);
}
}
public class CartItemRecyclerAdapter extends RecyclerView.Adapter<CartItemRecyclerAdapter.CartItemViewHolder> {
Context context;
List<CategoryItem> cartitems;
CartItem quantity;
int cartTotal=0;
public CartItemRecyclerAdapter(Context context, List<CategoryItem> cartitems) {
this.context = context;
this.cartitems = cartitems;
this.quantity = new CartItem(1);
}
#NonNull
#Override
public CartItemRecyclerAdapter.CartItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new CartItemRecyclerAdapter.CartItemViewHolder(LayoutInflater.from(context).inflate(R.layout.cartitem, parent, false));
}
#Override
public void onBindViewHolder(#NonNull CartItemViewHolder holder, int position) {
holder.cartitem.setActivated(true);
holder.cartItemname.setText(cartitems.get(position).getName());
holder.cartItemimage.setImageResource(cartitems.get(position).getImageURI());
holder.cartItemprice.setText("Rs. " + cartitems.get(position).getPrice() * cartitems.get(position).getQuantity());
holder.cartItemquantity.setText("" + cartitems.get(position).getQuantity());
updatecarttotal();
holder.plusimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cartitems.get(position).quantity++;
holder.cartItemquantity.setText(""+cartitems.get(position).getQuantity());
holder.cartItemprice.setText("Rs. " + cartitems.get(position).getPrice()*cartitems.get(position).getQuantity());
updatecarttotal();
}
});
holder.minusimagem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cartitems.get(position).quantity--;
holder.cartItemquantity.setText(""+cartitems.get(position).getQuantity());
holder.cartItemprice.setText("Rs. " + cartitems.get(position).getPrice()*cartitems.get(position).quantity);
updatecarttotal();
if (cartitems.get(position).getQuantity() == 0) {
cartitems.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, cartitems.size());
updatecarttotal();
} else {
updatecarttotal();
}
}
});
holder.crossimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cartitems.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, cartitems.size());
updatecarttotal();
}
});
}
public void updatecarttotal() {
for (int i = 0; i < cartitems.size(); i++) {
cartTotal += cartitems.get(i).getPrice()*quantity.quantity;
}}
#Override
public int getItemCount() {
return cartitems.size();
}
public static final class CartItemViewHolder extends RecyclerView.ViewHolder{
ImageView cartItemimage , plusimage, minusimagem, crossimage;
TextView cartItemname, cartItemprice,cartItemquantity, billtotal;
CardView cartitem;
public CartItemViewHolder(#NonNull View itemView) {
super(itemView);
cartitem = itemView.findViewById(R.id.cartitemcardview);
cartItemimage = itemView.findViewById(R.id.cart_itemimage);
plusimage = itemView.findViewById(R.id.plus);
minusimagem =itemView.findViewById(R.id.minus);
crossimage = itemView.findViewById(R.id.remove);
cartItemname = itemView.findViewById(R.id.cartitemname);
cartItemprice = itemView.findViewById(R.id.cartitemprice);
cartItemquantity = itemView.findViewById(R.id.quantity);
}
}
}'''
public class CategoryItem {
String name;
int imageURI,price;
int quantity;
public CategoryItem(String name, int price, int imageURI) {
this.name = name;
this.price = price;
this.imageURI = imageURI;
this.quantity = 1;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getImageURI() {
return imageURI;
}
public void setImageURI(int imageURI) {
this.imageURI = imageURI;
}}`
Consider storing your state in a viewmodel class using a live data, then you can observe for changes in your data and update your ui accordingly.
Hello can I ask why my search view isn't filtering the list of data when searching on the fragments recyclerview and Also when I click the fragments activity again after trying to search it would result into an error
java.lang.NullPointerException: Attempt to invoke interface method
'void java.util.List.add(int, java.lang.Object)' on a null object
reference at
com.google.firebase.ikuzou.database.MemberDetailAdapter$UserChildEventListener.onChildAdded(MemberDetailAdapter.java:73)
RecyclerView Adapter
public class MemberDetailAdapter extends RecyclerView.Adapter<MemberDetailAdapter.ViewHolder> implements Filterable {
private List<User1> mUser,nUser;
private Callback mCallback;
private DatabaseReference userref;
public MemberDetailAdapter(Callback callback) {
mCallback = callback;
mUser = new ArrayList<>();
userref = FirebaseDatabase.getInstance().getReference().child("Accounts").child("Users");
userref.addChildEventListener(new UserChildEventListener());
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()){
mUser=nUser;
}else {
List<User1> filteredList = new ArrayList<>();
for (User1 row : nUser){
if (row.getFirst().toLowerCase().contains(charString.toLowerCase()) || row.getSecond().contains(charSequence)){
filteredList.add(row);
}
}
mUser=filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = mUser;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
}
};
}
class UserChildEventListener implements ChildEventListener{
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
User1 user = dataSnapshot.getValue(User1.class);
user.setKey(dataSnapshot.getKey());
mUser.add(0,user);
notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
String key = dataSnapshot.getKey();
User1 updatedUser = dataSnapshot.getValue(User1.class);
for (User1 user : mUser){
if (user.getKey().equals(key)){
user.setValues(updatedUser);
notifyDataSetChanged();
return;
}
}
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
String key = dataSnapshot.getKey();
for(User1 user: mUser){
if (user.getKey().equals(key)){
mUser.remove(user);
break;
}
}
notifyDataSetChanged();
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.model, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final User1 user = mUser.get(position);
holder.mfirstNameTextView.setText(user.getFirst());
holder.msecondNameTextView.setText(user.getSecond());
holder.mnumberTextView.setText(user.getNumber());
holder.mgenderTextView.setText(user.getGender());
holder.mEmailTextView.setText(user.getEmail());
holder.mDateTextView.setText(user.getDate());
holder.mTypeTextView.setText(user.getType());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallback.onEdit(user);
}
});
}
public void remove(User1 user) {
//TODO: Remove the next line(s) and use Firebase instead
userref.child(user.getKey()).removeValue();
}
#Override
public int getItemCount() {
if(mUser==null){
Log.v("LOG","Warn, null filteredData");
return 0;
}else{
return mUser.size();
}
}
public void add(User1 user) {
//TODO: Remove the next line(s) and use Firebase instead
userref.push().setValue(user);
}
public void update(User1 user, String newFirst,String newSecond, String newNumber, String newGender,String newDate) {
//TODO: Remove the next line(s) and use Firebase instead
user.setFirst(newFirst);
user.setSecond(newSecond);
user.setNumber(newNumber);
user.setGender(newGender);
user.setDate(newDate);
userref.child(user.getKey()).setValue(user);
}
public interface Callback {
public void onEdit(User1 user);
}
class ViewHolder extends RecyclerView.ViewHolder {
private TextView mfirstNameTextView;
private TextView msecondNameTextView;
private TextView mnumberTextView;
private TextView mgenderTextView;
private TextView mEmailTextView;
private TextView mDateTextView;
private TextView mTypeTextView;
public ViewHolder(View itemView) {
super(itemView);
mfirstNameTextView = (TextView) itemView.findViewById(R.id.firstnameTxt);
msecondNameTextView = (TextView) itemView.findViewById(R.id.lastnameTxt);
mnumberTextView = (TextView) itemView.findViewById(R.id.numberTxt);
mgenderTextView = (TextView) itemView.findViewById(R.id.genderTxt);
mEmailTextView = (TextView) itemView.findViewById(R.id.emailTxt);
mDateTextView = (TextView) itemView.findViewById(R.id.dateTxt);
mTypeTextView = (TextView) itemView.findViewById(R.id.typeTxt);
}
}
My Fragment code
public class memberFragment extends Fragment implements MemberDetailAdapter.Callback, SearchView.OnQueryTextListener {
private ListView mylistView;
private DatabaseReference db;
private Firebasehelper helper;
private CustomAdapter adapter;
private ListView lv;
private com.google.firebase.ikuzou.database.MemberDetailAdapter mAdapter;
public memberFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_member2, container, false);
mAdapter = new com.google.firebase.ikuzou.database.MemberDetailAdapter(this);
setHasOptionsMenu(true);
RecyclerView view1 = (RecyclerView) view.findViewById(R.id.recycler_view);
view1.setLayoutManager(new LinearLayoutManager(getContext()));
view1.setHasFixedSize(true);
view1.setAdapter(mAdapter);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.search_menu, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setOnQueryTextListener(this);
super.onCreateOptionsMenu(menu, inflater);
super.onCreateOptionsMenu(menu, inflater);
}
private void showAddEditDialog(final User1 user) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(getString(user == null ? R.string.dialog_add_title : R.string.dialog_edit_title));
View view = getLayoutInflater().inflate(R.layout.input_dialog, null, false);
builder.setView(view);
final EditText firstnameEditText = (EditText) view.findViewById(R.id.firstnameEditText);
final EditText secondnameEditText = (EditText) view.findViewById(R.id.secondnameEditText);
final EditText numberEditText = (EditText) view.findViewById(R.id.numberEditText);
final EditText genderEditText = (EditText) view.findViewById(R.id.genderEditText);
final EditText emailEditText = (EditText) view.findViewById(R.id.emailEditText);
final EditText dateEditText = (EditText) view.findViewById(R.id.dateEditText);
final TextView typeEditText = (TextView) view.findViewById(R.id.typeEditText);
if (user != null) {
// pre-populate
firstnameEditText.setText(user.getFirst());
secondnameEditText.setText(user.getSecond());
numberEditText.setText(user.getNumber());
genderEditText.setText(user.getGender());
emailEditText.setText(user.getEmail());
dateEditText.setText(user.getDate());
typeEditText.setText(user.getType());
TextWatcher textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// empty
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// empty
}
#Override
public void afterTextChanged(Editable s) {
String firstname = firstnameEditText.getText().toString();
String secondname = secondnameEditText.getText().toString();
String number = numberEditText.getText().toString();
String gender = genderEditText.getText().toString();
String date = dateEditText.getText().toString();
mAdapter.update(user, firstname,secondname,number,gender,date );
}
};
firstnameEditText.addTextChangedListener(textWatcher);
secondnameEditText.addTextChangedListener(textWatcher);
numberEditText.addTextChangedListener(textWatcher);
genderEditText.addTextChangedListener(textWatcher);
emailEditText.addTextChangedListener(textWatcher);
dateEditText.addTextChangedListener(textWatcher);
}
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (user == null) {
String firstname = firstnameEditText.getText().toString();
String secondname = secondnameEditText.getText().toString();
String number = numberEditText.getText().toString();
String gender = genderEditText.getText().toString();
String email = emailEditText.getText().toString();
String date = dateEditText.getText().toString();
mAdapter.add(new User1(firstname,secondname,number,gender, date, email));
}
}
});
builder.setNegativeButton(android.R.string.cancel, null);
builder.create().show();
// Inflate the layout for this fragment
}
#Override
public void onEdit(final User1 user) {
showAddEditDialog(user);
}
#Override
public boolean onQueryTextSubmit(String query) {
mAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String query) {
mAdapter.getFilter().filter(query);
return false;
}
Before all of this happen I have a
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()'
But changing my getItemcount into
public int getItemCount() {
if(mUser==null){
Log.v("LOG","Warn, null filteredData");
return 0;
}else{
return mUser.size();
}
}
From
public int getItemCount() {
return mUser.size();
}
Fixed the problem.