I can get images and titles, texts in my post_row layout from my Firebase Server.
I want to click each items in the Recyclerview and I searched on them on google. but I couldn't find suitable codes implementing the click event in FirebaseRecyclerView.
and This is my FirebaseRecycler Adapter code!
thank you ~~!!
mDatabase = FirebaseDatabase.getInstance().getReference().child("post");
#Override
protected void onStart() {
super.onStart();
final Query DBquery = FirebaseDatabase.getInstance().getReference().child("post").orderByChild("count");
FirebaseRecyclerAdapter<Post, PostViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(
Post.class,
R.layout.post_row,
PostViewHolder.class,
DBquery
mDatabase
) {
#Override
protected void populateViewHolder(PostViewHolder viewHolder, Post model, int position) {
viewHolder.setTitle(model.getTitle());
viewHolder.setDesc(model.getDesc());
viewHolder.setImage(getApplicationContext(), model.getImage());
viewHolder.setDate(model.getDate());
}
};
mPostList.setAdapter(firebaseRecyclerAdapter);
}
public static class PostViewHolder extends RecyclerView.ViewHolder {
View mView;
public PostViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setTitle(String title){
TextView post_title = mView.findViewById(R.id.post_title);
post_title.setText(title);
}
public void setDesc(String desc){
TextView post_desc = mView.findViewById(R.id.post_desc);
post_desc.setText(desc);
}
public void setImage(Context ctx, String image){
ImageView post_image = mView.findViewById(R.id.post_image);
Picasso.get().load(image).into(post_image);
}
public void setDate(String date){
TextView post_date = mView.findViewById(R.id.post_date);
post_date.setText(date);
}
}
`
Use a listview to show your data, I use it like this and it's working really good.
Just inside populateViewHolder
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
mDatabase = mAdapter.getRef(position);
Intent intent = new Intent(MainActivity.this, UserEdit.class);
intent.putExtra("uid",mDatabase.getKey());
intent.putExtra("name", mAdapter.getItem(position).getNombre());
intent.putExtra("Email", mAdapter.getItem(position).getEmail());
intent.putExtra("paid", mAdapter.getItem(position).getPago());
intent.putExtra("connection", mAdapter.getItem(position).getUConexion());
intent.putExtra("connection2", mAdapter.getItem(position).getPConexion());
startActivity(intent);
}
});
mListView.setAdapter(mAdapter);
This is just an example from my code, it just clicks the list, get the item and pass it to another activity to work with that data.
With this you are setting the adapter data into a listview, and then clicking each item gives you the data of that position and you can manage that data in another activity if you need it.
The getters I'm using at the putExtras are being passed by the POJO class to the FirebaseList.
FirebaseListOptions<Usuarios> options = new FirebaseListOptions.Builder<Usuarios>()
.setQuery(query, Usuarios.class)
.setLayout(R.layout.item_row)
.build();
Here Usuarios is this:
private String Nombre;
private String Dispositivo;
private String sexo;
private String lenguaje;
private String email;
public Usuarios(){}
public Usuarios(String nombre, String dispositivo, String sexo, String lenguaje, String email, String PConexion, String UConexion, String URL_frases, String URL_grupos, String URL_pictos, String edad, String pago) {
Nombre = nombre;
Dispositivo = dispositivo;
this.sexo = sexo;
this.lenguaje = lenguaje;
this.email = email;
....
}
public String getNombre() {
return Nombre;
}
public void setNombre(String nombre) {
Nombre = nombre;
}
public String getDispositivo() {
return Dispositivo;
}
....
Remember, here the variables nombre, email and so one need to be declared exactly as the Firebase database ones, otherwise you will see blank and results won't display, and remember in your onStart to place mAdapter.startListening();.
Add a function in your PostViewHolder say
public void init(int position){
itemView.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) {
//Handle your click here
}
});
}
Now from populateViewHolder call
viewHolder.init(position);
To solve this, in your PostViewHolder class attach a click listener on your view like this:
mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Do what you need to do
}
});
If you want to add a click listener on each view, then just find the views inside the mView object and attach the listener on each one of them. That's it!
Make ImageView Object outside the function as you did for mView .
And then in the populateViewHolder just add
viewHolder.imageView.setOnClickListener()
It'll work fine Guaranteed
Related
I've been using ListVeiw implementation provided by Firebase-ui available in this link.
I intend to put a OnClick Listener for each row.When pressed it should change background color, But I could not find any way to get it done.Any help would be great.
-- Done So Far--
Activity
public class AddActivity extends AppCompatActivity {
//Databse refernce
FirebaseDatabase database= FirebaseDatabase.getInstance();
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
listView = findViewById(R.id.listveiw);
Query query = FirebaseDatabase.getInstance()
.getReference("l")
.child("p")
.limitToLast(50);
FirebaseListOptions<ListItem> options = new FirebaseListOptions.Builder<ListItem>()
.setLayout(R.layout.listitem)
.setQuery(query, ListItem.class)
.build();
FirebaseListAdapter<ListItem> adapter = new FirebaseListAdapter<ListItem>(options) {
#Override
protected void populateView(View v, ListItem model, int position) {
String s = model.getName();
TextView a= v.findViewById(R.id.textView2);
a.setText(s);
s=model.getWatch();
a= v.findViewById(R.id.textView3);
a.setText(s);
ImageButton b= v.findViewById(R.id.imageButton);
}
};
listView.setAdapter(adapter);
}
}
ListItem.class
public class ListItem {
private String name;
private String watch;
public ListItem(){}
public ListItem(String name,String watch){
this.name=name;
this.watch=watch;
}
public String getName() {
return name;
}
public String getWatch() {
return watch;
}
public void setName(String name) {
this.name = name;
}
public void setWatch(String watch) {
this.watch = watch;
}
}
You may set click event like this in listView inside populateView(...)
mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(this, YourActivity.class);
intent.putExtra(TITLE, title);
intent.putExtra(CONTENT, content);
intent.putExtra(KEY, key);
startActivity(intent);
}
I am using FirebaseUI to get some values from my real-time database to Firebase RecyclerView. So.. my data looks like that:
users:
userid:
info:
Name:Muhammad
I don't know how to get the value of Name which means what exactly should I do in the Users class? Here is my code (I think that the problem is in class user, I just don't know how to access child info)
public class User {
private String name;
private String email;
private String state;
private String image;
private String thumbnail;
public User(String name, String state, String image) {
this.name = name;
this.state = state;
this.image = image;
}
public User() {
}
public String getName() {
return name;
}
public String getState() {
return state;
}
public String getImage() {
return image;
}
}
my Main Activity
myDB refer to and on start method (updated after SUPERCILEX comment )
mDb = FirebaseDatabase.getInstance().getReference().child(App_Constants.USERS_COLUMN);
#Override
protected void onStart() {
super.onStart();
Query query = mDb;
FirebaseRecyclerOptions<User> options = new FirebaseRecyclerOptions.Builder<User>()
.setQuery(query, new SnapshotParser<User>() {
#NonNull
#Override
public User parseSnapshot(#NonNull DataSnapshot snapshot) {
String Name = snapshot.child(App_Constants.INFO_COLUMN).child(App_Constants.NAME_COLUMN).getValue().toString();
String State = snapshot.child(App_Constants.INFO_COLUMN).child(App_Constants.STATE_COLUMN).getValue().toString();
String Image = snapshot.child(App_Constants.INFO_COLUMN).child(App_Constants.IMAGE_COLUMN).getValue().toString();
User user = new User(Name,State,Image);
return user;
}
}).build();
FirebaseRecyclerAdapter<User,Users_ViewHolder> adapter = new FirebaseRecyclerAdapter<User, Users_ViewHolder>(options) {
#NonNull
#Override
public Users_ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_user,parent,false);
return new Users_ViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull Users_ViewHolder holder, int position, #NonNull User model) {
holder.Set_Name(model.getName());
holder.Set_Image(model.getImage());
holder.Set_State(model.getState());
}
};
mUsers.setAdapter(adapter);
}
my ViewHolder
public class Users_ViewHolder extends RecyclerView.ViewHolder{
View mView;
public Users_ViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void Set_Name(String Name)
{
TextView mName = mView.findViewById(R.id.tv_single_user_name);
mName.setText(Name);
}
public void Set_Image(String url)
{
CircleImageView mImage = mView.findViewById(R.id.iv_single_user);
Picasso.get().load(url).placeholder(R.drawable.profile).into(mImage);
}
public void Set_State(String State)
{
TextView mState = mView.findViewById(R.id.tv_single_user_state);
mState.setText(State);
}
}
thanks
I believe it'll come in as a Map<String, Object> on the field info. However, you can always use a custom SnapshotParser to build your model to your liking: https://github.com/firebase/FirebaseUI-Android/blob/master/database/README.md#using-the-firebaserecycleradapter.
Some Advices :would you mind changing the set methods names?
from Set_State to setState,I too had similar problems please respect Java naming conventions
Also add the set methods in your custom model
Second:
FirebaseRecyclerOptions<User> options =
new FirebaseRecyclerOptions.Builder<User>()
.setQuery(query, User.class)
.build();
Start Listening:
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
stopListening() call removes the event listener and all data in the adapter
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
Here you have a very good explained example
everyone.
Hello. I’ve created android application. I am retrieving data from real-time database and also using recycle view + view holder. But when I go to another activity and then go back - my list oh view holder items was reset. How I can save state view holder and restore them?
I looked at various topics on the site, but not one answer did not help me.
My Pojo Class
public class Post {
private String post_id;
private String post_title;
private long post_date;
private long post_desc;
public Post(String post_id, String post_title, long post_date, String post_desc) {
this.post_id = post_id;
this.post_title = post_title;
this.comments_count = comments_count;
this.post_date = post_date;
this.post_desc = post_desc;
}
public void setPost_id(String post_id) {
this.post_id = post_id;
}
public String getPost_title() {
return post_title;
}
public void setPost_title(String post_title) {
this.post_title = post_title;
}
public String getPost_date() {
String month = new java.text.SimpleDateFormat("MM").
format(new java.util.Date(post_date * 1000));
int monthnumber = Integer.parseInt(month);
String value = new java.text.SimpleDateFormat("dd ").
format(new java.util.Date(post_date * 1000));
value +=MonthName[monthnumber-1];
value+= new java.text.SimpleDateFormat(" HH:mm").
format(new java.util.Date(post_date * 1000));
return value;
}
public void setPost_date(long post_date) {
this.post_date = post_date;
}
public String getPost_desc() {
return post_desc;
}
public void setPost_desc(String post_desc) {
this.post_desc = post_desc;
}}
ViewHolderClass
public static class PostViewHolder extends RecyclerView.ViewHolder {
public PostViewHolder(View itemView) {
super(itemView); }
public void setTitle(String title) {
titleViewPost.setText(title);
}
public void setDate(String date) {
dateViewPost.setText(date);
}
public void setDesc(String desc) {
descViewPost.setText(desc);
}}}
FirebaseRecyleAdapter
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder >(
Post.class,
R.layout.post_row,
PostViewHolder.class,
mDatabase
) {#Override
protected void populateViewHolder(final PostViewHolder viewHolder,
Post model, final int position) {
viewHolder.mCommentButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent commentActivity = new Intent(MainActivity.this, CommentActivity.class);
commentActivity.putExtra("post_id", post_key);
if(mUserId != null) {
commentActivity.putExtra("user_id", mUserId);
}
startActivity(commentActivity);
}
});
As I understand, the whole problem is that my adapter is reused and I can not return to that position in the tape - where I was before.
Its my app.https://play.google.com/store/apps/details?id=dev.arounda.chesnock
I want fix thiw trouble for this application
Try to call firebaseRecyclerAdapter.startListening(); in onCreate() instead of onStart and firebaseRecyclerAdapter.stopListening(); in onDestroy() instead of onStop()
I have implemented recyclerview with cardview using firebase real time database, I'm facing problem in passing data to another activity , when user clicks on cardview then data should pass from cardview to another activity called " DetailActivity" then DetailActivity should open
Here is firebase adapter
FirebaseRecyclerAdapter<Food,FoodViewHolder> adapter = new FirebaseRecyclerAdapter<Food, FoodViewHolder>(
Food.class,
R.layout.food_item,
FoodViewHolder.class,
//referencing the node where we want the database to store the data from our Object
mDatabaseReference.child("users").child(userId).child("food").getRef()
) {
#Override
protected void populateViewHolder(FoodViewHolder viewHolder, final Food model, int position) {
if(tvNoMovies.getVisibility()== View.VISIBLE){
tvNoMovies.setVisibility(View.GONE);
}
viewHolder.tvFoodName.setText(model.getFoodName());
viewHolder.ratingBar.setRating(model.getFoodRating());
viewHolder.tvFoodCategory.setText(model.getFoodCategory());
viewHolder.tvFoodAvailableUpto.setText(model.getFoodAvailableUpto());
viewHolder.tvFoodPrice.setText(model.getFoodPrice());
Picasso.with(getActivity().getApplicationContext()).load(model.getFoodPoster()).into(viewHolder.ivFoodPoster);
}
};
mRecyclerView.setAdapter(adapter);
Here is my viewholder.class
public static class FoodViewHolder extends RecyclerView.ViewHolder{
TextView tvFoodName;
RatingBar ratingBar;
ImageView ivFoodPoster;
TextView tvFoodCategory;
TextView tvFoodAvailableUpto;
TextView tvFoodPrice;
public FoodViewHolder(View v) {
super(v);
tvFoodName = (TextView) v.findViewById(R.id.tvName);
ratingBar = (RatingBar) v.findViewById(R.id.rating_bar);
ivFoodPoster = (ImageView) v.findViewById(R.id.imgThumb);
tvFoodCategory = (TextView) v.findViewById(R.id.tvCategory);
tvFoodAvailableUpto= (TextView) v.findViewById(R.id.tvavailable);
tvFoodPrice = (TextView) v.findViewById(R.id.tvprice);
}
}
Here is my Food.class
public class Food {
public String foodName;
public String foodPoster;
public float foodRating;
public String foodCategory;
public String foodAvailableUpto;
public String foodPrice;
public Food(){
}
public Food(String foodName,String foodPoster,float foodRating, String foodCategory , String foodAvailableUpto , String foodPrice){
this.foodName = foodName;
this.foodPoster = foodPoster;
this.foodRating = foodRating;
this.foodCategory = foodCategory;
this.foodAvailableUpto = foodAvailableUpto;
this.foodPrice = foodPrice;
}
Here is the screenshot of recycleview with cardview
Now You can send the user to other activity when he clicks the food name(for example):
FirebaseRecyclerAdapter<Food,FoodViewHolder> adapter = new FirebaseRecyclerAdapter<Food, FoodViewHolder>(
Food.class,
R.layout.food_item,
FoodViewHolder.class,
//referencing the node where we want the database to store the data from our Object
mDatabaseReference.child("users").child(userId).child("food").getRef()
) {
#Override
protected void populateViewHolder(FoodViewHolder viewHolder, final Food model, int position) {
if(tvNoMovies.getVisibility()== View.VISIBLE){
tvNoMovies.setVisibility(View.GONE);
}
viewHolder.tvFoodName.setText(model.getFoodName());
viewHolder.tvFoodName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),Activity2.class);//replace activity2 with ur intended activity
intent.putExtra();//put whatever data you need to send
startActivity(intent)
}
});
viewHolder.ratingBar.setRating(model.getFoodRating());
viewHolder.tvFoodCategory.setText(model.getFoodCategory());
viewHolder.tvFoodAvailableUpto.setText(model.getFoodAvailableUpto());
viewHolder.tvFoodPrice.setText(model.getFoodPrice());
Picasso.with(getActivity().getApplicationContext()).load(model.getFoodPoster()).into(viewHolder.ivFoodPoster);
}
};
mRecyclerView.setAdapter
(adapter);
I am trying to show my integers saved in the firebase database in my Recyclerview. I have two Strings I can easily show in my App, but somehow it doesn't work with integers. Even more strange is that when I save a String where before there was an integer I got an error.
Here my database structure
Here I populate my Viewholder
#Override
public void onStart() {
super.onStart();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<ListItem, ListViewHolder>(
ListItem.class,
R.layout.card_item,
ListViewHolder.class,
mDatabase.orderByChild("minusAccandShare").endAt(0)
) {
#Override
protected void populateViewHolder(ListViewHolder viewHolder, ListItem model, final int position) {
viewHolder.setImage(getActivity().getApplicationContext(), model.getImage());
viewHolder.setHeading(model.getHeading());
viewHolder.setStoreName(model.getStoreName());
viewHolder.setAcceptCount(model.getAcceptCount());
viewHolder.mView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Intent i = new Intent(getActivity(), DetailActivity.class);
Bundle extras = new Bundle();
extras.putString(EXTRA_QUOTE, firebaseRecyclerAdapter.getRef(position).getKey());
i.putExtra(BUNDLE_EXTRAS, extras);
startActivity(i);
}
});
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
My ViewHolder
public static class ListViewHolder extends RecyclerView.ViewHolder {
View mView;
public ListViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setImage(Context ctx, String image){
ImageView postImage = (ImageView) mView.findViewById(R.id.im_item_icon);
Picasso.with(ctx).load(image).resize(200,200).into(postImage);
}
public void setHeading(String heading){
TextView card_heading = (TextView) mView.findViewById(R.id.lbl_item_sub_title);
card_heading.setText(heading);
}
public void setStoreName(String storeName){
TextView card_storeName = (TextView) mView.findViewById(R.id.lbl_item_text);
card_storeName.setText(storeName);
}
public void setAcceptCount(String accepts){
TextView accepts_count = (TextView) mView.findViewById(R.id.lbl_accepts_count);
accepts_count.setText(accepts);
}
}
And finally my model
public class ListItem {
private String heading, storeName, image;
private Long accepts;
public ListItem() {
}
public ListItem(String heading,String storeName, Long accepts, String image){
this.heading = heading;
this.storeName = storeName;
this.image = image;
this.accepts = accepts;
}
public String getHeading() {
return heading;
}
public String getStoreName() {
return storeName;
}
public String getImage() {return image;}
public String getAcceptCount() {
return String.valueOf(accepts);
}
In this way I see null where there should stand 200 instead. I tried everything. I even saved an String instead of an integer and tried to show it the same way as the heading String ( which works perfectly) but then I see a blank place... Please help. Thanks
you should create a getter and setter for accepts in ListItem.
public Long getAccepts() {
return accepts;
}
public void setAccepts(Long accepts) {
this.accepts = accepts;
}