So i have a recycler view that is designed to show users sending messages to each other from my Firebase RTD. Originally it was working to show all users and the recycler items were clicked then it would show messages between the users. However, when modifying it to only view users that were in open messages with the current user, the items that populated my recycler view no longer displays and an error saying E/RecyclerView: No adapter attached; skipping layout is logged within the Run tab.
Unfortunately i can no longer undo the changes and have struggled to find the cause of my problem but have assume that it is either taking place in my adapted or activity classes.
InboxActivity.java:
public class InboxActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private List<User> inboxLst;
FirebaseUser user;
DatabaseReference reference;
UserAdapter usrAdpt;
private List<String> userLst;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inbox);
//Identify and setup recycler view
recyclerView = findViewById(R.id.rycInbox);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
userLst = new ArrayList<>();
//Get all chats between current user and and other users
user = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("Chats");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userLst.clear();
for (DataSnapshot snp : dataSnapshot.getChildren()){
Chat chat = snp.getValue(Chat.class);
if (chat.getSender().equals(user.getUid())){
userLst.add(chat.getReceiver());
}
if (chat.getReceiver().equals(user.getUid())){
userLst.add(chat.getSender());
}
}
readChat();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void readChat() {
inboxLst = new ArrayList<>();
reference = FirebaseDatabase.getInstance().getReference("Users");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userLst.clear();
for (DataSnapshot snp : dataSnapshot.getChildren()) {
User usr = snp.getValue(User.class);
//Display users that are currently in an open chat
for (String id : userLst){
if(usr.getId().equals(id)){
if(inboxLst.size() != 0){
for (User usrl : inboxLst){
if(!usr.getId().equals(usrl.getId())){
inboxLst.add(usr);
}
}
}else{
inboxLst.add(usr);
}
}
}
}
//Set the adapter for the recycler view once using the chat information retrieved from firebase database
usrAdpt = new UserAdapter(InboxActivity.this,inboxLst);
recyclerView.setAdapter(usrAdpt);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) { }
});
}
}
UserAdapter.java:
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder> {
private Context cont;
private List<User> nUser;
public UserAdapter(Context cont, List<User> nUser){
this.cont = cont;
this.nUser = nUser;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(cont).inflate(R.layout.lst_layout_inbox, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
User user = nUser.get(position);
holder.username.setText(user.getUsername());
holder.usrLst.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(cont, MessageActivity.class);
intent.putExtra("userid",user.getId());
cont.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return nUser.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView username;
RelativeLayout usrLst;
public ViewHolder(View itemView){
super(itemView);
username = itemView.findViewById(R.id.usrName);
usrLst = itemView.findViewById(R.id.usrCard);
}
}
}
The only catchup in your question is, in the following method:
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userLst.clear(); // <------ WHY YOU CLEAR LIST HERE??? COMMENT THIS ----------
for (DataSnapshot snp : dataSnapshot.getChildren()) {
User usr = snp.getValue(User.class);
//Display users that are currently in an open chat
for (String id : userLst){
if(usr.getId().equals(id)){
if(inboxLst.size() != 0){
for (User usrl : inboxLst){
if(!usr.getId().equals(usrl.getId())){
inboxLst.add(usr);
}
}
}else{
inboxLst.add(usr);
}
}
}
}
//Set the adapter for the recycler view once using the chat information retrieved from firebase database
usrAdpt = new UserAdapter(InboxActivity.this,inboxLst);
recyclerView.setAdapter(usrAdpt);
}
why you do userLst.clear(); ?
Since in OnCreate() method you populate userLst and call readChat(). And in onDataChange() you clear the userLst and then afterwards you try to iterate over the userLst to Display users that are currently in an open chat.
I would suggest to comment this userLst.clear(); and after setting items call notifyDataSetChanged()
Try these things:
Set the adapter in onCreate.
and in the onDataChanged listener, update the ArrayList and call notifyDataSetChanged().
This should help
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.
Java
Here is the code of fragment of my app and when I run it my app crashes as soon as I start the app got Customer home fragment it crashes, In logcat its showing there is error in CustomerHomefragemnt so here's the code as I am not being able to troubleshoot it Please answer if someone can help. Here is my fragment code`
public class CustomerHomeFragment extends Fragment implements
SwipeRefreshLayout.OnRefreshListener {
RecyclerView recyclerView;
private List<UpdateDishModel> updateDishModelList;
private CustomerHomeAdapter adapter;
String State, City, Sub;
DatabaseReference dataaa, databaseReference;
SwipeRefreshLayout swipeRefreshLayout;
SearchView searchView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_customerhome, null);
setHasOptionsMenu(true);
recyclerView = v.findViewById(R.id.recycle_menu);
recyclerView.setHasFixedSize(true);
Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.move);
recyclerView.startAnimation(animation);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
updateDishModelList = new ArrayList<>();
swipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipelayout);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimaryDark, R.color.green);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
String userid = FirebaseAuth.getInstance().getCurrentUser().getUid();
dataaa = FirebaseDatabase.getInstance()
.getReference("Customer").child(userid);
dataaa.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Customer cust = dataSnapshot.getValue(Customer.class);
State = cust.getState();
City = cust.getCity();
Sub = cust.getSuburban();
customermenu();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
return v;
}
#Override
public void onRefresh() {
customermenu();
}
private void customermenu() {
swipeRefreshLayout.setRefreshing(true);
DatabaseReference databaseReference =
FirebaseDatabase.getInstance().getReference("FoodSupplyDetails")
.child(State).child(City).child(Sub);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
updateDishModelList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
for (DataSnapshot snapshot1 : snapshot.getChildren()) {
UpdateDishModel updateDishModel =
snapshot1.getValue(UpdateDishModel.class);
updateDishModelList.add(updateDishModel);
}
}
adapter = new CustomerHomeAdapter(getContext(), updateDishModelList);
recyclerView.setAdapter(adapter);
swipeRefreshLayout.setRefreshing(false);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
swipeRefreshLayout.setRefreshing(false);
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
search(newText);
return true;
}
});
}
private void search(final String searchtext) {
ArrayList<UpdateDishModel> mylist = new ArrayList<>();
for (UpdateDishModel object : updateDishModelList) {
if (object.getDishes().toLowerCase().contains(searchtext.toLowerCase())) {
mylist.add(object);
}
}
adapter = new CustomerHomeAdapter(getContext(), mylist);
recyclerView.setAdapter(adapter);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.search, menu);
MenuItem menuItem = menu.findItem(R.id.Searchdish);
searchView = (SearchView) menuItem.getActionView();
searchView.setQueryHint("Search Dish");
}
}
```
`here is my Homeadapter code`
public class CustomerHomeAdapter extends
RecyclerView.Adapter<CustomerHomeAdapter.ViewHolder>
{
private Context mcontext;
private List<UpdateDishModel>updateDishModellist;
DatabaseReference databaseReference;
public CustomerHomeAdapter(Context context,List<UpdateDishModel>updateDishModellist)
{
this.updateDishModellist=updateDishModellist;
this.mcontext=context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view=
LayoutInflater.from(mcontext)
.inflate(R.layout.customer_menudish,parent,false);
return new CustomerHomeAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
final UpdateDishModel updateDishModel=updateDishModellist.get(position);
Glide.with(mcontext).load(updateDishModel.getImageURL()).into(holder.imageView);
holder.Dishname.setText(updateDishModel.getDishes());
updateDishModel.getRandomUID();
updateDishModel.getChefId();
holder.price.setText("Price: ₹ " + updateDishModel.getPrice());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(mcontext,OrderDish.class);
intent.putExtra("FoodMenu",updateDishModel.getRandomUID());
intent.putExtra("ChefId",updateDishModel.getChefId());
mcontext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return updateDishModellist.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView Dishname,price;
ElegantNumberButton additem;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView=itemView.findViewById(R.id.menu_image);
Dishname=itemView.findViewById(R.id.dishname);
price=itemView.findViewById(R.id.dishprice);
additem=itemView.findViewById(R.id.number_btn);
}
}
}
I think error is in this code as i am not able to trouble shoot is please help me with this
private void customermenu() {
swipeRefreshLayout.setRefreshing(true);
DatabaseReference databaseReference =
FirebaseDatabase.getInstance().getReference("FoodSupplyDetails")
.child(State).child(City).child(Sub);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
updateDishModelList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
for (DataSnapshot snapshot1 : snapshot.getChildren()) {
UpdateDishModel updateDishModel =
snapshot1.getValue(UpdateDishModel.class);
updateDishModelList.add(updateDishModel);
}
}
adapter = new CustomerHomeAdapter(getContext(), updateDishModelList);
recyclerView.setAdapter(adapter);
swipeRefreshLayout.setRefreshing(false);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
swipeRefreshLayout.setRefreshing(false);
}
});
enter image description here
enter image description here
From your code, your issue seems to be on below line:
FirebaseDatabase.getInstance().getReference("FoodSupplyDetails")
.child(State).child(City).child(Sub);
Error tells you you cannot pass null for ".child()". So it is telling you the values for State, City and Sub are null. You can confirm this by going to your Firebase's console database and seeing the data structure for the corresponding "Customer" with the firebase id.
Please check your Firebase database and make sure the customer data exists.
Before you run your query you should make sure the values are not null.
if (State != null && City != null && Sub != null) {
// Run your query here
} else {
Log.d("TAG", "Data provided is null")
}
When you are fetching customer's information, try logging that and check which of them is null:
String State, City, Sub;
//...
State = cust.getState();
City = cust.getCity();
Sub = cust.getSuburban();
Log.d("TAG", State);
Log.d("TAG", City);
Log.d("TAG", Sub);
// call customermenu now
customermenu();
The error tells you you cannot pass null for ".child()". So it is telling you the values for data(stored in the firebase database) are null. You can confirm this by going to your Firebase's console database and seeing the data structure corresponding with the firebase id.
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.
This is my firebase structure
databaseSupp.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
suppList.clear();
for (DataSnapshot suppSnapshot : dataSnapshot.child("Task").getChildren()) {
//Log.d("fbBee", dataSnapshot.getRef().child("Task").child("9223450").child("Firebase").toString());
Log.d("fbBee", suppSnapshot.getValue().toString());
Log.d("fbGet",suppSnapshot.child("Firebase").getValue().toString());
Supp supp = suppSnapshot.child("Firebase").getValue(Supp.class);
suppList.add(supp);
}
SuppList adapter = new SuppList(MainActivity2.this, suppList);
mListViewSupp.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
This is my code, but this code just show child Firebase. I want read and show data from child Firebase, but I need flag on child Reply for reference in my fragmens. please help for code.
Try something like that:
final DatabaseReference database = FirebaseDatabase.getInstance().getReference().child("Task/");
database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot taskNo : dataSnapshot.getChildren()) {
// now you in (9223450)
Object firebaseObj = taskNo.child("Firebase").getValue(FirebaseObj.class); //class with params set/get methods
Object replayObj = taskNo.child("Replay").getValue(ReplayObj.class); //class with params set/get methods
// ALTERNATIVE
/*
for (DataSnapshot child : taskNo.getChildren()) {
if(child.getKey().equals("Firebase")) {
String address = child.child("Address").getValue(String.class);
String customer = child.child("Customer").getValue(String.class);
// ...
} else if (child.getKey().equals("Replay")) {
// replay
// ...
}
}
*/
}
}
#Override
public void onCancelled(DatabaseError databaseError) { }
});
Like This
public class SuppList extends ArrayAdapter {
private Activity context;
private List<Supp> suppList;
public SuppList (Activity context, List<Supp> suppList){
super(context, R.layout.list_layout_new, suppList);
this.context = context;
this.suppList = suppList;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_layout_new, null, true);
TextView textViewSo = (TextView) listViewItem.findViewById(R.id.textViewSo);
TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName);
TextView textViewAddress = (TextView) listViewItem.findViewById(R.id.textViewAddress);
Supp supp = suppList.get(position);
textViewSo.setText(supp.getSuppId());
//Log.e("SuppTest", supp.getSuppId());
textViewName.setText(supp.getSuppName());
textViewAddress.setText(supp.getSuppAddress());
return listViewItem;
}
}
I am trying to get recieverUID from a certain table and then get the Value of username cooresponding the UID from another table.
What I think is happening is that the Adapter is being set before the receivedNames Array List has been fetched as the App runs fine when I set the receivedName Array list as a constant.
Please tell me what's wrong here and if this is the correct way to do this
Here's what my database looks like,
Firebase DB
My code for Tab 3 Fragment
public class Tab3 extends Fragment {
private static RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private static RecyclerView recyclerView;
private static ArrayList<String> reminderMessages;
protected static ArrayList<String> receiverNames;
String senderUID;
private DatabaseReference mDatabase;
//Overriden method onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Change R.layout.tab1 in you classes
View v = inflater.inflate(R.layout.tab3, container, false);
//get current user
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
reminderMessages = new ArrayList<>();
receiverNames = new ArrayList<>();
senderUID = user.getUid();
mDatabase = FirebaseDatabase.getInstance().getReference();
Query query = mDatabase.child("reminders").orderByChild("senderUID").equalTo(senderUID);
//Setting size of recycler view as constant
recyclerView = (RecyclerView) v.findViewById(R.id.my_recycler_view);
recyclerView.setHasFixedSize(true);
//Setting Linear Layout
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
//Getting message from database
String message = ds.child("reminderMessage").getValue(String.class);
//Adding database to ArrayList
reminderMessages.add(message);
//Getting ReceiverUID
String rUID = ds.child("receiverUID").getValue(String.class);
//Getting corresponding username of the ReceiverUID
GetName getName = new GetName();
getName.GetName(rUID);
reminderMessages.add(message);
// Log.d("String names", receiverNames.toString());
}
adapter = new DataAdapter(reminderMessages,receiverNames);
recyclerView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
//Error in Reaching Database
Toast.makeText(getContext(), "Something went Wrong!", Toast.LENGTH_SHORT).show();
}
});
//Returning the layout file after inflating
return v;
}
And here is my GetName Class
public class GetName {
private FirebaseAuth auth;
ListView listView;
private DatabaseReference mDatabase;
String receiverName;
public void GetName(String UID){
mDatabase = FirebaseDatabase.getInstance().getReference().child("users");
Query query = mDatabase.orderByKey().equalTo(UID);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot2) {
// dataSnapshot is the "issue" node with all children with id 0
for (DataSnapshot users : dataSnapshot2.getChildren()) {
receiverName = users.child("username").getValue(String.class);
receiverNames.add(receiverName);
Log.d("name retrieved",receiverNames.toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
To solve this problem, please add the declaration of your receiverNames ArrayList inside the onDataChange() method, otherwise it will be null. This is happening due to asynchronous behaviour of that method. If you want to use those values outside that method, please see my answer from this post.