Please help me. I want to show the username only once from firebase. Although the user have multiple record in the firebase, I just want to view the name of user who make order. The user can make multiple order, but I just want to show their name once.
I tried many ways but can't succeed. Someone who know about this? Thank you very much.
public void onCreate(Bundle savedInstanceState) {
UID = this.getArguments().getString("UID");
mDatabase = FirebaseDatabase.getInstance().getReference();
mStorage = FirebaseStorage.getInstance();
mItems = new ArrayList<>();
wordDulicate = new ArrayList<>();
tempList = new ArrayList<>();
if(UID != null){
mItemsKey = new ArrayList<>();
mOrderedItemRef = mDatabase.child("OrderedItem");
Log.d(TAG, " mOrderedItemRef:" + mOrderedItemRef);
mOrderedItemVEL = mOrderedItemRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mItems.clear();
mItemsKey.clear();
wordDulicate.clear();
Log.d(TAG, "onDataChange");
for (DataSnapshot d : dataSnapshot.getChildren()) {
OrderedItem orderedItem = d.getValue(OrderedItem.class);
Log.d(TAG, "orderedItem:" + orderedItem.getUserName());
mItems.add(orderedItem);
mItemsKey.add(d.getKey());
}
updateUI();
}
#Override
public void onCancelled (DatabaseError databaseError){
Log.d(TAG, "get item databaseError: "+databaseError);
}
});
}
else{
Log.d(TAG, "UID: "+UID);
}
super.onCreate(savedInstanceState);
}
#Override
public void onDestroy(){
super.onDestroy();
// if (mItemRef != null) mItemRef.removeEventListener(mItemVEL);
}
#Override
public void onDetach(){
super.onDetach();
// if (mItemRef != null) mItemRef.removeEventListener(mItemVEL);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_admin_list_user_order, container, false);
mItemRecyclerView = (RecyclerView) view.findViewById(R.id.admin_order_recycler_view);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mItemRecyclerView.getContext(), new LinearLayoutManager(getActivity()).getOrientation());
mItemRecyclerView.addItemDecoration(dividerItemDecoration);
mItemRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
private void updateUI(){
Log.d(TAG, "Enter updateUI(); mItems: " + mItems);
mAdapter = new ItemAdapter(mItems);
mItemRecyclerView.setAdapter(mAdapter);
}
private class ItemHolder extends RecyclerView.ViewHolder{
OrderedItem mItems;
TextView mNameTextView;
ItemHolder(final View itemView){
super(itemView);
mNameTextView = (TextView) itemView.findViewById(R.id.textview_username);
/* if (UID != null) {
itemView.setOnClickListener(new View.OnClickListener() {
#SuppressLint("LongLogTag")
#Override
public void onClick(View view) {
Log.d(TAG, "UID != null");
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder
.setMessage("Delete This Item?")
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
deleteItem(mItems);
}
}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
}*/
}
void bindData(OrderedItem s){
mItems = s;
mNameTextView.setText(s.getUserName());
}
}
private class ItemAdapter extends RecyclerView.Adapter<ItemHolder>{
private ArrayList<OrderedItem> mItems;
ItemAdapter(ArrayList<OrderedItem> Items){
mItems = Items;
}
#Override
public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.admin_listed_user_order,parent,false);
return new ItemHolder(view);
}
#Override
public void onBindViewHolder(ItemHolder holder, int position) {
OrderedItem s = mItems.get(position);
holder.bindData(s);
}
#Override
public int getItemCount() {
return mItems.size();
}
}
}
Since you rely on a key and a value, why not use a map instead? Maps have a key and a value, and you can check whether or not an item with a key is present by getting the key, instead of having to iterate through the list and find duplicates.
First you need to initialize it:
Map<String, ArrayList<OrderedItem>> items = new HashMap<>();
The value is an ArrayList to keep any existing data
then put the items:
for (DataSnapshot d : dataSnapshot.getChildren()) {
OrderedItem orderedItem = d.getValue(OrderedItem.class);
Log.d(TAG, "orderedItem:" + orderedItem.getUserName());
items.putIfAbsent(d.getKey(), new ArrayList<>());//create a list if it doesn't exist
items.get(d.geyKey()).add(orderedItem);//add the item
}
and clearing with a map is the same as with lists
Related
I am new to android studio and currently watching tutorials. As of now I have a Shopping cart activity where I can increment, decrement and delete items in cart. The thing is whenever I delete, add or deduct an item, the cart values does not update. I still need to change activities to see the changes. Also the item that I deleted still appears at the bottom of recyclerview items after the dialog appearance unless I change the activity and go back. Please help me how to apply real time update. Below are my class files for the cart activity and adapter class.
CartActivity.java
#Override
protected void onStop() {
if (EventBus.getDefault().hasSubscriberForEvent(MyUpdateCartEvent.class))
EventBus.getDefault().removeStickyEvent(MyUpdateCartEvent.class);
EventBus.getDefault().unregister(this);
super.onStop();
}
#Subscribe(threadMode = ThreadMode.MAIN_ORDERED, sticky = true)
public void onUpdateCart(MyUpdateCartEvent event) {
loadCartFromFirebase();
}
private void loadCartFromFirebase() {
fAuth = FirebaseAuth.getInstance();
if(fAuth.getCurrentUser() != null){
userId = fAuth.getCurrentUser().getUid();
} else {
userId = "UNIQUE_USER_ID";
}
List<CartModel> cartModels = new ArrayList<>();
FirebaseDatabase.getInstance()
.getReference("cart")
.child(userId)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
for (DataSnapshot cartSnapshot : snapshot.getChildren()) {
CartModel cartModel = cartSnapshot.getValue(CartModel.class);
cartModel.setKey(cartSnapshot.getKey());
cartModels.add(cartModel);
}
cartLoadListener.onCartLoadSuccess(cartModels);
} else {
cartLoadListener.onCartLoadFailed("Cart Empty");
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
cartLoadListener.onCartLoadFailed(error.getMessage());
}
});
}
private void init() {
ButterKnife.bind(this);
cartLoadListener = this;
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recycler_cart.setLayoutManager(layoutManager);
purchScrnBtn.setOnClickListener(v -> startActivity(new Intent(this, PurchaseActivity.class)));
}
#Override
public void onCartLoadSuccess(List<CartModel> cartModelList) {
double sum = 0;
for (CartModel cartModel : cartModelList) {
sum += cartModel.getTotalPrice();
}
textTotal.setText(new StringBuilder("$").append(sum));
MyCartAdapter adapter = new MyCartAdapter(this, cartModelList);
recycler_cart.setAdapter(adapter);
}
MyCartAdapter.java
package com.example.cart.adapter;
public class CartActivity extends AppCompatActivity implements CartLoadListener {
public MyCartViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new MyCartViewHolder(LayoutInflater.from(context)
.inflate(R.layout.layout_cart_item, parent, false));
}
#Override
public void onBindViewHolder(#NonNull MyCartViewHolder holder, int position) {
holder.minus.setOnClickListener(v -> {
minusCartItem(holder,cartModelList.get(position));
});
holder.delete.setOnClickListener(v -> {
AlertDialog dialog = new AlertDialog.Builder(context)
.setTitle("Delete item")
.setMessage("Do you really want to delete item")
.setNegativeButton("CANCEL", (dialogInterface, i) -> dialogInterface.dismiss())
.setPositiveButton("OK", (dialogInterface2, i) -> {
//Temp remove
notifyItemRemoved(position);
deleteFromFirebase(cartModelList.get(position));
dialogInterface2.dismiss();
}).create();
dialog.show();
});
}
private void deleteFromFirebase(CartModel cartModel) {
FirebaseDatabase.getInstance()
.getReference("cart")
.child(userId)
.child(cartModel.getKey())
.removeValue()
.addOnSuccessListener(aVoid -> EventBus.getDefault().postSticky(new MyUpdateCartEvent()));
}
#SuppressLint("SuspiciousIndentation")
private void minusCartItem(MyCartViewHolder holder, CartModel cartModel) {
if(cartModel.getQuantity() > 1)
cartModel.setQuantity(cartModel.getQuantity()-1);
cartModel.setTotalPrice(cartModel.getQuantity()*Float.parseFloat(cartModel.getPrice()));
//update quantity
holder.txtQuantity.setText(new StringBuilder().append(cartModel.getQuantity()));
updateFirebase(cartModel);
}
public class MyCartViewHolder extends RecyclerView.ViewHolder{
Unbinder unbinder;
public MyCartViewHolder(#NonNull View itemView) {
super(itemView);
unbinder = ButterKnife.bind(this, itemView);
}
}
}
The thing is whenever I delete, add or deduct an item, the cart values does not update.
That's because you load data from Firebase with addListenerForSingleValueEvent, which only loads the data when you call it. If you want to continue to monitor the data for changes, use addValueEventListener instead.
I have a recyclerview. There are city names in the recyclerview and when I long click, I want to delete it from the recyclerview. I wrote some code in adapter class. When I click on the city names, I can delete them, but when I view the recyclerview again, the city names I deleted appear again. How can I fix this ?
My adapter class
public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> {
ArrayList<City> arrayList;
Context context;
public Adapter(ArrayList<City> arrayList ,Context context ){
this.arrayList = arrayList;
this.context = context;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
RecyclerviewRowBinding recyclerviewRowBinding = RecyclerviewRowBinding.inflate(LayoutInflater.from(parent.getContext()),parent,false);
return new MyViewHolder(recyclerviewRowBinding);
}
#Override
public void onBindViewHolder(#NonNull Adapter.MyViewHolder holder, int position) {
holder.binding.MytxtCities.setText(arrayList.get(position).cityName);
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setIcon(R.drawable.warningicon);
builder.setMessage("Are you sure that you want to delete "+arrayList.get(position).cityName);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
arrayList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position,arrayList.size());
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
return true;
}
});
holder.itemView.setOnClickListener(v -> {
Intent intent = new Intent(holder.itemView.getContext(),MainActivity.class);
intent.putExtra("citId",arrayList.get(position).id);
holder.itemView.getContext().startActivity(intent);
});
}
#Override
public int getItemCount() {
return arrayList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView Mytxt_cities;
private RecyclerviewRowBinding binding;
public MyViewHolder(#NonNull RecyclerviewRowBinding binding) {
super(binding.getRoot());
this.binding = binding;
Mytxt_cities = itemView.findViewById(R.id.Mytxt_cities);
}
}
}
My recyclerview class is cities class
public class cities extends AppCompatActivity {
RecyclerView recyclerView ;
ArrayList<City> cityArrayList;
Adapter cityadapter;
ImageView cities_back_icon;
public void init(){
cities_back_icon = findViewById(R.id.Id_cities_back_icon);
cities_back_icon_click_register();
cityArrayList = new ArrayList<>();
recyclerView = findViewById(R.id.recyclerview_id);
SQLGet_Data();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cities);
init();
}
private void cities_back_icon_click_register(){
cities_back_icon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(cities.this, MainActivity.class);
startActivity(intent);
}
});
}
private void SQLGet_Data(){
try {
SQLiteDatabase sqLiteDatabase = this.openOrCreateDatabase("City",MODE_PRIVATE,null);
Cursor cursor = sqLiteDatabase.rawQuery("SELECT*FROM city",null);
int idIx = cursor.getColumnIndex("id");
int nameIx = cursor.getColumnIndex("cityname");
while(cursor.moveToNext()){
String cityname = cursor.getString(nameIx);
int id = cursor.getInt(idIx);
City city = new City(cityname,id);
cityArrayList.add(city);
}
cityadapter.notifyDataSetChanged();
cursor.close();
}
catch (Exception e ){
e.printStackTrace();
}
/*---------------------- set recyclerview-----------------------------*/
recyclerView.setLayoutManager(new LinearLayoutManager(cities.this));
cityadapter = new Adapter(cityArrayList,this);
recyclerView.setAdapter(cityadapter);
/*--------------------------We drew a line between the data in the recyclerview------------------------------------*/
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), DividerItemDecoration.VERTICAL);
Drawable drawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.custom_divider);
dividerItemDecoration.setDrawable(drawable);
recyclerView.addItemDecoration(dividerItemDecoration);
}
}
The problem is that you are only deleting the cities from your ArrayList that is inside your adapter. But those cities still remain in your SQL database. Then when you restart the Activity your ArrayList will be created with the data of your SQL database, where those deleted cities still exist.
To delete cities consistently you need to delete the cities not only in your adapter but also in your SQL database.
I am trying to display data from my database in my fragment through recycler view. I used a for loop to go through all the users in my database. All the users who are neither friends nor have sent requests should be displayed as implemented in the if condition of fragment class. The code for fragment class is written below.
public class AddMemberFragment extends Fragment {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private View view ;
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
String userId;
String n_team ;
ArrayList<Friend> friends;
public AddMemberFragment() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.addnewfriend_fragment, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
userId = firebaseUser.getUid();
ManageTeamTabbedActivity activity = (ManageTeamTabbedActivity) getActivity();
n_team = activity.getMyData();
mRecyclerView = (RecyclerView) getView().findViewById(R.id.addNewFriend);
//mRecyclerView.setHasFixedSize(true);//
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
friends = new ArrayList<>();
mAdapter = new AddMemberAdapter(getActivity(), friends, n_team) ;
mRecyclerView.setAdapter(mAdapter);
mRootRef.child("users");
mRootRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ArrayList<Friend> friendArrayList = new ArrayList<>();
DataSnapshot friendsData = dataSnapshot.child(firebaseUser.getUid()).child("friends");
DataSnapshot requests = null;
DataSnapshot currentFriends = null;
if (friendsData.hasChild("requests")) {
requests = dataSnapshot.child(firebaseUser.getUid()).child("friends").child("requests");
}
if (friendsData.hasChild("currentFriends")) {
currentFriends = dataSnapshot.child(firebaseUser.getUid()).child("friends").child("currentFriends");
}
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
Log.d("demo", "USERID " + FirebaseAuth.getInstance().getCurrentUser().getUid());
Friend friend = new Friend();
if ((userSnapshot.getKey().equals(FirebaseAuth.getInstance().getCurrentUser().getUid())) || (requests != null && requests.hasChild(userSnapshot.getKey()))
|| (currentFriends != null && currentFriends.hasChild(userSnapshot.getKey()))) {
} else {
friend.setId(userSnapshot.getKey());
friend.setFriendName((String) userSnapshot.child("profiles").child("fname").getValue());
friendArrayList.add(friend);
}
}
friends = friendArrayList;
if (friends != null && !friends.isEmpty()) {
mAdapter.setFriendList(friends);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
And the corresponding adapter code is written here :
public class AddMemberAdapter extends RecyclerView.Adapter<AddMemberAdapter.RecyclerViewHolder>{
private ArrayList<Friend> mData;
private Context mContext;
private FirebaseAuth auth;
private String u_team ;
public AddMemberAdapter(Context mContext, ArrayList<Friend> friendList , String u_team) {
this.mData = friendList;
this.mContext = mContext;
this.u_team= u_team;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.addnewfriend_layout, parent, false);
AddMemberAdapter.RecyclerViewHolder viewHolder = new AddMemberAdapter.RecyclerViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, final int position) {
final Friend frnd =(Friend) mData.get(position);
holder.friendName.setText(frnd.getFriendName());
holder.addFriend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
frnd.setStatus("sent");
final DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
final String UID = firebaseUser.getUid();
mRootRef.child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mRootRef.child("users").child(UID).child("friends").child("requests").child(frnd.getId()).setValue(frnd);
Friend temp = new Friend();
temp.setId(firebaseUser.getUid());
temp.setFriendName(firebaseUser.getDisplayName());
temp.setStatus("received");
mRootRef.child("users").child(frnd.getId()).child("friends").child("requests").child(firebaseUser.getUid()).setValue(temp);
mData.remove(frnd);
notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
#Override
public int getItemCount() {
return mData.size();
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
TextView friendName;
ImageButton addFriend;
public RecyclerViewHolder(View itemView) {
super(itemView);
friendName = (TextView)itemView.findViewById(R.id.textViewFriendName);
addFriend = (ImageButton) itemView.findViewById(R.id.imagebuttonFriendAdd);
}
}
public void setFriendList(ArrayList<Friend> friendList){
this.mData = friendList;
notifyDataSetChanged();
}
}
The output I am getting is attached here.
Users who are not friends and have not been sent friend requests by the current user should have been displayed in this Add New Member fragment through this RecyclerView. I tried to debug it myself and removed the if condition but it did not work either. Please guide how to display it. The
The database screenshot is attached as well.
I could not find a problem with your firebase query and the data-extraction techniques, however, with this data structure, as the list grows you will have a difficult time getting the list of your friends. From my understanding, it is just taking a lot of time to display the list in that fragment.
Also, you might consider setting up the adapter with the RecyclerView while you are initializing the RecyclerView.
You might consider doing something like the following.
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
userId = firebaseUser.getUid();
ManageTeamTabbedActivity activity = (ManageTeamTabbedActivity) getActivity();
n_team = activity.getMyData();
mRecyclerView = (RecyclerView) getView().findViewById(R.id.addNewFriend);
// mRecyclerView.setHasFixedSize(true); // Remove this line
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
// Set the adapter here with an empty list first.
friends = new ArrayList<>();
mAdapter = new AddMemberAdapter(getActivity(), friends, n_team);
mRecyclerView.setAdapter(mAdapter);
mRootRef.child("users");
mRootRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ArrayList<Friend> friendArrayList = new ArrayList<>();
DataSnapshot friendsData = dataSnapshot.child(firebaseUser.getUid()).child("friends");
DataSnapshot requests = null;
DataSnapshot currentFriends = null;
if (friendsData.hasChild("requests")) {
requests = dataSnapshot.child(firebaseUser.getUid()).child("friends").child("requests");
}
if (friendsData.hasChild("currentFriends")) {
currentFriends = dataSnapshot.child(firebaseUser.getUid()).child("friends").child("currentFriends");
}
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
Log.d("demo", "USERID " + FirebaseAuth.getInstance().getCurrentUser().getUid());
Friend friend = new Friend();
if ((userSnapshot.getKey().equals(FirebaseAuth.getInstance().getCurrentUser().getUid())) || (requests != null && requests.hasChild(userSnapshot.getKey()))
|| (currentFriends != null && currentFriends.hasChild(userSnapshot.getKey()))) {
} else {
friend.setId(userSnapshot.getKey());
friend.setFriendName((String) userSnapshot.child("profiles").child("fname").getValue());
friendArrayList.add(friend);
}
}
friends = friendArrayList;
if (friends != null && !friends.isEmpty()) {
mAdapter.setFriendList(friends); // Set the friend list to the adapter when the list is loaded.
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
And in your adapter, you will need a function to set the friends' list and call notifyDataSetChanged().
// In your adapter class, add the following method.
public void setFriendList(ArrayList<Friend> friendList) {
this.mData = friendList;
notifyDataSetChanged();
}
I hope that helps.
i have a custom listview that has 3 textview for Name, Unique id and Number of Absent and 1 image button for Delete in every list item. I tried to sort the number of absent, it sorts but the order breaks. I saw in internet the comparator and i think that's the solution to my problem but i don't know how to use it. Hoping that someone here can help me.
This is how i add values in my 3 ArrayList (mUid for unique id, MFullname for name, mStatus for Number of absent)
pagod = FirebaseDatabase.getInstance().getReference().child("users").child("teacher").child(user.getUid().toString().trim()).child("class").child(aba).child(message).child("Listofstudents");
pagod.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
String userid = child.child("userid").getValue().toString().trim();
String name = child.child("name").getValue().toString().trim();
mUid.add(userid);
mFullname.add(name);
//studentlist.invalidateViews();
//adapter.notifyDataSetChanged();
if (dataSnapshot.child(userid).child("attendance").exists()) {
pagodnapagod = FirebaseDatabase.getInstance().getReference();
Query query = pagodnapagod.child("users").child("teacher").child(user.getUid().toString().trim()).child("class").child(aba).child(message).child("Listofstudents").child(userid).child("attendance").child("finals").orderByChild("status").equalTo("absent");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String numberOfStudent ="Number of Absent: "+dataSnapshot.getChildrenCount();
//Toast.makeText(MyClassesActivity.this, numberOfStudent, Toast.LENGTH_SHORT).show();
mStatus.add(numberOfStudent);
//Collections.sort(mStatus, Collections.reverseOrder());
adapters.notifyDataSetChanged();
progressDialog.dismiss();
} else {
String numberOfStudent = "Number of Absent: 0";
mStatus.add(numberOfStudent);
//Collections.sort(mStatus, Collections.reverseOrder());
adapters.notifyDataSetChanged();
progressDialog.dismiss();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
String numberOfStudent = "Number of Absent: 0";
mStatus.add(numberOfStudent);
//Collections.sort(mStatus, Collections.reverseOrder());
adapters.notifyDataSetChanged();
progressDialog.dismiss();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
This is my custom adapter.
class Adapters extends BaseAdapter implements Filterable {
private Context context;
private int resource;
private int ids;
private ArrayList arrayList;
private List<String> originalData=null;
private List<String>filteredData=null;
private List<String> userId;
private List<String> status;
private FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
private Adapters.ItemFilter mFilter = new Adapters.ItemFilter();
private LayoutInflater inflater;
public Adapters(Context context, int resource, int id, ArrayList arrayList, ArrayList userId, ArrayList status){
this.context = context;
this.resource = resource;
this.ids = id;
this.arrayList = arrayList;
this.filteredData = arrayList ;
this.originalData = arrayList ;
this.userId = userId;
this.status = status;
inflater = LayoutInflater.from(context);
}
public int getCount() {
return filteredData.size();
}
public Object getItem(int position) {
return filteredData.get(position);
}
public long getItemId(int position) {
return position;
}
// Hold views of the ListView to improve its scrolling performance
private class ViewHolder {
public TextView type;
public TextView uid;
public TextView count;
public ImageButton removeButton;
}
public View getView(final int position, final View convertView, ViewGroup parent) {
View rowView = convertView;
// Inflate the list_item.xml file if convertView is null
if(rowView==null){
rowView = inflater.inflate(R.layout.listitem6, null);
rowView= inflater.inflate(resource, parent, false);
Adapters.ViewHolder viewHolder = new Adapters.ViewHolder();
viewHolder.type= (TextView) rowView.findViewById(R.id.txt);
viewHolder.uid= (TextView) rowView.findViewById(R.id.id);
viewHolder.count= (TextView) rowView.findViewById(R.id.count);
viewHolder.removeButton= (ImageButton) rowView.findViewById(btn_del);
rowView.setTag(viewHolder);
}
final String x = (String) arrayList.get(position);
final String y = arrayList.get(position).toString().trim();
// Set text to each TextView of ListView item
Adapters.ViewHolder holder = (Adapters.ViewHolder) rowView.getTag();
holder.type.setText(x);
holder.uid.setText(x);
holder.count.setText(x);
holder.removeButton.setBackgroundResource(R.drawable.deletes);
holder.removeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
View parentRow = (View) view.getParent();
ListView listView = (ListView) parentRow.getParent();
final int position = listView.getPositionForView(parentRow);
TextView userId=(TextView) parentRow.findViewById(R.id.id);
TextView userName=(TextView) parentRow.findViewById(R.id.txt);
final String name = userName.getText().toString().trim();
final String uid = userId.getText().toString().trim();
//Toast.makeText(StudentListActivity.this, name +"\n" + uid, Toast.LENGTH_SHORT).show();
final AlertDialog.Builder builder2=new AlertDialog.Builder(context);
final View dialogView = inflater.inflate(R.layout.customdialog, null);
builder2.setView(dialogView);
final EditText input = (EditText) dialogView.findViewById(R.id.edit1);
final TextInputLayout inputs = (TextInputLayout) dialogView.findViewById(R.id.text_field);
TextWatcher watcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
inputs.setErrorEnabled(false);
inputs.setError(null);
}
};
input.addTextChangedListener(watcher);
builder2.setTitle("Delete Class");
builder2.setMessage("Do you want to delete "+y+" from this class?");
builder2.setPositiveButton("ok", null);
builder2.setNegativeButton("cancel", null);
builder2.setIcon(R.drawable.deletes);
builder2.setCancelable(false);
final AlertDialog mAlertDialog = builder2.create();
mAlertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(final DialogInterface dialog) {
Button a = mAlertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// TODO Do something
if (input.getText().toString().equalsIgnoreCase("delete")) {
arrayList.remove(position);
notifyDataSetChanged();
Toast.makeText(view.getContext(), y + " has been deleted in this class", Toast.LENGTH_SHORT).show();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("users").child("teacher").child(user.getUid().toString().trim()).child("class").child(aba).child(message).child("Listofstudents").child(uid);
mDatabase.setValue(null);
ref0 = FirebaseDatabase.getInstance().getReference();
ref0.child("usersclass").orderByChild("userid_classid").equalTo(uid+"-"+message).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
String hello = child.getKey();
ref0.child("usersclass").child(hello).setValue(null);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
dialog.dismiss();
notifyDataSetChanged();
restartThis();
} else {
inputs.setError("Enter word DELETE");
}
}
});
Button b = mAlertDialog.getButton(AlertDialog.BUTTON_NEGATIVE);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// TODO Do something
dialog.dismiss();
}
});
}
});
mAlertDialog.show();
}
});
holder.type.setText(filteredData.get(position));
holder.uid.setText(userId.get(position));
holder.count.setText(status.get(position));
return rowView;
}
public Filter getFilter() {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<String> list = originalData;
int count = list.size();
final ArrayList<String> nlist = new ArrayList<String>(count);
String filterableString ;
for (int i = 0; i < count; i++) {
filterableString = list.get(i);
if (filterableString.toLowerCase().contains(filterString)) {
nlist.add(filterableString);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
}
Can anyone check if there are errors in it. here my code, If there is any error in the code please tell me? I don't know how to fix the code Search.java.
in my RecyclerItemClickListener.java
public interface RecyclerItemClickListener {
void onItemClick(int position);
}
My Adapter HierAdapter.java
public class HireAdapter extends RecyclerView.Adapter<HireAdapter.ViewHolder>{
private ArrayList<HireItem> TeacherItemList;
private Context context;
private RecyclerItemClickListener itemClickListener;
public HireAdapter(Context c, ArrayList<HireItem> teacherItemList, RecyclerItemClickListener listener) {
TeacherItemList = teacherItemList;
context = c;
itemClickListener = listener;
}
public static class ViewHolder extends RecyclerView.ViewHolder{
public final TextView nameText, subjectText,levelText ,cityText;
public ViewHolder(View itemView) {
super(itemView);
nameText = (TextView)itemView.findViewById(R.id.result_name);
subjectText = (TextView)itemView.findViewById(R.id.result_subject);
levelText = (TextView)itemView.findViewById(R.id.result_level);
cityText = (TextView)itemView.findViewById(R.id.result_city);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rowView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_teachers,parent,false);
final ViewHolder viewHolder = new ViewHolder(rowView);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemClickListener.onItemClick(viewHolder.getLayoutPosition());
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.nameText.setText(TeacherItemList.get(position).getResult_name());
holder.subjectText.setText(TeacherItemList.get(position).getResult_subject());
holder.levelText.setText(TeacherItemList.get(position).getResult_level());
holder.cityText.setText(TeacherItemList.get(position).getResult_city());
//Here it is simply write onItemClick listener here
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, ProfileTeaAdapter.class);
context.startActivity(intent);
}
});
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public int getItemCount() {
return TeacherItemList.size();
}}
Here Search.java, I wrote notes at each error. Because I did not know how to correct some codes to work with HireAdapter and RecyclerItemClickListener, can anyone solve the error?
public class Search extends Fragment implements RecyclerItemClickListener {
private Context context;
private RecyclerView recyclerView;
private DatabaseReference databaseReference;
private FirebaseAuth firebaseAuth;
private List<HireItem> hireItem = new ArrayList<>();
HireAdapter mAdapter;
ImageView bt_search;
ProgressDialog progressDialog;
Spinner spinner_sort;
String key = "req_skill1";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_search,container,false);
//Getting FireBase Instance
firebaseAuth = FirebaseAuth.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference("teachers");
//Getting id of Views
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.rv_places);
recyclerView.setAdapter(mAdapter);
//
bt_search = (ImageView)view.findViewById(R.id.bt_search);
spinner_sort = (Spinner)view.findViewById(R.id.spinner_sort);
setupSpinner();
List<HireItem> hireItem = new ArrayList<>();
mAdapter = new HireAdapter(getContext(),R.layout.list_item_teachers,hireItem); // error at (getContext(),R.layout.list_item_teachers,hireItem)
bt_search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mAdapter != null){
mAdapter.clear(); // error at .clear();
}
progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Searching Teachers");
progressDialog.show();
FirebaseDatabase.getInstance().getReference("teachers").orderByChild("subject").startAt(key).endAt(key + "~")
.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Teachers child = dataSnapshot.getValue(Teachers.class);
HireItem hireItem = new HireItem(child.teaname, child.city, child.subject, child.level, child.sex,child.mobile, child.qualification, child.skill1, child.experince, child.salary,child.age);
mAdapter.add(hireItem); // error at .add
progressDialog.dismiss();
if(mAdapter == null){
Toast.makeText(getContext(), "No Match Found", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
if(mAdapter == null){
Toast.makeText(getContext(), "No Match Found", Toast.LENGTH_SHORT).show();
}
else{
recyclerView.setAdapter(mAdapter); // error at recyclerView
}
}
});
return view;
}
private void setupSpinner(){
ArrayAdapter adapter = ArrayAdapter.createFromResource(getContext(),R.array.array_teacher_sort,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner_sort.setAdapter(adapter);
spinner_sort.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
key = (String)adapterView.getItemAtPosition(i);
if(key.equals(getString(R.string.sort_A))){
key = "Math";
}else if(key.equals(getString(R.string.sort_AA))){
key = "computer";
}
else if(key.equals(getString(R.string.sort_AB))){
key = "Biology";
}
else if(key.equals(getString(R.string.sort_AD))){
key = "Physics";
}
else if(key.equals(getString(R.string.sort_AXX))){
key = "Holy Quran";
}
else if(key.equals(getString(R.string.sort_AZ))){
key = "Chysics";
}
else if(key.equals(getString(R.string.sort_AS))){
key = "English";
}
else if(key.equals(getString(R.string.sort_AQ))){
key = "Arabic";
}
else if(key.equals(getString(R.string.sort_ADD))){
key = "Science";
}
else if(key.equals(getString(R.string.sort_AE))){
key = "History";
}
else if(key.equals(getString(R.string.sort_AW))){
key = "Geograpghy";
}
else if(key.equals(getString(R.string.sort_AR))){
key = "Art education";
}
else if(key.equals(getString(R.string.sort_AT))){
key = "Family education";
}
else if(key.equals(getString(R.string.sort_aae))){
key = "Religion";
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public void onResume() {
super.onResume();
mAdapter.clear(); // error at .clear();
}
#Override
public void onItemClick(int position) {
} }
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rowView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_teachers,parent,false);
final ViewHolder viewHolder = new ViewHolder(rowView);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemClickListener.onItemClick(viewHolder.getLayoutPosition());
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.nameText.setText(TeacherItemList.get(position).getResult_name());
holder.subjectText.setText(TeacherItemList.get(position).getResult_subject());
holder.levelText.setText(TeacherItemList.get(position).getResult_level());
holder.cityText.setText(TeacherItemList.get(position).getResult_city());
//Here it is simply write onItemClick listener here
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, ProfileTeaAdapter.class);
context.startActivity(intent);
}
});
}
Here you are setting onClickListner on the same view twice. The Listener set in the onBindViewHolder will override the Listner set in the onCreateViewHolder method.