This question already has answers here:
Firebase: Query to exclude data based on a condition
(2 answers)
Closed 3 years ago.
Currently, it pulls in all users details and populates their image, name, and bio. I want it to hide the current user from the list of users and I don't know how to implement the code for it.
I have tried if/while statements to compare dataSnapshot to the current user but I don't know how to populate the users depending on this condition.
public class SearchFragment extends Fragment {
private RecyclerView usersList;
private DatabaseReference databaseReference;
private DatabaseReference userDatabase;
private DatabaseReference checkName;
private FirebaseAuth firebaseAuth;
private String currentUserID;
private View view;
public SearchFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_search, container, false);
usersList = view.findViewById(R.id.search_users);
firebaseAuth = FirebaseAuth.getInstance();
currentUserID = firebaseAuth.getCurrentUser().getUid();
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
userDatabase = FirebaseDatabase.getInstance().getReference();
checkName = userDatabase.child("Users").child(currentUserID).child("name");
usersList.setHasFixedSize(true);
usersList.setLayoutManager(new LinearLayoutManager(getContext()));
return view;
}
#Override
public void onStart() {
super.onStart();
final FirebaseRecyclerOptions<Users> options = new FirebaseRecyclerOptions.Builder<Users>()
.setQuery(databaseReference, Users.class)
.build();
FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<Users, SearchFragment.UsersViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull SearchFragment.UsersViewHolder holder, int position, #NonNull final Users users) {
holder.setName(users.getName());
holder.setCity(users.getCity());
holder.setImage(users.getImage());
final String user_ID = getRef(position).getKey();
final String user_Name = users.getName();
final String user_Img = users.getImage();
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CharSequence pickOption[] = new CharSequence[]{"View Profile", "Send Message"};
final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Select an Option");
builder.setItems(pickOption, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (i == 0){
Intent otherProfileIntent = new Intent(getActivity(), OthersProfileActivity.class);
otherProfileIntent.putExtra("user_ID", user_ID);
otherProfileIntent.putExtra("user_Name", user_Name);
otherProfileIntent.putExtra("user_Img", user_Img);
startActivity(otherProfileIntent);
}
if (i == 1) {
Intent messageIntent = new Intent(getActivity(), MessageActivity.class);
messageIntent.putExtra("user_ID", user_ID);
messageIntent.putExtra("user_Name", user_Name);
messageIntent.putExtra("user_Img", user_Img);
startActivity(messageIntent);
}
}
});
builder.show();
}
});
}
#NonNull
#Override
public SearchFragment.UsersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.users_layout, parent, false);
return new SearchFragment.UsersViewHolder(view);
}
};
usersList.setAdapter(adapter);
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
}
public static class UsersViewHolder extends RecyclerView.ViewHolder {
View mView;
public UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setName(String name) {
TextView userNameView = mView.findViewById(R.id.single_userName);
userNameView.setText(name);
}
public void setCity(String name) {
TextView userNameView = mView.findViewById(R.id.single_userStatus);
userNameView.setText(name);
}
public void setImage(String image) {
CircleImageView userImage = mView.findViewById(R.id.single_userImg);
if(!image.equals("default")) {
Picasso.get().load(image).into(userImage);
}
}
}
}
I am expecting the current user to be hidden from the list of all users in the RecyclerView. Thanks in advance!
You might consider modifying your databaseReference like the following.
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
checkName = userDatabase.child("Users").child(currentUserID).child("name");
// This is your updated database reference
databaseReference = FirebaseDatabase.getInstance().getReference()
.child("Users").child(currentUserID);
Now while setting the options for your FirebaseRecyclerAdapter you might consider setting the query like the following.
final FirebaseRecyclerOptions<Users> options = new FirebaseRecyclerOptions.Builder<Users>()
.setQuery(databaseReference.equalTo(null), Users.class)
.build();
I have not tested this. However, please let me know if that works.
Related
I want to change firestore query parameter when clicking button. For example, my query is this by default:
db.collection("Posts").whereEqualTo("postCategory", "Business").orderBy("createdAt", Query.Direction.DESCENDING);
But when I click "Economy" button query needs to be changed to this and show different post results:
db.collection("Posts").whereEqualTo("postCategory", "Economy").orderBy("createdAt", Query.Direction.DESCENDING);
I tried to create String called selectedCategory and changed the value as I clicked the button but it had no effect as I call it in onCreateView and it is called only once. I also created indexes in Firestore console so it is not index related problem. There are 2 recyclerviews in my fragment; one of them holds buttons for category and other shows posts. I have been working on this problem for a while and any help is appreciated. Thanks
Edit:
TrendCategoryTagsAdapter.java
public class TrendCategoryTagsAdapter extends FirestoreRecyclerAdapter<CategorySelection, TrendCategoryTagsAdapter.TrendCategoryTagsHolder> {
Context context;
CategoryTagClicked categoryTagClicked;
int row_index;
public TrendCategoryTagsAdapter(#NonNull FirestoreRecyclerOptions<CategorySelection> options, Context context, CategoryTagClicked categoryTagClicked) {
super(options);
this.context = context;
this.categoryTagClicked = categoryTagClicked;
}
#Override
protected void onBindViewHolder(#NonNull final TrendCategoryTagsHolder holder, final int position, #NonNull CategorySelection model) {
holder.categoryNameText.setText(model.getCategoryName());
holder.categoryNameContainer.setOnClickListener(view -> {
String categoryName = holder.categoryNameText.getText().toString();
categoryTagClicked.onCategoryClicked(categoryName);
row_index = position;
notifyDataSetChanged();
});
if (row_index == position) {
holder.categoryNameContainer.setBackground(ContextCompat.getDrawable(context, R.drawable.black_rounded_bg));
} else {
holder.categoryNameContainer.setBackground(ContextCompat.getDrawable(context, R.drawable.grey_rounded_bg));
}
}
#NonNull
#Override
public TrendCategoryTagsHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.trendcategory_cell, parent, false);
return new TrendCategoryTagsAdapter.TrendCategoryTagsHolder(v);
}
public static class TrendCategoryTagsHolder extends RecyclerView.ViewHolder {
RelativeLayout categoryNameContainer;
TextView categoryNameText;
public TrendCategoryTagsHolder(#NonNull View itemView) {
super(itemView);
categoryNameContainer = itemView.findViewById(R.id.categoryNameContainer);
categoryNameText = itemView.findViewById(R.id.categoryNameText);
}
}
}
TrendingFragment.java
public class TrendingFragment extends Fragment implements CategoryTagClicked {
RecyclerView trendPostRV, trendingCategoryRV;
public TextView noPostTV;
FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference categoryRef, postRef;
TrendCategoryTagsAdapter trendCategoryTagsAdapter;
TrendingPostAdapter trendingPostAdapter;
String selectedCategory = "Art";
public TrendingFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_trending, container, false);
trendPostRV = view.findViewById(R.id.trendPostRV);
trendingCategoryRV = view.findViewById(R.id.trendingCategoryRV);
noPostTV = view.findViewById(R.id.noPostTV);
setUpTrendCategoryTagsRV();
setUpTrendingPostRV();
checkIfDataNull();
// Inflate the layout for this fragment
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
trendCategoryTagsAdapter.startListening();
trendingPostAdapter.startListening();
}
#Override
public void onDestroyView() {
super.onDestroyView();
trendCategoryTagsAdapter.stopListening();
trendingPostAdapter.stopListening();
}
private void setUpTrendCategoryTagsRV() {
categoryRef = db.collection("Categories");
Query query = categoryRef.orderBy("categoryName", Query.Direction.ASCENDING);
FirestoreRecyclerOptions<CategorySelection> options = new FirestoreRecyclerOptions.Builder<CategorySelection>()
.setQuery(query, CategorySelection.class)
.build();
trendCategoryTagsAdapter = new TrendCategoryTagsAdapter(options, getContext(), this);
trendingCategoryRV.setNestedScrollingEnabled(false);
final LinearLayoutManager trendingTagsLM = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
trendingCategoryRV.setLayoutManager(trendingTagsLM);
trendingCategoryRV.setAdapter(trendCategoryTagsAdapter);
trendCategoryTagsAdapter.notifyDataSetChanged();
}
public void setUpTrendingPostRV() {
postRef = db.collection("Posts");
Query query = postRef.whereEqualTo("postCategory", selectedCategory).orderBy("createdAt", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<Post> options = new FirestoreRecyclerOptions.Builder<Post>()
.setQuery(query, Post.class)
.build();
trendingPostAdapter = new TrendingPostAdapter(options, getContext());
trendPostRV.setNestedScrollingEnabled(false);
LinearLayoutManager trendingPostLM = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
trendPostRV.setLayoutManager(trendingPostLM);
trendPostRV.setAdapter(trendingPostAdapter);
trendingPostAdapter.notifyDataSetChanged();
}
private void checkIfDataNull() {
db.collection("Posts").whereEqualTo("postCategory", selectedCategory).get().addOnCompleteListener(task -> {
if (task.isSuccessful() && task.getResult() != null) {
if (task.getResult().size() == 0) {
noPostTV.setVisibility(View.VISIBLE);
trendPostRV.setVisibility(View.GONE);
} else {
noPostTV.setVisibility(View.GONE);
trendPostRV.setVisibility(View.VISIBLE);
}
} else {
Log.d("TAG", "Error getting documents: ", task.getException());
}
});
}
#Override
public void onCategoryClicked(String category) {
selectedCategory = category;
Toast.makeText(getContext(), selectedCategory, Toast.LENGTH_SHORT).show();
}
}
CategoryTagClicked.java (Interface)
public interface CategoryTagClicked {
void onCategoryClicked(String category);
}
Brief explanation of what I do:
Whenever I click on category button I pass the text of the button (in this case category name) to the selectedCategory string inside TrendingFragment. String selectedCategory is a parameter for query in setUpTrendingPostRV function. The problem is it only shows results after changing fragments but I want changes to take place immediately after I click the button.
I finally found what was an issue. It seems I needed to update my options inside onCategoryClicked interface.
#Override
public void onCategoryClicked(String category) {
selectedCategory = category;
Toast.makeText(getContext(), selectedCategory, Toast.LENGTH_SHORT).show();
Query newQuery = postRef.whereEqualTo("postCategory", selectedCategory).orderBy("createdAt", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<Post> options = new FirestoreRecyclerOptions.Builder<Post>()
.setQuery(newQuery, Post.class)
.build();
trendingPostAdapter.updateOptions(options);
checkIfDataNull();
}
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
at rishabh.example.chatapp.ChatsFragment.onCreateView(ChatsFragment.java:51)
Code of ChatsFragment.java
public class ChatsFragment extends Fragment
{
private View PrivateChatsView;
private RecyclerView chatsList;
private DatabaseReference ChatsRef, UsersRef;
private FirebaseAuth mAuth;
private String currentUserID;
public ChatsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
PrivateChatsView = inflater.inflate(R.layout.fragment_chats, container, false);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
ChatsRef = FirebaseDatabase.getInstance().getReference().child("Contacts").child(currentUserID);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
chatsList = (RecyclerView) PrivateChatsView.findViewById(R.id.chats_list);
chatsList.setLayoutManager(new LinearLayoutManager(getContext()));
return PrivateChatsView;
}
#Override
public void onStart()
{
super.onStart();
FirebaseRecyclerOptions<Contacts> options =
new FirebaseRecyclerOptions.Builder<Contacts>()
.setQuery(ChatsRef, Contacts.class)
.build();
FirebaseRecyclerAdapter<Contacts, ChatsViewHolder> adapter =
new FirebaseRecyclerAdapter<Contacts, ChatsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final ChatsViewHolder holder, int position, #NonNull Contacts model)
{
final String usersIDs = getRef(position).getKey();
final String[] retImage = {"default image"};
UsersRef.child(usersIDs).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
if (dataSnapshot.exists())
{
if (dataSnapshot.hasChild("image"))
{
retImage[0] = dataSnapshot.child("image").getValue().toString();
Picasso.get().load(retImage[0]).into(holder.profileImage);
}
final String retName = dataSnapshot.child("name").getValue().toString();
final String retStatus = dataSnapshot.child("status").getValue().toString();
holder.userName.setText(retName);
holder.userStatus.setText("Last Seen: " + "\n" + "Date " + " Time");
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Intent chatIntent = new Intent(getContext(), ChatActivity.class);
chatIntent.putExtra("visit_user_id", usersIDs);
chatIntent.putExtra("visit_user_name", retName);
chatIntent.putExtra("visit_user_image", retImage[0]);
startActivity(chatIntent);
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
}
});
}
#NonNull
#Override
public ChatsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i)
{
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.users_display_layout, viewGroup, false);
return new ChatsViewHolder(view);
}
};
chatsList.setAdapter(adapter);
adapter.startListening();
}
public static class ChatsViewHolder extends RecyclerView.ViewHolder
{
CircleImageView profileImage;
TextView userStatus, userName;
public ChatsViewHolder(#NonNull View itemView)
{
super(itemView);
profileImage = itemView.findViewById(R.id.users_profile_image);
userName = itemView.findViewById(R.id.user_profile_name);
userStatus = itemView.findViewById(R.id.user_status);
}
}
}
I don't know where the code is giving error and could not able to find the bug. Please help me to find the bug.
Error pointing on the line: currentUserID = mAuth.getCurrentUser().getUid();
This line is used in many activities and not given any error but on this activity this line is giving a null error. Please help me so that I can solve this error.
It looks like the current user isn't initialized when your ChatsFragment is created.
The simplest fix is to not create the ChatsFragment until the user is initialized.
Another simple fix is to only attach the database listener if there is a current user:
mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
currentUserID = mAuth.getCurrentUser().getUid();
ChatsRef = FirebaseDatabase.getInstance().getReference().child("Contacts").child(currentUserID);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
}
A common alternative is to wait until the user is initialized inside the ChatsFragment before attaching a listener to the database. You do that with a so-called auth state listener:
mAuth = FirebaseAuth.getInstance();
mAuth.onAuthStateChanged(new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
currentUserID = mAuth.getCurrentUser().getUid();
ChatsRef = FirebaseDatabase.getInstance().getReference().child("Contacts").child(currentUserID);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
}
}
};
I'm unable to retrieve the Firebase Database. I am able to successfully upload the Data to Firebase but when I wanted to retrieve the database it shows the blank screen.
Here is the the Firebase database screenshot:
My code is:
public class SubjectBooks extends AppCompatActivity {
FirebaseAuth fauth;
String user;
DatabaseReference dbreference,dbref;
RecyclerView rv;
String subject;
int child_count=0;
ArrayList<Books> list;
SubjectBooksAdapter staggeredBooksAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subject_books_request);
getSupportActionBar().setTitle("Request for Room");
// this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// this.getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu_share);
fauth = FirebaseAuth.getInstance();
subject = getIntent().getStringExtra("subject").trim();
dbreference = FirebaseDatabase.getInstance().getReference("roomrequest").child("request");
dbreference.keepSynced(true);
user = fauth.getCurrentUser().getEmail();
list = new ArrayList<>();
staggeredBooksAdapter = new SubjectBooksAdapter(list);
rv = (RecyclerView) findViewById(R.id.recyclerView);
rv.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
rv.setLayoutManager(llm);
rv.setAdapter(staggeredBooksAdapter);
dbreference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
final Books b1 = dataSnapshot.getValue(Books.class);
// Log.e("Value is ",dataSnapshot.getKey()+" "+b1.getBauthor());
//Log.e("Book"," received");
if(!user.equals(b1.getSelleremail())) {
child_count++;
list.add(b1);
staggeredBooksAdapter.notifyDataSetChanged();
}
// Log.e("Has child : ", dataSnapshot.getKey());
// if(child_count==0){
// Toast.makeText(SubjectBooks.this, "No books found!", Toast.LENGTH_SHORT).show();
// Intent in = new Intent(SubjectBooks.this, BooksPage.class);
// startActivity(in);
// finish();
// }
}
#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) {
}
});
}
}
and code for my adapter is
public class SubjectBooksAdapter extends RecyclerView.Adapter<SubjectBooksAdapter.MyViewHolder> {
ArrayList<Books> bookslist;
CardView cv;
FirebaseAuth fauth;
FirebaseDatabase database;
DatabaseReference dbreference;
Books b;
public SubjectBooksAdapter(ArrayList<Books> bookslist){
this.bookslist = bookslist;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_request,parent,false);
return new MyViewHolder(v);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView bookName,bookAuthor,bookDesc,bookPrice,bookCall;
ImageView iv;
MyViewHolder(final View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.my_card_view);
iv = (ImageView) itemView.findViewById(R.id.imageView);
database = FirebaseDatabase.getInstance();
dbreference = database.getReference("roomrequest");
bookName = (TextView) itemView.findViewById(R.id.bookName);
bookAuthor = (TextView) itemView.findViewById(R.id.bookAuthor);
bookDesc = (TextView) itemView.findViewById(R.id.bookDesc);
bookPrice = (TextView) itemView.findViewById(R.id.bookPrice);
bookCall = (TextView) itemView.findViewById(R.id.bookCall);
fauth = FirebaseAuth.getInstance();
}
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
database = FirebaseDatabase.getInstance();
dbreference = database.getReference("roomrequest");
b = bookslist.get(position);
holder.bookName.setText(b.getBname());
holder.bookAuthor.setText(b.getBauthor());
holder.bookDesc.setText(b.getBdesc());
holder.bookPrice.setText("Rs. "+b.getPrice());
holder.bookCall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Log.e("Current user is ", fauth.getCurrentUser().getEmail());
}
});
Glide.with(cv.getContext()).load(Uri.parse(b.getPics())).placeholder(R.drawable.bshelf).error(R.drawable.bshelf).into(holder.iv);
}
#Override
public int getItemCount() {
return bookslist.size();
}
}
I run the code and compiled ..it compiles successfully and when when app is launched then it shows blank white screen.
If There are any other details you would like to know please comment I would be very happy to provide the details as you required.
I'm using Firebase Realtime Database with Firebase UI, however i'm not being able to search with multiple clauses.
What i need is to take the Users that do not have an specific id. As i'm already filtering them by City i need to filter these ones with specific id.
I've been trying to solve it in many ways, however none of them has come to success.
This is my Database
I cant take and render the card with the user with that username.
public class SearchFragment extends android.support.v4.app.Fragment {
private EditText mSearchField;
private ImageButton mSearchBtn;
private RecyclerView mResultList;
private DatabaseReference mUserDatabase;
public static SearchFragment newInstance() { return new SearchFragment(); }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_search, container, false);
mSearchField = view.findViewById(R.id.search_field);
mSearchBtn = view.findViewById(R.id.search_btn);
mResultList = view.findViewById(R.id.result_list);
mResultList.setHasFixedSize(true);
mResultList.setLayoutManager(new LinearLayoutManager(mResultList.getContext()));
mSearchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String searchText = mSearchField.getText().toString();
firebaseUserSearch(searchText);
mSearchField.setText("");
}
});
mUserDatabase = FirebaseDatabase.getInstance().getReference("usuarios");
return view;
}
public void firebaseUserSearch(String searchText) {
Toast.makeText(getContext(), "Buscando usuários", Toast.LENGTH_LONG).show();
String searchTextLower = searchText.toLowerCase();
final Query firebaseSearchQuery = mUserDatabase.orderByChild("city").startAt(searchTextLower).endAt(searchTextLower + "\uf8ff");
firebaseSearchQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
GenericTypeIndicator<Map<String, String>> genericTypeIndicator = new GenericTypeIndicator<Map<String, String>>() {};
Map<String, String> map = dataSnapshot.getValue(genericTypeIndicator );
String username = map.get("username").toString();
Log.d("oi", username);
Log.d("olar", UserDetails.username);
if(username != UserDetails.username) {
final FirebaseRecyclerOptions<User> options =
new FirebaseRecyclerOptions.Builder<User>()
.setQuery(firebaseSearchQuery, User.class)
.build();
bindAndBuildFirebaseUi(options);
}
}
public void bindAndBuildFirebaseUi(FirebaseRecyclerOptions options) {
final FirebaseRecyclerAdapter<User, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<User, UsersViewHolder>(options) {
#Override
public UsersViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_layout, parent, false);
return new UsersViewHolder(v);
}
#Override
protected void onBindViewHolder(final UsersViewHolder holder, int position, final User model) {
holder.bind(model);
Log.d("SearchFragment", "Binded the model");
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UserDetails.chatWithId = model.getUsername();
UserDetails.chatWith = model.getName();
startActivity(new Intent(getContext(), Chat.class));
}
});
}
};
firebaseRecyclerAdapter.startListening();
mResultList.setAdapter(firebaseRecyclerAdapter);
}
}
As you can see i even tried to filter them throught the database again, howeever, Firebase ui is taking the filter from options which is the first query filtering the users by city.
Does anyone have any idea how to take avoid rendering the users with an specific id???
And i also know that Firebase does not allow to use more than one orderBy.
The Firebase RTDB doesn't support multiple where clauses unfortunately. However, if you denormalize your data properly, you can use one query to link to another ref in the database and effectively filter data in that way. Take a look at the docs: https://github.com/firebase/FirebaseUI-Android/blob/master/database/README.md#using-firebaseui-with-indexed-data.
As a side note, you really shouldn't be using the RTDB to store actual data as it won't scale. It's designed for low latency real-time updates for multiplayer stuff or a ticketing app etc. Instead, I'd recommend looking into Firestore, especially if this is a new app.
Here's the hack I mentioned in my comment below:
public class MyAdapter extends FirebaseRecyclerAdapter {
private static final int TYPE_NORMAL = 0;
private static final int TYPE_HIDDEN = 1;
private final View mEmpty = new View(getContext());
public MyAdapter(#NonNull FirestoreRecyclerOptions options) {
super(options);
mEmpty.setVisibility(View.GONE);
}
#Override
public int getItemViewType(int position) {
if (getItem(position).username.equals(UserDetails.username)) {
return TYPE_HIDDEN;
} else {
return TYPE_NORMAL;
}
}
#Override
public UsersViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == TYPE_HIDDEN) {
return new UsersViewHolder(mEmpty);
}
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_layout, parent, false);
return new UsersViewHolder(v);
}
#Override
protected void onBindViewHolder(final UsersViewHolder holder, int position, final User model) {
if (getItemViewType(position) == TYPE_HIDDEN) return;
holder.bind(model);
Log.d("SearchFragment", "Binded the model");
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UserDetails.chatWithId = model.getUsername();
UserDetails.chatWith = model.getName();
startActivity(new Intent(getContext(), Chat.class));
}
});
}
}
I have to develop a chat app in android using firebase,It consist of different groups having options of leaving and joining the group,First time it doesn't show joined and leaved groups but on second time when we scroll list view or change view then it shows correctly.I have to fix the issue kindly look the below code and show what problems should be fixed.
public class Allgroups extends AppCompatActivity {
private DatabaseReference mDatabaseRef;
private List<ImageUpload> imgList;
private List<groupuserstoken> imgList1;
ListView listView;
private ImageListAdapter adapter;
private DatabaseReference databaseReference;
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_allgroups);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Please wait loading groups...");
listView=(ListView)findViewById(R.id.allgroups11);
mDatabaseRef = FirebaseDatabase.getInstance().getReference();
imgList=new ArrayList<>();
final Query query = mDatabaseRef.child("Groups");
listView.smoothScrollByOffset(10);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
ImageUpload img = snapshot.getValue(ImageUpload.class);
imgList.add(img);
}
adapter = new ImageListAdapter(Allgroups.this, R.layout.custommenu, imgList);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String name=imgList.get(i).getName();
String path=imgList.get(i).getUrl();
String topic=imgList.get(i).getTopic();
Intent intent= new Intent(getApplicationContext(),Main4Activity.class);
intent.putExtra("name",name);
intent.putExtra("path",path);
intent.putExtra("topic",topic);
startActivity(intent);
}
});
}
}
public class ImageListAdapter extends ArrayAdapter<ImageUpload> {
private Activity context;
private int resource;
private List<ImageUpload> listImage;
private DatabaseReference mDatabaseRef;
private List<groupuserstoken> imgList1;
ProgressDialog progressDialog;
int pos;
public ImageListAdapter(#NonNull Activity context, #LayoutRes int resource, #NonNull List<ImageUpload> objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
listImage = objects;
}
TextView tvName;
TextView tvDes;
TextView statuss;
Button leave;
ImageView img;
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.custommenu, null);
}
// final LayoutInflater inflater = context.getLayoutInflater();
// v = LayoutInflater.from(getContext()).inflate(R.layout.custommenu, parent, false);
ImageUpload listImage1 = getItem(position);
if (listImage1 !=null) {
tvName = (TextView) v.findViewById(R.id.as);
tvDes = (TextView) v.findViewById(R.id.aa);
statuss = (TextView) v.findViewById(R.id.users);
img = (ImageView) v.findViewById(R.id.addgroup1);
leave = (Button) v.findViewById(R.id.leavegroup);
mDatabaseRef = FirebaseDatabase.getInstance().getReference();
final String name = listImage.get(pos).getName();
final Query query1 = mDatabaseRef.child(name + "user");
query1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
imgList1 = new ArrayList<>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
groupuserstoken img = snapshot.getValue(groupuserstoken.class);
imgList1.add(img);
}
String token = FirebaseInstanceId.getInstance().getToken();
if (!(imgList1.isEmpty())) {
if (!(imgList1.contains(token))) {
leave.setText("Leave Group");
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
tvName.setText(listImage1.getName());
tvDes.setText(listImage1.getDescription());
statuss.setText(listImage1.getMembers() + " Users ");
Glide.with(context).load(listImage1.getUrl()).into(img);
}
leave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String groupname = listImage.get(position).getName();
mDatabaseRef = FirebaseDatabase.getInstance().getReference().child(groupname+"user").child(FirebaseInstanceId.getInstance().getToken());
mDatabaseRef.child("token").setValue(FirebaseInstanceId.getInstance().getToken());
}
});
return v;
}
}
Please use setTag() and getTag() in your adapter, but for better practice is to use RecyclerView instead of ListView.