I cant find a way to set image to imageView from drawable folder depending on string data received from Firebase Database.
I get values from Firebase Database like this:
DatabaseReference personsRef = FirebaseDatabase.getInstance().getReference().child("Persons");
Query personsQuery = personsRef.orderByKey();
FirebaseRecyclerOptions personsOptions = new FirebaseRecyclerOptions.Builder<Adapter>().setQuery(personsQuery, Adapter.class).build();
mAdapter = new FirebaseRecyclerAdapter<Adapter, Tab1.MyViewHolder>(personsOptions) {
#Override
protected void onBindViewHolder(Tab1.MyViewHolder holder, final int position, final Adapter model) {
holder.setTitle(model.getTitle());
holder.setDate(model.getDate());
}
#Override
public Tab1.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycle_tab1, parent, false);
return new Tab1.MyViewHolder(view);
}
};
The goal is to populate imageViews in RecyclerView with images from drawable folder depending on data loaded from Firebase. Something like: if "title" loaded from firebase = 1, set imageView to R.drawable.thisPerson1.
You can append your received string to ImageView Resource ID
DatabaseReference personsRef = FirebaseDatabase.getInstance().getReference().child("Persons");
Query personsQuery = personsRef.orderByKey();
FirebaseRecyclerOptions personsOptions = new FirebaseRecyclerOptions.Builder<Adapter>().setQuery(personsQuery, Adapter.class).build();
mAdapter = new FirebaseRecyclerAdapter<Adapter, Tab1.MyViewHolder>(personsOptions) {
#Override
protected void onBindViewHolder(Tab1.MyViewHolder holder, final int position, final Adapter model) {
holder.setTitle(model.getTitle());
holder.setDate(model.getDate());
holder.yourImageView.setImageResource(R.drawable+"."+model.getImage())
}
#Override
public Tab1.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycle_tab1, parent, false);
return new Tab1.MyViewHolder(view);
}
};
If title is number like 0..10 then u could try to create res array:
if 1..10 then try to use model.getTitle() - 1 etc.
<integer-array name="some_name">
<item>#drawable/thisPerson1</item>
<item>#drawable/thisPerson2</item>
<item>#drawable/thisPerson3</item>
<item>#drawable/thisPerson4</item>
</integer-array>
private TypedArray imagesArray = getResources().obtainTypedArray(R.array.some_name);
private int image = imagesArray.getResourceId(imagesArray.getIndex(title), defaultValue)
ImageView.setBackgroundResource(image)
imagesArray.recycle()
Related
Hello so I have a function in an app where you will add a data from the adapter if the quantity is non-zero and it will be saved to the firebase realtime database. What i wanna do is if the other item in adapter is non-zero it will add a child to the database but instead firebase is just replacing the item instead of adding a new child what should i do?
here is the code
public class UsualFragRViewAdapter extends RecyclerView.Adapter <UsualFragRViewAdapter.ViewHolder> {
private List<FragmentsUsualModels> items;
private Context context;
public UsualFragRViewAdapter( Context context,List<FragmentsUsualModels> items ) {
this.context = context;
this.items = items;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_usual_array, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
final FragmentsUsualModels arrayitems = items.get(position);
holder.itemName.setText(arrayitems.getItemName());
holder.price.setText(String.valueOf("$ " +arrayitems.getPrice()));
holder.quantity.setNumber(arrayitems.getQuantity());
holder.card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
holder.quantity.setOnValueChangeListener(new ElegantNumberButton.OnValueChangeListener() { //all items are located in its positions
#Override
public void onValueChange(ElegantNumberButton view, int oldValue, int newValue) { //Need to pass all non-zero items as chatview
arrayitems.setQuantity(String.valueOf(newValue));
if (newValue !=0){
String datavalue = holder.itemName.getText().toString();
String dataprice = holder.price.getText().toString();
String dataquantity = holder.quantity.getNumber().toString();
DatabaseReference data = FirebaseDatabase.getInstance().getReference("itemdata");
data.child("dataname").setValue(datavalue);
data.child("dataprice").setValue(dataprice);
data.child("dataquantity").setValue(dataquantity);
Log.d(TAG, "the new value of this data is: " +dataquantity);
Log.d(TAG, "the itemname of this position is: "+datavalue);
Log.d(TAG, "the price of this item in this position is: " +dataprice);
}
Log.d(TAG, "user changed the quantity in this position to " +arrayitems);
}
});
}
#Override
public int getItemCount() {
return items.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CardView card;
ImageView image;
TextView itemName;
TextView price;
ElegantNumberButton quantity;
Button donebtn;
public ViewHolder(#NonNull View itemView) {
super(itemView);
card = itemView.findViewById(R.id.ucard);
image = itemView.findViewById(R.id.uimage);
itemName = itemView.findViewById(R.id.uitemName);
price = itemView.findViewById(R.id.uprice);
quantity = itemView.findViewById(R.id.uquantity);
donebtn = itemView.findViewById(R.id.udonebtn);
}
}
}
If you want to generate a new child node under a location, call push() on that DatabaseReference. So to create a new child node under itemdata:
DatabaseReference data = FirebaseDatabase.getInstance().getReference("itemdata");
DatabaseReference newData = data.push();
Now you can write the data to this new location as:
newData.child("dataname").setValue(datavalue);
newData.child("dataprice").setValue(dataprice);
newData.child("dataquantity").setValue(dataquantity);
One additional change to consider is the reducing the number of writes. Your current code does a separate setValue() call for each property. This works, but it means that any listeners will get called three times, once for each property.
While this may be what you want, it is quite common to want these writes to appear as one operation. If that is the case, you can perform a single setValue() with:
Map<String,Object> values = new HashMap<>();
values.put("dataname", datavalue);
values.put("dataprice", dataprice);
values.put("dataquantity", dataquantity);
newData.setValue(values);
The end result will be exactly the same as before, but now with a single write operation.
You should use push() to create unique id for database item
dataBase.child(/*CHILD*/).push().setValue(dataValue);
I want to display feed like Instagram i am using 2 layouts for that.
Using Recycle view in that adapter i check with view type for multi image or single image, for multi image i am using view pager .
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
switch (viewType) {
case ModelUser.VIEW_PAGER:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.feed_multi_photo, parent, false);
return new TextTypeViewHolder(view);
case ModelUser.IMAGE_TYPE:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.feed_photo, parent, false);
return new ImageTypeViewHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int listPosition) {
ModelUser object = dataSet.get(listPosition);
if (object != null) {
switch (object.type1) {
case ModelUser.VIEW_PAGER:
final SliderPagerAdapter sliderPagerAdapter = new SliderPagerAdapter((Activity) mContext, slider_image_list);
((TextTypeViewHolder) holder).mvViewPager.setAdapter(sliderPagerAdapter);
((TextTypeViewHolder) holder).mvViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
addBottomDots(position, ((TextTypeViewHolder) holder).ll_dots);
page = position;
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
On setting adapter data i am using
MultiViewTypeAdapter feedMainAdapter = new MultiViewTypeAdapter(feed_list,imagelist,context);
RecylerFeed.setAdapter(feedMainAdapter);
feed_list is for single image and imagelist is for multiimage so,my problem is in imagelist i am getting list of every images how can i differentiate those images for particular user?
my problem is in imagelist i am getting list of every images
Because, passing slider_image_list in SliderPagerAdapter which contains all user images.
how can i differentiate those images for particular user?
Create new user specific image list from slider_image_list before passing to ViewPager:
case ModelUser.VIEW_PAGER:
//Create new List of images for current user from `slider_image_list`
ArrayList<> currentUserImages=new ArrayList<>();
final SliderPagerAdapter sliderPagerAdapter =
new SliderPagerAdapter((Activity) mContext, currentUserImages);
....
break;
Add RecyclereView in
feed_multi_photo
And inside onBindViewHolder
switch (object.type1) {
case ModelUser.VIEW_PAGER:
//Impement Nested RecyclerAdapter of Multiple Image using imagelist
InnerRecyclerviewAdapter adapter=new InnerRecyclerviewAdapter(context,imagelist);
holder.recyclerView.setAdapter(adapter);
holder.recyclerView.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(layoutManager);
I have node of "genresComments" that saves comments of each user to for each video id. It goes like that Genre -> video ID -> user ID:Data.
What im trying to get is all the user's id and their data (The data i mean:comment,profilePicture,username).
thats the query that should point to that data
Query query = FirebaseDatabase.getInstance().getReference(Params.GENRESCOMMENTS).child(genre).child(videoID);
But i'm sure that it points only on the "users id" and not bringing me the inside data that i need.
My question is how do i get for each "video id" all his "user id" and his data (comment,profilePicture,username).
EDIT
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
videoID = getArguments().getString(Params.VIDEOID);
genre = getArguments().getString(Params.GENRE);
progressBar.setVisibility(View.VISIBLE);
if(videoID != null){
Query query = FirebaseDatabase.getInstance().getReference(Params.GENRESCOMMENTS).child(genre).child(videoID);
options = new FirebaseRecyclerOptions.Builder<Comment>().setQuery(query,Comment.class).build();
adapter = new FirebaseRecyclerAdapter<Comment,CommentsViewHolder>(options) {
#Override
protected void onBindViewHolder(CommentsViewHolder holder, int position, Comment model) {
holder.userName.setText(model.getUserName());
holder.comment.setText(model.getComment());
Glide.with(getContext()).load(model.getUserProfile()).into(holder.userProfile);
}
#Override
public CommentsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.comment_item,parent,false);
return new CommentsViewHolder(view) ;
}
};
}
if(adapter != null) {
rvComments.setAdapter(adapter);
rvComments.setLayoutManager(new LinearLayoutManager(getContext()));
}
}
I use this query for recycler view
Do like below code (it may get errors): learn about event listener first
FirebaseDatabase.getInstance().getReference(Params.GENRESCOMMENTS).child(genre).child(videoID).addValueEventListener(new ValueEventListener(Datasnapshot snap){
for(DataSnapshot s:snap.getChildren()){
Comment c=s.getValue(Comment.class);
//c.getPRofilePic c.getComment();
}
});
class Comment {
private String comment;
private String profilePic;
private String username;
//getter setter
}
I want to retrieve data in ascending order, but received data somehow added to recyclerview in descending order.
Firebase Database:
What I am doing:
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("/Teacher");
Query query = mDatabase.orderByChild("rating");
FirebaseRecyclerOptions<Teacher> options =
new FirebaseRecyclerOptions.Builder<Teacher>()
.setQuery(query, Teacher.class)
.build();
FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<Teacher, TeacherViewHolder>(options) {
#NonNull
#Override
public TeacherViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.teacher_list_item, parent, false);
return new TeacherViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull final TeacherViewHolder holder, int position, #NonNull final Teacher model) {
// some stuff here
}
};
Since you can't do that natively with the RTDB, you'll probably want to do something like this:
LinearLayoutManager layoutManager = new LinearLayoutManager(context);
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);
See https://stackoverflow.com/a/27727398/4548500 for more details.
To get a sorted and filtered result, you have to pass a query into the FirebaseRecyclerAdapter constructor:
public MyFireAdapterDiasFiestaRecyclerView(
Class<DiaFiestaMeta> modelClass,
int modelLayout,
Class<MyFireViewHolder> viewHolderClass,
Query query) {
...
And then invoke it with a query that orders and filters:
adapter = new MyFireAdapterDiasFiestaRecyclerView(
DiaFiestaMeta.class,
layout_that_you_use,
MyFireViewHolder.class,
ref.orderByChild("property_to_sort_and_filter_on").equalTo("value_to_filter_on")
);
I have an app I am working on that needs live queries using location from the user. Writing to the geofire node is okay but I have trouble on reading. Once I get the id's how do I make a query with them and display data using the firebase recycleradapter?
Here is my code so far (without Geofire):
FirebaseRecyclerOptions<Venue> options =
new FirebaseRecyclerOptions.Builder<Venue>()
.setQuery(filterRef, Venue.class)
.build();
adapter = new FirebaseRecyclerAdapter<Venue, VenueViewHolder>(options) {
#Override
public VenueViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.single_venue_item, parent, false);
return new VenueViewHolder(view);
}
#Override
protected void onBindViewHolder(final VenueViewHolder holder, final int position, Venue model) {
final String venueName = model.getVenueName();
holder.venueName.setText(venueName);
Glide.with(holder.mView.getContext())
.load(model.getVenueMainImage())
.apply(new RequestOptions()
.placeholder(R.mipmap.ic_launcher_round))
.into(holder.venueMainImage);
}
};
venuesRecyclerView.setLayoutManager(mLinearLayoutManager);
venuesRecyclerView.setAdapter(adapter);