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
Related
I am trying to use anychart to plot data stored from firebase database but I cannot retrieve data with ValueDataEntry.
I have already tested the connection to my database using System.out.println() to retrieve data and it's fine.
public class statistics extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_statistics);
AnyChartView anyChartView = findViewById(R.id.any_chart_view);
anyChartView.setProgressBar(findViewById(R.id.progress_bar));
Cartesian cartesian = AnyChart.column();
final List<DataEntry> data = new ArrayList<>();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("sales");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()){
Sales sales = ds.getValue(Sales.class);
data.add(new ValueDataEntry(sales.getName(), sales.getSold()));
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Column column = cartesian.column(data);
column.tooltip()
.titleFormat("{%X}")
.position(Position.CENTER_BOTTOM)
.anchor(Anchor.CENTER_BOTTOM)
.offsetX(0d)
.offsetY(5d)
.format("${%Value}{groupsSeparator: }");
cartesian.animation(true);
cartesian.title("sample title");
cartesian.yScale().minimum(0d);
cartesian.yAxis(0).labels().format("${%Value}{groupsSeparator: }");
cartesian.tooltip().positionMode(TooltipPositionMode.POINT);
cartesian.interactivity().hoverMode(HoverMode.BY_X);
cartesian.xAxis(0).title("Product");
cartesian.yAxis(0).title("Revenue");
anyChartView.setChart(cartesian);
}
here is my class
public class Sales {
public String id;
public String name;
public int sold;
public Sales() {
}
public Sales(String id, String name, int sold) {
this.id = id;
this.name = name;
this.sold = sold;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSold() {
return sold;
}
public void setSold(int sold) {
this.sold = sold;
}
}
I just simply want to populate a bar graph with data from firebase.
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
DataBase Structure
I am trying to get reference to Users from Chatlist. What i am trying to do is if a users is logged in he will see the users mentioned under is Uid in Chatlist node inside his recyclerview.
I am getting a the nullpointerexception in the following line
DatabaseReference UserRef = rootRef.child("Users").child(chatlist.getId());
Exception
java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
at com.google.firebase.database.DatabaseReference.child(com.google.firebase:firebase-database##19.2.1:96)
at com.shivam.chatapp2.Fragments.Chats.onCreateView(Chats.java:112)
MyCode
public class Chats extends Fragment {
private RecyclerView recyclerView;
private UserAdapter userAdapter;
private List<User> mUsers;
FirebaseUser fuser;
DatabaseReference reference;
FloatingActionButton profile, credentials;
ValueEventListener ChatListListener;
List<Chatlist> usersList;
private ChatsFragmentAdapter chatsFragmentAdapter;
public Chats() {
// 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_chats, container, false);
profile = view.findViewById(R.id.fab_edit_profile_pic);
credentials = view.findViewById(R.id.fab_edit_name);
FabAction();
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
fuser = FirebaseAuth.getInstance().getCurrentUser();
usersList = new ArrayList<>();
reference = FirebaseDatabase.getInstance().getReference("Chatlist").child(fuser.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
usersList.clear();
if(dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Chatlist chatlist = snapshot.getValue(Chatlist.class);
usersList.add(chatlist);
}
}
//chatList();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Chatlist chatlist=new Chatlist();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference UserRef = rootRef.child("Users").child(chatlist.getId());
UserRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
mUsers.add(user);
}
userAdapter = new UserAdapter(getContext(), mUsers, true);
recyclerView.setAdapter(userAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return view;
}
Update
Chatlist.java
public class Chatlist {
public String id;
public String MessageCheck;
public Chatlist() {
}
public Chatlist(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
User.java
public class User {
private String id;
private String First;
private String EmailID;
private String imageURL;
private String status;
public User(String id, String first, String emailID, String imageURL,String status) {
this.id = id;
this.First = first;
this.EmailID = emailID;
this.imageURL = imageURL;
this.status=status;
}
public User() {
}
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 getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
public String getEmailID() {
return EmailID;
}
public void setEmailID(String emailID) {
EmailID = emailID;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
start listening to the users node from your first query of chatlist node:
reference = FirebaseDatabase.getInstance().getReference("Chatlist").child(fuser.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
usersList.clear();
if(dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Chatlist chatlist = snapshot.getValue(Chatlist.class);
usersList.add(chatlist);
//start listening to users node here
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference UserRef = rootRef.child("Users").child(chatlist.getId());
UserRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
.....
....
....
}
....
....
update
Make sure this line is removed:
Chatlist chatlist=new Chatlist();
update 2
don't do this inside your users query:
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
mUsers.add(user);
}
instead do this:
User user = dataSnapshot.getValue(User.class);
mUsers.add(user);
update 3
chatlist class:
public class Chatlist {
public String id;
public Chatlist(String id) {
this.id = id;
}
public Chatlist(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
users class:
public class User {
private String id;
private String First;
private String EmailId;
private String imageURL;
private String status;
public User(String id, String First, String EmailId, String imageURL,String status) {
this.id = id;
this.First = First;
this.EmailId = EmailId;
this.imageURL = imageURL;
this.status=status;
}
public User() {
}
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) {
this.First = first;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
public String getEmailID() {
return EmailId;
}
public void setEmailID(String emailID) {
this.EmailId = emailID;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
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);
}
I have 2 applications(different package names) which use one Firebase database. One app has to write access to the database and another have read access to the database.in my second application, i use recyclerview to retrieve data which is stored by 1st App.
for this I use below code:
FirebaseOptions options = new FirebaseOptions.Builder()
.setApplicationId("1:567....259c8f58311") // Required for Analytics.
.setApiKey("AIzaSyA9BRxl......hE03y5qD-c") // Required for Auth.
.setDatabaseUrl("https://mycity-3a561.firebaseio.com/") // Required for RTDB.
.build();
FirebaseApp.initializeApp(this /* Context */, options, "MyCity");
// Retrieve my other app.
FirebaseApp app = FirebaseApp.getInstance("MyCity");
// Get the database for the other app.
FirebaseDatabase secondaryDatabase = FirebaseDatabase.getInstance(app);
DatabaseReference data = secondaryDatabase.getInstance().getReference();
data.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()) {
for (DataSnapshot dSnapshot : ds.getChildren()) {
WaterClass waterClass = dSnapshot.getValue(WaterClass.class);
Log.d("Show", waterClass.getName() == null ? "" : waterClass.getName());
list.add(waterClass);
}
adapter = new WaterAdapter(ShowWaterDetails.this, list);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
progressDialog.dismiss();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
}
});
}
Adapter class
private class WaterAdapter extends RecyclerView.Adapter<WaterAdapter.ViewHolder> {
ShowWaterDetails showDetail;
List<WaterClass> listData;
public WaterAdapter(ShowWaterDetails showWaterDetails, List<WaterClass> list) {
this.showDetail = showWaterDetails;
this.listData = list;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.show_items, parent, false);
WaterAdapter.ViewHolder viewHolder = new WaterAdapter.ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(WaterAdapter.ViewHolder holder, int position) {
WaterClass AllDetails = listData.get(position);
holder.NameTextView.setText(AllDetails.getName());
holder.DetailTextView.setText(AllDetails.getDetail());
holder.DateTextView.setText(AllDetails.getDate());
holder.LocationTextView.setText(AllDetails.getLocation());
holder.TypeTextView.setText(AllDetails.getType());
Picasso.with(showDetail).load(AllDetails.getImgurl()).resize(120, 60).into(holder.ImageTextView);
}
#Override
public int getItemCount() {
return listData.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView NameTextView;
public TextView DetailTextView;
public TextView DateTextView;
public TextView LocationTextView;
public TextView TypeTextView;
public ImageView ImageTextView;
public ViewHolder(View itemView) {
super(itemView);
NameTextView = itemView.findViewById(R.id.ShowNameTextView);
DetailTextView = itemView.findViewById(R.id.ShowDetailTextView);
DateTextView = itemView.findViewById(R.id.ShowDateTextView);
LocationTextView = itemView.findViewById(R.id.ShowLocationTextView);
TypeTextView = itemView.findViewById(R.id.ShowTypeTextView);
ImageTextView = itemView.findViewById(R.id.ShowImageView);
}
}
}
}
POJO Class
class WaterClass {
private String id;
private String email;
private String name;
private String type;
private String detail;
private String location;
private String date;
private String imgurl;
public WaterClass(){
}
public WaterClass(String id, String currentUserString, String imageUrl, String nameString, String typeString, String detailString, String locationString, String dateString) {
this.id = id;
this.email = currentUserString;
this.name =nameString;
this.type = typeString;
this.detail = detailString;
this.location = locationString;
this.date = dateString;
this.imgurl = imageUrl;
}
public String getImgurl() {
return imgurl;
}
public void setImgurl(String imgurl) {
this.imgurl = imgurl;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
:
there is no error but my recycler not showing anything
go to onStart() and start listening
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
and in your onStop
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
The FirebaseRecyclerAdapter uses a snapshot listener to monitor changes to the Firestore query. To begin listening for data, call the startListening() method. You may want to call this in your onStart() method. Make sure you have finished any authentication necessary to read the data before calling startListening() or your query will fail.
Be sure that the names of constant in the POJO match exatly the names
of your database structure in your firebase console !!
ps: do not post your api-keys or app-ids in your questions, keep them secret, and consider using firebaserecycleradapter if you are using firebase-database , it will be more easy to setup and to show values.
Your POJO is ok !
Found Solution!!
just change this part of a code
FirebaseApp.initializeApp(this /* Context */, options, "MyCity");
// Retrieve my other app.
FirebaseApp app = FirebaseApp.getInstance("MyCity");
TO
FirebaseApp.initializeApp(this);
// Retrieve my other app.
FirebaseApp app = FirebaseApp.getInstance("[DEFAULT]");