I keep getting a blank screen on my app but no errors and my Firebase contains data. It looks like its not retrieved correctly. I have checked out answers from other similar questions, tried the solutions but i still cannot find the solution to my problem. Kindly help am a bit new to this.
This is my OrderStatus class
public class OrderStatus extends AppCompatActivity {
public RecyclerView recyclerView;
public RecyclerView.LayoutManager layoutManager;
FirebaseDatabase database;
DatabaseReference requests;
FirebaseRecyclerAdapter<DeliveryRequest, OrderViewHolder> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_status);
database = FirebaseDatabase.getInstance();
requests = database.getReference("OrderRequests");
recyclerView = (RecyclerView)findViewById(R.id.listOrders);
//ADAPTER
loadOrders();
}
private void loadOrders() {
FirebaseRecyclerOptions<DeliveryRequest> options =
new FirebaseRecyclerOptions.Builder<DeliveryRequest>()
.setQuery(requests, new SnapshotParser<DeliveryRequest>() {
#NonNull
#Override
public DeliveryRequest parseSnapshot(#NonNull DataSnapshot snapshot) {
return null;
}
})
.build();
adapter = new FirebaseRecyclerAdapter<DeliveryRequest, OrderViewHolder>(options) {
#Override
public OrderViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Create a new instance of the ViewHolder, in this case we are using a custom
// layout called R.layout.message for each item
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.order_layout, parent, false);
return new OrderViewHolder(view);
}
#Override
protected void onBindViewHolder(OrderViewHolder holder, int position, DeliveryRequest model) {
// Bind the Chat object to the ChatHolder
// ...
holder.txtOrderPhone.setText(model.getPhone());
holder.txtOrderAddress.setText(model.getAddress());
holder.txtOrderStatus.setText(convertCodeToStatus(model.getStatus()));
holder.txtOrderId.setText(adapter.getRef(position).getKey());
}
};
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
adapter.startListening();
}
private String convertCodeToStatus(String status){
if (status.equals("0"))
return "placed";
else if (status.equals("1"))
return "on my way";
else
return "Shipped";
}
}
My String class
public class DeliveryRequest {
public String firstName, lastName,address, phone,total, status;
public List<ProposalDetails> proposalDetails;
public DeliveryRequest() {
}
public DeliveryRequest(String firstName,String lastName, String address,String phone,String total,String status, List<ProposalDetails> proposalDetails){
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.phone = phone;
this.proposalDetails = proposalDetails;
this.status = "0";
this.total= total;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public List<ProposalDetails> getProposalDetails() {
return proposalDetails;
}
public void setProposalDetails(List<ProposalDetails> proposalDetails) {
this.proposalDetails = proposalDetails;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
You're implemented parseSnapshot by return null, which means that any DataSnapshot that comes from your database is turned into null.
You're probably looking for something like:
public DeliveryRequest parseSnapshot(#NonNull DataSnapshot snapshot) {
return snapshot.getValue(DeliveryRequest.class);
}
Related
I can get data using value event listener but when i am using FirebaseRecyclerOptions i am not getting any data. When i set debug in my code datasnapshot is 0
Here is my code
#NonNull
protected RecyclerView.Adapter newAdapter() {
FirebaseRecyclerOptions<ChatModel> options =
new FirebaseRecyclerOptions.Builder<ChatModel>() //sChatQuery=database.getReference("comments").child("story"+did).limitToLast(15);;
.setQuery(sChatQuery, ChatModel.class)
.setLifecycleOwner(this)
.build();
return new FirebaseRecyclerAdapter<ChatModel, ChatHolder>(options) {
#Override
public ChatHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ChatHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.chat_list_row, parent, false));
}
#Override
protected void onBindViewHolder(#NonNull ChatHolder holder, int position, #NonNull ChatModel model) {
holder.bind(model);
}
#Override
public void onDataChanged() {
}
};
}
And ChatModel class to get firebase data is
public class ChatModel {
String email;
String message;
String time;
String name;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And firebase database which i am trying to retrieve is given below
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 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
I'm implementing my small app. Today,
I'm having trouble getting data from my Firebase.
Here is my Firebase structure:
This is modal Request:
public class Request {
// private String phone, name, address, total, status;
private String phone, name, address, status;
private int total;
private List<Order> foods;
public Request() {
}
public Request(String phone, String name, String address, int total, List<Order> foods) {
this.phone = phone;
this.name = name;
this.address = address;
this.total = total;
this.foods = foods;
this.status = "0"; //Default 0. 0: place, 1: shipping, 2: shipped
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
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 List<Order> getFoods() {
return foods;
}
public void setFoods(List<Order> foods) {
this.foods = foods;
}
}
I obtained the Order data by going to "PhoneNumber" and getting the
"ID Order" data as follows:
private FirebaseRecyclerAdapter<Request, OrderViewHolder> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_status);
//Firebase:
FirebaseDatabase database = FirebaseDatabase.getInstance();
requests = database.getReference("Requests");
//init:
recyclerView = (RecyclerView) findViewById(R.id.recycler_orderview);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
loadOrders(Common.currentUser.getPhone());
//Common.currentUser.getPhone() This is PhoneNumber current
}
private void loadOrders(final String phone) {
adapter = new FirebaseRecyclerAdapter<Request, OrderViewHolder>(
Request.class,
R.layout.order_item,
OrderViewHolder.class,
requests.child(phone) // I have access to "PhoneNumber"
) {
#Override
protected void populateViewHolder(OrderViewHolder viewHolder, Request model, int position) {
viewHolder.txtOrderId.setText(adapter.getRef(position).getKey());
viewHolder.txtOrderStatus.setText(convertCodeToStatus(model.getStatus()));
viewHolder.txtOrderPhone.setText(model.getPhone());
viewHolder.txtOrderAddress.setText(model.getAddress());
viewHolder.txtOrderTotal.setText(String.valueOf(model.getTotal()));
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
// Get CategoryID and send Activity Foods List:
Intent moveToOrderDetails = new Intent(OrderStatusActivity.this, OrderDetailsActivity.class);
moveToOrderDetails.putExtra("KeyOrder", adapter.getRef(position).getKey());
startActivity(moveToOrderDetails);
}
});
}
};
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
}
And this is my Apdapter:
public class OrderViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnCreateContextMenuListener {
public TextView txtOrderId, txtOrderStatus, txtOrderPhone, txtOrderAddress, txtOrderTotal;
private ItemClickListener itemClickListener;
public OrderViewHolder(View itemView) {
super(itemView);
txtOrderId = (TextView) itemView.findViewById(R.id.order_id);
txtOrderStatus = (TextView) itemView.findViewById(R.id.order_status);
txtOrderPhone = (TextView) itemView.findViewById(R.id.order_phone);
txtOrderAddress = (TextView) itemView.findViewById(R.id.order_address);
txtOrderTotal = (TextView) itemView.findViewById(R.id.order_total);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View view) {
itemClickListener.onClick(view,getAdapterPosition(),false);
}
#Override
public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
contextMenu.setHeaderTitle("Select the action");
contextMenu.add(0, 0, getAdapterPosition(), Common.UPDATE);
contextMenu.add(0, 1, getAdapterPosition(), Common.DELETE);
}
}
And now I'm having trouble figuring out how to get the data of all
orders without having to go to "Number Phone". I tried to think and
perform but failed.
This is image demo about an order:
I want to Sort from top to bottom on Firebase Database. Can anyone help me? I tried to use collections, but it didn't work.
Activity where starts the recycler view
public class activity_ranking extends AppCompatActivity {
RecyclerView rv;
List<User> users;
Adapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ranking);
rv = (RecyclerView)findViewById(R.id.recycler);
rv.setLayoutManager(new LinearLayoutManager(this));
users = new ArrayList<>();
FirebaseDatabase database = FirebaseDatabase.getInstance();
adapter = new Adapter(users);
Collections.sort(users, new Comparator<User>(){
public int compare(User obj1, User obj2)
{
// TODO Auto-generated method stub
return (obj1.getStars() > obj2.getStars()) ? +1: (obj1.getStars() > obj2.getStars()) ? 1:0 ;
}
});
rv.setAdapter(adapter);
Query query = database.getReference().child("users").orderByChild("stars");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
users.removeAll(users);
for (DataSnapshot snapshot:
dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
users.add(user);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
MyClass user
public class User {
public User() {
}
String username;
String name;
int stars;
String id;
public User(String username, String name, int stars, String id) {
this.username = username;
this.name = name;
this.stars = stars;
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStars() {
return stars;
}
public void setStars(int stars) {
this.stars = stars;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
To invert the list, add items to the beginning instead of the end. So instead of:
users.add(user);
do
users.add(0, user);
See: Java Arrays how to add elements at the beginning