this is my db structure
I have a list of passenger and i want to retrive them from the firebase database if the passenger list contains more than one passenger then i want to get those data show in one textView. But everytime it generates 2 textView if there were two passenger. I want in all cases it shows all the data in just one TextView.
This is my model Class`
public class RetrieveTickets {
private String name;
private String age;
private String gender;
public RetrieveTickets() {
}
public RetrieveTickets(String name, String age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public List<HashMap<String,Object>> toList(){
List<HashMap<String,Object>> list=new ArrayList<>();
HashMap<String,Object> map=new HashMap<>();
map.put("name",getName());
map.put("age",getAge());
map.put("gender",getGender());
list.add(map);
return list;
}
}
this is MyActivity where i am showing the data
public class MyBookingsActivity extends AppCompatActivity{
private RecyclerView recyclerView;
private DatabaseReference databaseReference;
private FirebaseAuth mAuth;
private FirebaseRecyclerAdapter<RetrieveTickets, BookingHolder> firebaseRecyclerAdapter;
public static List<String> trips=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_bookings);
recyclerView = (RecyclerView) findViewById(R.id.my_bookings);
recyclerView.setHasFixedSize(true);
String tripId = getIntent().getStringExtra("TripId");
trips.add(tripId);
// String bookingId = getIntent().getStringExtra("BookingId");
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
String userId = user.getUid();
databaseReference = FirebaseDatabase.getInstance().getReference();
Query query = databaseReference.child("BooKings").child(userId).child(tripId).child("passenger");
FirebaseRecyclerOptions<RetrieveTickets> firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<RetrieveTickets>()
.setQuery(query, RetrieveTickets.class)
.build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<RetrieveTickets, BookingHolder>(firebaseRecyclerOptions) {
#Override
protected void onBindViewHolder(#NonNull BookingHolder holder, int position, #NonNull RetrieveTickets model) {
holder.setPassengers(model);
}
#NonNull
#Override
public BookingHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.tickets, parent, false);
return new BookingHolder(view);
}
#Override
public void onError(#NonNull DatabaseError error) {
super.onError(error);
Toast.makeText(MyBookingsActivity.this,"error"+error,Toast.LENGTH_LONG).show();
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
#Override
protected void onStart() {
super.onStart();
firebaseRecyclerAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
if (firebaseRecyclerAdapter != null) {
firebaseRecyclerAdapter.stopListening();
}
}
public static class BookingHolder extends RecyclerView.ViewHolder{
private TextView passenger;
public BookingHolder(#NonNull View itemView) {
super(itemView);
passenger=(TextView)itemView.findViewById(R.id.passenger);
}
void setPassengers(RetrieveTickets retrieveTickets) {
passenger.setText(retrieveTickets.toList().toString());
}
}
If you want to display all passengers in one TextView then you shouldn't do like this... Right now you are using RecyclerView and it will make rows == number of passengers and its exactly why we use RecyclerView
If you want to show PassengerList in one textView do like this
StringBuilder passengerStrBuilder = new StringBuilder();
for (String details : yourList) {
passengerStrBuilder.append(details + "\n");
}
textView.setText(passengerStrBuilder.toString());
Here yourList is Passenger List
Related
i have facing issue like only two items are displayed others two items are not displayed they are contact and flat no this items are not displaying...i tried also removing and adding others textview but through this only two items are displayed.... Now I want to display the data on a RecyclerView which doesn't seem to work, I'm pretty sure that my code is good but something doesn't seem to work and I can't find it.i also try all the things suggested by stackoverflow but nothing can happen so that i think i need to ask...
Here the file
public class RecieptFP extends AppCompatActivity {
private RecyclerView mFirestoreList;
private FirebaseFirestore firebasefirestore;
private FirestoreRecyclerAdapter adapter;
Button Back;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reciept_fp);
Back = findViewById(R.id.btndashboard);
firebasefirestore = FirebaseFirestore.getInstance();
mFirestoreList = findViewById(R.id.firestore_list);
//query
Query query = firebasefirestore.collection("UserDataR");
//RecyclerOptions
FirestoreRecyclerOptions<RecieptModel> options = new FirestoreRecyclerOptions.Builder<RecieptModel>()
.setQuery(query, RecieptModel.class)
.build();
adapter = new FirestoreRecyclerAdapter<RecieptModel, RecieptViewHolder>(options) {
#NonNull
#Override
public RecieptViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listsingleiteam, parent, false);
return new RecieptViewHolder(view);
}
#Override
protected void onBindViewHolder(RecieptViewHolder recieptViewHolder, int i, RecieptModel recieptModel) {
recieptViewHolder.list_name.setText(recieptModel.getName());
recieptViewHolder.list_amount.setText(recieptModel.getAmount());
recieptViewHolder.list_contact.setText(recieptModel.getContact());
recieptViewHolder.list_Flatno.setText(recieptModel.getFlatNo());
}
};
//viewholder
mFirestoreList.setHasFixedSize(false);
mFirestoreList.setLayoutManager(new LinearLayoutManager(this));
mFirestoreList.setAdapter(adapter);
Back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i1 = new Intent(RecieptFP.this, Dashboard.class);
startActivity(i1);
}
});
}
private class RecieptViewHolder extends RecyclerView.ViewHolder {
private TextView list_name;
private TextView list_amount;
private TextView list_contact;
private TextView list_Flatno;
public RecieptViewHolder(#NonNull View itemView) {
super(itemView);
list_name = itemView.findViewById(R.id.list_name);
list_amount = itemView.findViewById(R.id.list_amount);
list_contact = itemView.findViewById(R.id.list_contact);
list_Flatno = itemView.findViewById(R.id.list_Flatno);
}
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
Recipet Model
package com.societypay;
public class RecieptModel {
private String Name;
private String Amount;
private String Contact;
private String FlatNo;
private RecieptModel(){}
private RecieptModel(String Name,String Amount,String Contact,String FlatNo){
this.Name=Name;
this.Amount=Amount;
this.Contact=Contact;
this.FlatNo=FlatNo;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getAmount() {
return Amount;
}
public void setAmount(String amount) {
Amount = amount;
}
public String getContact() {
return Contact;
}
public void setContact(String contact) {
Contact = contact;
}
public String getFlatNo() {
return FlatNo;
}
public void setFlatNo(String flatNo) {
FlatNo = flatNo;
}
}
Please use following pojo and try.
public class RecieptModel
{
private String MobileNo;
private String Amount;
private String Flat_no;
private String Name;
public String getMobileNo ()
{
return MobileNo;
}
public void setMobileNo (String MobileNo)
{
this.MobileNo = MobileNo;
}
public String getAmount ()
{
return Amount;
}
public void setAmount (String Amount)
{
this.Amount = Amount;
}
public String getFlat_no ()
{
return Flat_no;
}
public void setFlat_no (String Flat_no)
{
this.Flat_no = Flat_no;
}
public String getName ()
{
return Name;
}
public void setName (String Name)
{
this.Name = Name;
}
#Override
public String toString()
{
return "ClassPojo [MobileNo = "+MobileNo+", Amount = "+Amount+", Flat_no = "+Flat_no+", Name = "+Name+"]";
}
}
I'm still relatively new to Android and firebase and trying to populate recyclerview from firebase database but for some reasons that I can't get, the view is not populated.The activity loads but all I see is a blank activity page.I'd like to populate these views using data from a Firebase Database just to get three data(name,email,phonenos) of Users.
public class TestUsersActivity extends AppCompatActivity {
public TextView mname,email,phone;
private RecyclerView recyclerView;
FirebaseAuth mAuth;
DatabaseReference mDatabase;
private FirebaseRecyclerAdapter adapter;
private LinearLayoutManager linearLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_users);
recyclerView = findViewById(R.id.listuser);
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
fetch();
}
private void fetch() {
FirebaseRecyclerOptions<Users> options = new FirebaseRecyclerOptions.Builder<Users>()
.setQuery(mDatabase,Users.class)
.build();
adapter = new FirebaseRecyclerAdapter<Users, ViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull ViewHolder myViewHolder, int i, #NonNull Users users) {
myViewHolder.setName(users.getFname() + " "+ users.getLname());
myViewHolder.setEmail(users.getEmail());
myViewHolder.setphone(users.getPhonenos());
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_list_row,parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onDataChanged() {
super.onDataChanged();
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(View itemView) {
super(itemView);
mname = itemView.findViewById(R.id.name);
email = itemView.findViewById(R.id.email);
phone = itemView.findViewById(R.id.phoneNos);
}
public void setName(String string) {
mname.setText(string);
}
public void setEmail(String string) {
email.setText(string);
}
public void setphone(String string){
phone.setText(string);
}
}
}
Below is my modelclass that i want to get just the name,email and phone nos from.
public class Users {
private String fname;
private String lname;
private String email;
private String phonenos;
private String jobTitle;
private String dateCreated;
private String lastlogin;
public Users(){
}
public Users(String fname, String lname, String email, String phonenos, String jobTitle, String dateCreated, String lastlogin) {
this.fname = fname;
this.lname = lname;
this.email = email;
this.phonenos = phonenos;
this.jobTitle = jobTitle;
this.dateCreated = dateCreated;
this.lastlogin = lastlogin;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhonenos() {
return phonenos;
}
public void setPhonenos(String phonenos) {
this.phonenos = phonenos;
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public String getDateCreated() {
return dateCreated;
}
public void setDateCreated(String dateCreated) {
this.dateCreated = dateCreated;
}
public String getLastlogin() {
return lastlogin;
}
public void setLastlogin(String lastlogin) {
this.lastlogin = lastlogin;
}
}
I don't know if you must pass a query instead of a database reference
make the query a member variable
......
private Query query;
......
do this:
query = FirebaseDatabase.getInstance().getReference().child("Users");
and pass it like this to options
FirebaseRecyclerOptions<Users> options = new FirebaseRecyclerOptions.Builder<Users>()
.setQuery(query,Users.class)
.build();
ALSO MAKE SURE YOUR FIREBASE SECURITY RULES ARE NOT SET TO READ FALSE
This question already has an answer here:
Error in fetching data from Firebase to RecyclerView. FATAL EXCEPTION: ... does not define a no-argument constructor
(1 answer)
Closed 2 years ago.
I am trying to retrieve data from firebase realtime database on to my recyclerview . Earlier i was able to retrieve data on to my recyclerview but don't know what happened it suddenly started showing me error.
I get error in this line
User user=snapshot.getValue(User.class);
And this error in logcat window
com.google.firebase.database.DatabaseException: Class com.shivam.chatapp2.Model.User does not define a no-argument constructor. If you are using ProGuard, make sure these constructors are not stripped.
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.deserialize
My Full Code
UserAdapter.java:
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder> {
private Context mContext;
private List<User> mUsers;
public UserAdapter(Context mContext, List<User> mUsers) {
this.mContext = mContext;
this.mUsers = mUsers;
}
#NonNull
#Override
public UserAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(mContext).inflate(R.layout.user_item,parent,false);
return new UserAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull UserAdapter.ViewHolder holder, int position) {
final User user=mUsers.get(position);
holder.username.setText(user.getFirst());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(mContext, MessageActivity.class);
intent.putExtra("UserName",user.getFirst());
intent.putExtra("userid", user.getId());
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mUsers.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView username;
public ImageView profile_image;
public ViewHolder(#NonNull View itemView) {
super(itemView);
username=itemView.findViewById(R.id.username);
profile_image=itemView.findViewById(R.id.profile_image);
}
}
}
User.java:
public class User {
private String id;
private String First;
private String Last;
private String EmailID;
public User(String id, String first, String last, String emailID) {
this.id = id;
First = first;
Last = last;
EmailID = emailID;
}
public User(String userid, String first_name, String eMail) {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirst() {
return First;
}
public void setFirst(String first) {
First = first;
}
public String getLast() {
return Last;
}
public void setLast(String last) {
Last = last;
}
public String getEmailID() {
return EmailID;
}
public void setEmailID(String emailID) {
EmailID = emailID;
}
}
UserFragment.java:
public class UsersFragment extends Fragment {
private RecyclerView recyclerView;
private UserAdapter mUserAdapter;
private List<User> mUsers;
String TAG = "MyTag";
public UsersFragment() {
// 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_users, container, false);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mUsers = new ArrayList<>();
readUser();
return view;
}
private void readUser() {
final FirebaseUser firebaseUser=FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Users");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mUsers.clear();
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
User user=snapshot.getValue(User.class);
mUsers.add(user);
}
mUserAdapter=new UserAdapter(getContext(),mUsers);
recyclerView.setAdapter(mUserAdapter);
mUserAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
As per your error logs, it states that:
The User class doesnt has a default constructor with no parameters stated in the User.class file.
Add a default constructor to the User class in the User.class file like:
public User()
{
}
I'm retrieving data from firebase and trying to display that in recycler view, every thing is fine but it only shows one item in the list (there are total 14 items)
comment if you do not understand the question
This is my main activity where i get datasnapshots from firebase
public class cakes_activity extends AppCompatActivity {
RecyclerView recyclerView;
ArrayList<Data> listdata;
private DatabaseReference mref;
private NorthAdaptor north;
private final Context context = this;
public int counter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cakes);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
EditText editText = (EditText) findViewById(R.id.editText) ;
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//FIREBASE
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mref= FirebaseDatabase.getInstance().getReference("Cakes");
mref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Data data = dataSnapshot.getValue(Data.class);
listdata = new ArrayList<>();
listdata.add(data);
north = new NorthAdaptor(context,listdata);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.hasFixedSize();
recyclerView.setAdapter(north);
}
#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 the following code is my adaptor class:
public class NorthAdaptor extends RecyclerView.Adapter<NorthAdaptor.NorthHolder> {
private LayoutInflater inflater;
ArrayList<Data> northy;
public NorthAdaptor(Context context,ArrayList<Data> northy)
{
inflater=LayoutInflater.from(context);
this.northy=northy;
}
public NorthHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.each_item,parent,false);
NorthHolder holder = new NorthHolder(view);
return holder;
}
#Override
public void onBindViewHolder(NorthHolder holder, int position) {
holder.text2.setText(northy.get(position).getName());
holder.text3.setText("₹."+northy.get(position).getRS());
}
#Override
public int getItemCount() {
return northy.size();
}
class NorthHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
TextView text,text2,text3;
ImageView img;
private final Context context;
public NorthHolder(View itemview)
{
super(itemview);
context = itemView.getContext();
CardView card = (CardView) itemView.findViewById(R.id.card);
text3=(TextView)itemView.findViewById(R.id.Rs);
text2 = (TextView) itemView.findViewById(R.id.itemtext2);
img = (ImageView) itemView.findViewById(R.id.itemimage);
card.setOnClickListener(this);
}
#Override
public void onClick(View view){
Toast.makeText(
cakes_activity.this,
"Your message here",
Toast.LENGTH_SHORT
).show();
}
}
}
this is my java class to store the data received from firebase
public class Data {
private String ID,Name,image,RS;
public Data(){
}
public Data(String ID, String Name, String image, String RS) {
this.ID = ID;
this.Name = Name;
this.image= image;
this.RS = RS;
}
public String getId() {
return ID;
}
public String getRS() {
return RS;
}
public void setId(String id) {
this.ID = id;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String getimage() {
return image;
}
public void setImg(String image) {
this.image = image;
}
}
listdata = new ArrayList<>();
north = new NorthAdaptor(context,listdata);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.hasFixedSize();
recyclerView.setAdapter(north);
you need to write this code in onCreate instead of onchildadded
I have OrderCart from where I want to get sum of all the item prices so that it displays total price to the user
this is my Order class which has string price attribute
public class Order {
private String mID;
private String mName;
private String mPrice;
public Order(){
}
public Order(String id, String name, String price)
{
mID = id;
mName = name;
mPrice = price;
}
public String getmID() {
return mID;
}
public String getmName() {
return mName;
}
public String getmPrice() {
return mPrice;
}
and this is class where firebase adopter to retrieve data is present. The adopter displays all the children under OrderCart parent and total sum should be display below the adopter but it is giving errors
public class PlaceOrder extends AppCompatActivity {
private RecyclerView mOrderList;
private DatabaseReference mDatabase;
private int total_amount=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_open_orders);
mOrderList = (RecyclerView) findViewById(R.id.order_layout);
mOrderList.setHasFixedSize(true);
mOrderList.setLayoutManager(new LinearLayoutManager(this));
mDatabase = FirebaseDatabase.getInstance().getReference().child("OrderCart");
FirebaseRecyclerAdapter<Order, OrderViewHolder> FBRA = new FirebaseRecyclerAdapter<Order, OrderViewHolder>(
Order.class,
R.layout.single_order,
OrderViewHolder.class,
mDatabase
) {
#Override
protected void populateViewHolder(OrderViewHolder viewHolder, Order model, int position) {
viewHolder.setmID(model.getmID());
viewHolder.setmName(model.getmName());
viewHolder.setmPrice(model.getmPrice());
}
};
mOrderList.setAdapter(FBRA);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapScore : dataSnapshot.child("OrderCart").getChildren()) {
total_amount += Integer.parseInt(String.valueOf(snapScore.child("mPrice").getValue()));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
TextView item_price = (TextView) findViewById(R.id.price);
item_price.setText(total_amount);
}
now when I try to display total amount, the app collapse so how can I properly retrieve the data?
Try this way, use iterator to read the data.
Inside onDataChange,
Iterator<DataSnapshot> dataSnapshotsorder = dataSnapshot.child("OrderCart").getChildren().iterator();
while (dataSnapshotsorder .hasNext()) {
DataSnapshot dataSnapshotChild = dataSnapshotsChat.next();
total_amount += Integer.parseInt(String.valueOf(dataSnapshotChild .child("mPrice").getValue()));
}