Hi i'm stuck on this part where i have 2 collections first one is users and second one is friends. I want my recyclerview to display my friends on the list with the help of current user because on currentUser other peoples id are stored and i want it to display it on the recyclerview but when it displays it i want to get their information from users where they have their username and email stored.
I want only friends collection ids to display on recyclerview with the help of current user id. Then i want to get values from users collection like their name and email value.
Friends collection
users collection
ADAPTER
public class FriendsAdapter extends FirestoreRecyclerAdapter {
private OnItemClicklistener onItemClicklistener;
public FriendsAdapter(#NonNull FirestoreRecyclerOptions<AllUsers> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull FriendsHolder holder, int position, #NonNull AllUsers model) {
holder.textViewUsername.setText(String.valueOf(model.getName()));
holder.textViewEmail.setText(model.getEmail());
holder.setAvatar(model.getAvatar());
}
#NonNull
#Override
public FriendsHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.all_user_list_display, viewGroup, false);
return new FriendsAdapter.FriendsHolder(view);
}
class FriendsHolder extends RecyclerView.ViewHolder {
TextView textViewUsername;
TextView textViewEmail;
ImageView imageViewAvatar;
public FriendsHolder(#NonNull View itemView) {
super(itemView);
textViewUsername = itemView.findViewById(R.id.all_user_username);
textViewEmail = itemView.findViewById(R.id.all_user_userEmail);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION && onItemClicklistener != null) {
onItemClicklistener.onItemClick(getSnapshots().getSnapshot(position), position);
}
}
});
}
public void setAvatar(String avatar) {
imageViewAvatar = (ImageView) itemView.findViewById(R.id.all_user_profile_image);
Picasso.get().load(avatar).into(imageViewAvatar);
}
}
public interface OnItemClicklistener {
void onItemClick(DocumentSnapshot snapshot, int position);
}
public void setOnItemClickListener(FriendsAdapter.OnItemClicklistener listener) {
onItemClicklistener = listener;
}
FriendListFragment
public class FriendsListFragment extends Fragment {
private FirebaseFirestore db;
private CollectionReference usersCollection;
private CollectionReference friendsCollection;
private DocumentReference friends;
private DocumentReference users;
private FirebaseUser current_user;
private FriendsAdapter adapter;
public SearchView search_friends;
public FriendsListFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_friends, container, false);
current_user = FirebaseAuth.getInstance().getCurrentUser();
//FIREBASE
db = FirebaseFirestore.getInstance();
usersCollection = db.collection("users");
friendsCollection = db.collection("friends");
friends = friendsCollection.document(current_user.getUid());
Query friendQuery = usersCollection;
FirestoreRecyclerOptions<AllUsers> options = new FirestoreRecyclerOptions.Builder<AllUsers>()
.setQuery(friendQuery, AllUsers.class)
.build();
adapter = new FriendsAdapter(options);
RecyclerView recyclerView = view.findViewById(R.id.friendsList);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(adapter);
return view;
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
AllUsersClass
public class AllUsers {
public String name;
public String avatar;
public String email;
public String userId;
public AllUsers() {
}
public AllUsers(String name, String email, String avatar, String userId) {
this.name = name;
this.email = email;
this.avatar = avatar;
this.userId = userId;
}
public String getName() {
return name;
}
public String getAvatar() {
return avatar;
}
public String getEmail() {
return email;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
Related
I am trying to fetch and populate my Adapter with only those records which are set as true (in a record), and if they are false, I would not like to fetch and populate my Adapter with them.
I am basically trying to build a Train Pantry Food Ordering System in which Passengers can order food from Pantry car. But with one condition :
Food should be available in the particular train's Pantry car in which the Passenger is travelling.
Here is my Realtime Database :
Here, Firstly I want to fetch the boolean values for entered train number from Catalog -> (trainno) -> data(true/false), then accordingly, if it is true, I want to populate my Adapter with those food items only while getting food-item data from foodinfo -> (foodname) -> data.
Here are my codes :
Food :
public class Food {
private String description;
private String imageurl;
private String foodname;
public Food(String description, String imageurl, String foodname) {
this.description = description;
this.imageurl = imageurl;
this.foodname = foodname;
}
public Food(){}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImageurl() {
return imageurl;
}
public void setImageurl(String imageurl) {
this.imageurl = imageurl;
}
public String getFoodname() {
return foodname;
}
public void setFoodname(String foodname) {
this.foodname = foodname;
}
}
FoodAdapter:
public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.Viewholder>{
private final Context mContext;
private final List<Food> mFoods;
public FoodAdapter(Context mContext, List<Food> mFoods) {
this.mContext = mContext;
this.mFoods = mFoods;
}
#NonNull
#Override
public Viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.food_item, parent, false);
return new FoodAdapter.Viewholder(view);
}
#Override
public void onBindViewHolder(#NonNull Viewholder holder, int position) {
Food food = mFoods.get(position);
holder.foodDescription.setText(food.getDescription());
Picasso.get().load(food.getImageurl()).into(holder.foodImage);
holder.foodName.setText(food.getFoodname());
FirebaseDatabase.getInstance().getReference().child("foodinfo").child(food.getFoodname())
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Food food1 = dataSnapshot.getValue(Food.class);
holder.foodName.setText(food1.getFoodname());
holder.foodDescription.setText(food1.getDescription());
Picasso.get().load(food.getImageurl()).into(holder.foodImage);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public int getItemCount() {
return mFoods.size();
}
public class Viewholder extends RecyclerView.ViewHolder {
public ImageView foodImage;
public TextView foodName;
public TextView foodDescription;
public Viewholder(#NonNull View itemView) {
super(itemView);
foodImage =itemView.findViewById(R.id.food_image);
foodName = itemView.findViewById(R.id.food_name);
foodDescription = itemView.findViewById(R.id.food_description);
}
}
}
HomeFragment:
public class HomeFragment extends Fragment {
private RecyclerView recyclerViewMenu;
private FoodAdapter foodAdapter;
private List<Food> foodList;
private List<String> availableFoodsList; // foods available for a train passenger only that will be shown.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
recyclerViewMenu = view.findViewById(R.id.recycler_view_foods);
recyclerViewMenu.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setStackFromEnd(true);
linearLayoutManager.setReverseLayout(true);
recyclerViewMenu.setLayoutManager(linearLayoutManager);
foodList = new ArrayList<>();
foodAdapter = new FoodAdapter(getContext(), foodList);
recyclerViewMenu.setAdapter(foodAdapter);
availableFoodsList = new ArrayList<>();
return view;
}
}
you should modify the underlayer data (foodList) then use Adapter.notifyDataSetChanged() to refresh the recycler view for any adapter data changes
I have created an application and data of user is loaded via firebase recycler adapter. It have data of users and each user have a link in their profile which redirect to a webpage. Everything is working fine the user is redirected to the webpage via the default browser. My question is how can I restrict the app to open the links/urls within itself. I don't want the links to be opened in the default browser. Below is my code
MyViewholder
class MyViewHolder extends RecyclerView.ViewHolder {
TextView geglink, userName, userAbout;
View v;
public MyViewHolder(#NonNull #NotNull View itemView) {
super(itemView);
geglink = (TextView) itemView.findViewById(R.id.rcvGigLink);
userName = (TextView) itemView.findViewById(R.id.rcvName);
userAbout = (TextView) itemView.findViewById(R.id.rcvAbout);
v = itemView;
DashboardActivity
RecyclerView recyclerView;
FirebaseRecyclerOptions<ModelClass> options;
FirebaseRecyclerAdapter<ModelClass, MyViewHolder> adapter;
DatabaseReference dRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
dRef = FirebaseDatabase.getInstance().getReference().child("Users");
recyclerView = findViewById(R.id.dashboardRCV);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
LoadData();
}
private void LoadData() {
options = new FirebaseRecyclerOptions.Builder<ModelClass>()
.setQuery(dRef, ModelClass.class)
.build();
adapter = new FirebaseRecyclerAdapter<ModelClass, MyViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull MyViewHolder holder, int position, #NonNull ModelClass model) {
holder.geglink.setText(model.getGig());
holder.userName.setText(model.getName());
holder.userAbout.setText(model.getAbout());
holder.v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = model.getGig();
if (!url.startsWith("http://") && !url.startsWith("https://")){
url = "https://" + url;
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(browserIntent);
}
}
});
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_layout, parent, false);
return new MyViewHolder(view);
}
};
adapter.startListening();
recyclerView.setAdapter(adapter);
}
}
ModelClass
public class ModelClass {
String gig, name, about;
public String getGig() {
return gig;
}
public void setGig(String gig) {
this.gig = gig;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAbout() {
return about;
}
public void setAbout(String about) {
this.about = about;
}
public ModelClass(String gig, String name, String about) {
this.gig = gig;
this.name = name;
this.about = about;
}
public ModelClass() {
}
}
Thanks in advance
I was using firebaseUI library to populate recycler view using firestore database.
when I try to retrieve the document id when i click on recycler view item it was like this
DocumentSnapshot snapshot = getSnapshots()
.getSnapshot(holder.getAdapterPosition());
final String countryName = snapshot.getId();
I tred this code but getSnapshots() appears by the red colored word and nt workng inside onbindeviewolder so I tried this but not working too
DocumentReference aa=firebaseFirestore.collection("MainCategories").document(String.valueOf(SS));
String aaa=aa.getId();
So is there any method to retrieve the document id because the code above is not working here
private class CategoriesAdapter extends RecyclerView.Adapter<AllCategoriesViewHolder> {
private List<mainCategroies> categorylist;
CategoriesAdapter(List<mainCategroies> categorylist) {
this.categorylist = categorylist;
}
#NonNull
#Override
public AllCategoriesViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_maincategory, parent, false);
return new AllCategoriesViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final AllCategoriesViewHolder holder, int position) {
final String categoryName = categorylist.get(position).getCategory_Name();
holder.setCategory_Name(categoryName);
String d = categorylist.get(position).getImageUrl();
holder.setImageUrl(d);
MainActivityProgress.setVisibility(View.GONE);
holder.view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
public int getItemCount() {
return categorylist.size();
}
}
the holder class
private class AllCategoriesViewHolder extends RecyclerView.ViewHolder {
private View view;
public AllCategoriesViewHolder(final View itemView) {
super(itemView);
view = itemView;
}
void setCategory_Name(String category_Name) {
TextView names = view.findViewById(R.id.CategoryName);
names.setText(category_Name);
}
void setImageUrl(String imageUrl) {
ImageView imageView = view.findViewById(R.id.MainCat_CardViewImage);
Picasso.get()
.load(imageUrl)
.fit()
.into(imageView);
}
}
and the model class
public class CountryItem {
private String CountryName;
public CountryItem(){
}
public CountryItem(String countryName) {
CountryName = countryName;
}
public String getCountryName() {
return CountryName;
}
public void setCountryName(String countryName) {
CountryName = countryName;
}
}
The method you are trying to get uid of item i.e:
DocumentSnapshot snapshot = getSnapshots().getSnapshot(holder.getAdapterPosition());
final String countryName = snapshot.getId();
will work only in case of FirestoreRecyclerAdapter. As you are using a RecyclerView.Adapter you have to add uid in your Model class and then Retrieve it.
CountryItem.class
public class CountryItem {
private String CountryName;
private String uid;
//add getters and setters
}
And while Retrieving the data from firestore add uid field to your object. I assume you are using query for this then it would be like:-
Query query = firestore.collection("Collection").orderBy("CountryName",Query.Direction.ASCENDING);
query.addSnapshotListener(this, new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
for(DocumentSnapshot documentSnapshot: documentSnapshots) {
CountryItem countryItem = documentSnapshot.toObject(CountryItem.class);
countryItem.setuid(documentSnapshot.getId().toString());
countryItemList.add(countryItem);
}
}
});
And onClick of an item you can get uid and pass to your method:-
holder.view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String uid = categorylist.get(position).getUid();
}
});
I'm trying to filter my user from a list of users in the recycler view. But I need to get the uid for each user inside the onBindViewHolder and I don't know how. I'd also like to move the code in onBindViewHolder to the bind method of the ViewHolder but I don't know how to get the context.
Here is what I've done
private void setRecyclerView() {
mUsersRecyclerView.setHasFixedSize(true);
mUsersRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new UserAdapter();
mUsersRecyclerView.setAdapter(mAdapter);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> list = dataSnapshot.getChildren();
// Filter current user
//List<User> userList = new ArrayList<>();
for (DataSnapshot user : list) {
if (!user.getKey().equals(mCurrentUid)) {
mUserList.add(user.getValue(User.class));
}
}
// Setting data
// mAdapter.setItems(userList);
}
#Override public void onCancelled(#NonNull DatabaseError databaseError) {}
});
}
private class UserAdapter extends RecyclerView.Adapter<UserViewHolder> {
#NonNull
#Override
public UserViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new UserViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.user_item_layout, parent, false));
}
#Override
public void onBindViewHolder(#NonNull UserViewHolder holder, int position) {
User user = mUserList.get(position);
holder.bind(user);
// TODO: move this to holder.bind() method
holder.setThumb_image(user.getThumb_image(),getApplicationContext());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent9 = new Intent(UsersActivity.this,ProfileActivity.class);
intent9.putExtra("user_id", uid); // TODO: get uid for each user here
startActivity(intent9);
}
});
}
#Override
public int getItemCount() {
return mUserList.size();
}
}
private class UserViewHolder extends RecyclerView.ViewHolder {
View mView;
public UserViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void bind(User user) {
TextView nameView = mView.findViewById(R.id.item_name);
nameView.setText(user.getName());
TextView statusView = mView.findViewById(R.id.item_status);
statusView.setText(user.getStatus());
}
public void setThumb_image(String thumb_image, Context ctx) {
CircleImageView imageView = mView.findViewById(R.id.item_image);
Picasso.with(ctx).load(thumb_image).placeholder(R.mipmap.icon).into(imageView);
}
}
Here is a working code with FirebaseRecyclerAdapter that doesn't filter the user.
Add firbaseId in your model while you store data to firebase database
Here's example user model class which stores user's information to firebase
public class User {
private String name;
private String address;
private String firebaseId;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getFirebaseId() {
return firebaseId;
}
public void setFirebaseId(String firebaseId) {
this.firebaseId = firebaseId;
}
}
And then store value like below
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference databaseReference = firebaseDatabase.getReference(DATABASE_NAME);
String fireBaseId = databaseReference.push().getKey();
if (fireBaseId != null) {
User user = new User();
user.setName("SSB");
user.setAddress("Some address");
user.setFirebaseId(fireBaseId);
databaseReference.child(fireBaseId).setValue(user);
}
Then you can get id from user model class
I am trying to fetch data from my Parse database and display it into a RecyclerView. From my knowledge I cannot see what I have done wrong and when I run the app not errors occur, and when opening this very fragment the app doesn't crash just shows a blank screen.
Any idea what is the problem?
Businesses
package zafir.com.app;
import com.parse.ParseClassName;
import com.parse.ParseObject;
#ParseClassName("Businesses")
public class Businesses extends ParseObject
{
private String Name;
public String getName()
{
return getString("Name");
}
public void setName(String name)
{
put("Name", name);
}
public String getCategory()
{
return getString("Category");
}
public void setCategory(String category)
{
put("Category", category);
}
public String getEmail()
{
return getString("Email");
}
public void setEmail(String email)
{
put("Email", email);
}
public String getLocation()
{
return getString("Location");
}
public void setLocation(String location)
{
put("Location", location);
}
public String getPhone()
{
return getString("Phone");
}
public void setPhone(String phone)
{
put("Phone", phone);
}
public String getWebsite()
{
return getString("Website");
}
public void setWebsite(String website)
{
put("Website", website);
}
}
RecyclerAdapter
public static class ViewHolder extends RecyclerView.ViewHolder
{
public TextView zName;
public TextView zPhone;
public TextView zEmail;
public TextView zWebsite;
public TextView zLocation;
public TextView zCategory;
public ViewHolder(View itemView)
{
super(itemView);
zName = (TextView) itemView.findViewById(R.id.name);
zPhone = (TextView) itemView.findViewById(R.id.phone);
zEmail = (TextView) itemView.findViewById(R.id.email);
zWebsite = (TextView) itemView.findViewById(R.id.website);
zLocation = (TextView) itemView.findViewById(R.id.location);
zCategory = (TextView) itemView.findViewById(R.id.category);
}
}
public RecyclerAdapter(Context context,List<Businesses> data)
{
inflater=LayoutInflater.from(context);
this.data= data;
}
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View recView = inflater.inflate(R.layout.recycler_layout, parent, false);
ViewHolder ViewHolder = new ViewHolder(recView);
return ViewHolder;
}
#Override
public void onBindViewHolder(RecyclerAdapter.ViewHolder viewHolder, int position)
{
Businesses businesses = data.get(position);
TextView name = viewHolder.zName;
name.setText(businesses.getName());
TextView phone = viewHolder.zPhone;
phone.setText(businesses.getPhone());
TextView email = viewHolder.zEmail;
email.setText(businesses.getEmail());
TextView website = viewHolder.zWebsite;
website.setText(businesses.getWebsite());
TextView location = viewHolder.zLocation;
location.setText(businesses.getLocation());
TextView category = viewHolder.zCategory;
category.setText(businesses.getCategory());
}
#Override
public int getItemCount()
{
return data.size();
}
}
Categories(Fragment)
public class Categories extends Fragment
{
List<Businesses> data = new ArrayList<>();
private RecyclerView zRecyclerView;
private RecyclerAdapter zAdapter;
private RecyclerView.LayoutManager zLayoutManager;
public Categories()
{
// Required empty public constructor
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_categories,container, false);
zRecyclerView = (RecyclerView) rootView.findViewById(R.id.recview_categories);
zRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
getData();
return super.onCreateView(inflater, container, savedInstanceState);
}
public void getData()
{
final List<Businesses> data = new ArrayList<>();
ParseQuery<Businesses> query = new ParseQuery<>("Businesses");
query.findInBackground(new FindCallback<Businesses>()
{
#Override
public void done(List<Businesses> list, ParseException e)
{
if(e == null)
{
for(Businesses businesses : list)
{
Businesses bizList = new Businesses();
bizList.setNames(businesses.getNames());
bizList.setPhone(businesses.getPhone());
bizList.setEmail(businesses.getEmail());
bizList.setWebsite(businesses.getWebsite());
bizList.setLocation(businesses.getLocation());
bizList.setCategory(businesses.getCategory());
data.add(bizList);
}
zAdapter = new RecyclerAdapter(getActivity(), data);
zRecyclerView.setAdapter(zAdapter);
}
}
});
}
}
Everything looks good. You just have to call notifyDataSetChanged() on zAdapter whenever you are changing the data. So change your code like this:
zAdapter = new RecyclerAdapter(getActivity(), data);
zRecyclerView.setAdapter(zAdapter);
zAdapter.notifyDataSetChanged();