I'm using GraphView library. My code below gets data from Firebase real-time database and updates the graph with values from database, but it isn't sorted. I need it to be sorted in ascending order in X axis. The data in X axis is Long type, then it's converted to date.
I've tried adding dp[index] to array list and using different sorting methods, but nothing seems to work.
#Override
public void onStart() {
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
FirebaseAuth auth;
auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();
String id = user.getUid();
DataPoint[] dp = new DataPoint[(int) snapshot.child(id).getChildrenCount()];
int index = 0;
for(DataSnapshot myDataSnapshot : snapshot.child(id).getChildren()){
PointValue pointValue = myDataSnapshot.getValue(PointValue.class);
dp[index] = new DataPoint(pointValue.getxValue(), pointValue.getyValue());
index ++;
}
lineGraphSeries.resetData(dp);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
super.onStart();
}
AlertDialog, where data is being written to the database:
builder.setPositiveButton("ADD",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(TextUtils.isEmpty(weightEditText.getText().toString()) || TextUtils
.isEmpty(dateEditText.getText().toString())) {
Toast.makeText(getActivity(),"Please provide weight and date",
Toast.LENGTH_SHORT).show();
} else{
linearLayout.addView(createNewTextView(weightEditText.getText().toString(),
dateEditText.getText().toString()));
String id = user.getUid();
String randomId = reference.push().getKey();
try {
Date date = sdf.parse(dateEditText.getText().toString());
long x = date.getTime();
int y = Integer.parseInt(weightEditText.getText().toString());
PointValue pointValue = new PointValue(x,y);
reference.child(id).child(randomId).setValue(pointValue);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
});
builder.setView(view);
builder.show();
PointValue class:
public class PointValue {
long xValue;
int yValue;
public PointValue() {
}
public PointValue(long xValue, int yValue) {
this.xValue = xValue;
this.yValue = yValue;
}
public long getxValue() {
return xValue;
}
public int getyValue() {
return yValue;
}
}
#EDIT
Thanks to #Frank van Puffelen, I've managed to sort my data from Firebase Database using orderByChild()
https://firebase.google.com/docs/database/android/lists-of-data#sort_data
below working solution:
#Override
public void onStart() {
FirebaseAuth auth;
auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();
String id = user.getUid();
Query dateAscendingOrder = database.getReference("users")
.child(id).orderByChild("xValue");
dateAscendingOrder.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
DataPoint[] dp = new DataPoint[(int) snapshot.getChildrenCount()];
int index = 0;
for (DataSnapshot myDataSnapshot : snapshot.getChildren()){
PointValue pointValue = myDataSnapshot.getValue(PointValue.class);
dp[index] = new DataPoint(pointValue.getxValue(), pointValue.getyValue());
index++;
}
lineGraphSeries.resetData(dp);
}
Related
There is a point system in my application. I want to create an ordered list of points in a part. It will be in order from highest score to lowest score. In the code I wrote, this system does not work correctly. not ranked from highest to lowest score. Newly rated users appear at the top. How can I fix this problem? I want it sorted from highest score to lowest score.
Scoreboard class:
DatabaseReference UsersRef, RatingsRef;
int currentpage = 1 ;
static final int total_ITEMS = 10 ;
RecyclerView scorrecy ;
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
RatingsRef = FirebaseDatabase.getInstance().getReference().child("Ratings");
RatingsRef.keepSynced(false);
getScor();
public void getScor(){
FirebaseRecyclerOptions<ScorModel> options =
new FirebaseRecyclerOptions.Builder<ScorModel>()
.setQuery(RatingsRef.orderByChild("puan").limitToLast(currentpage * total_ITEMS),ScorModel.class)
.build();
FirebaseRecyclerAdapter<ScorModel,ScorViewHolder> adapter
=new FirebaseRecyclerAdapter<ScorModel, ScorViewHolder>(options)
{
#Override
protected void onBindViewHolder(#NonNull final ScorBoard.ScorViewHolder holder, int position, #NonNull ScorModel model) {
final String visit_user_id = getRef(position).getKey();
UsersRef.child(visit_user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("isim")){
final String myUsername = dataSnapshot.child("isim").getValue().toString();
holder.userName.setText(myUsername);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
RatingsRef.child(visit_user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("puan")){
final String myPoint = dataSnapshot.child("puan").getValue().toString();
holder.userPoint.setText(myPoint+" "+"Puan");
}else {
holder.userPoint.setText("0 Puan");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#NonNull
#Override
public ScorBoard.ScorViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.scorboard_model_layout,viewGroup,false);
ScorBoard.ScorViewHolder viewHolder = new ScorBoard.ScorViewHolder(view);
return viewHolder;
}
};
adapter.startListening();
scorrecy.setAdapter(adapter);
}
public static class ScorViewHolder extends RecyclerView.ViewHolder{
TextView userName , userPoint;
View mView;
public ScorViewHolder(#NonNull View itemView) {
super(itemView);
mView= itemView;
userName =itemView.findViewById(R.id.rank_username);
userPoint =itemView.findViewById(R.id.point);
}
}
ScorModel;
public String scor, username , currentUserID ;
public ScorModel(){
}
public ScorModel(String scor,String username , String currentUserID) {
this.scor= scor;
this.username = username;
this.currentUserID = currentUserID;
}
public String getScor() {
return scor;
}
public void setScor(String scor) {
this.scor = scor;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
Myy DB Ratings ;
enter image description here
Update :
RatingsRef = FirebaseDatabase.getInstance().getReference().child("Ratings");
RatingsRef.child(currentUserID).child("Ratings").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
double sum = 0.0;
try {
for (DataSnapshot ds: dataSnapshot.getChildren()) {
Map<String,Object> map = (Map<String, Object>) ds.getValue();
Object rating = map.get("rating");
Double pvalue = Double.parseDouble(String.valueOf(rating));
sum += pvalue;
Map userpoint = new HashMap();
userpoint .put("puan", String.valueOf(sum));
RatingsRef.child(currentUserID).updateChildren(userpoint );
}
}catch (Exception e){
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
You cannot get the desired results, because your puan field holds a value of type string and not a number. One thing to remember is that when you order strings the results are ordered lexicographically. For example, 10 is placed before 2. See an example below:
1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 3
So the best option that you have is to change the type of the field to be number and not string.
I have firebase database in my android project which contains three values: code, email, date. I am using switchcompat for counting present students in the firebase database. When switch will be checked, data will enter into the firebase database checking if the email is uniqe in the specific date. When switch will be unchecked, that current date's data will be removed. But my problem is that for the first time when I check the switch, it works fine. And in the second time after unchecking the switch once, when I check it once again, it enters data into firebase but also remove it automatically immediately even switch is still checked. I don't understand where is the problem in my code.
I am providing my code in the below for working of SwitchCompat.
Here is the code:
switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
final String date = df.format(c);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
final String previousDate = df.format(cal.getTime());
final int[] i = {0};
if (switch1.isChecked()) {
Query equery = present.orderByChild("email").equalTo(email);
equery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
String code = "1";
PresentStu presentStu = new PresentStu(FirebaseAuth.getInstance().getCurrentUser().getEmail(), date, code);
String uploadId = present.push().getKey();
present.child(uploadId).setValue(presentStu);
} else {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String eemail = snapshot.child("email").getValue().toString();
String ddate = snapshot.child("date").getValue().toString();
if (eemail.equals(eemail) && ddate.equals(date)) {
i[0]++;
break;
}
}
// Toast.makeText(User.this,""+i[0]+"",Toast.LENGTH_SHORT).show();
if (i[0] < 1){
String code = "1";
PresentStu presentStu = new PresentStu(FirebaseAuth.getInstance().getCurrentUser().getEmail(), date, code);
String uploadId = present.push().getKey();
present.child(uploadId).setValue(presentStu);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
} else {
Query equery = present.orderByChild("email").equalTo(email);
equery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String eemail = snapshot.child("email").getValue().toString();
String ddate = snapshot.child("date").getValue().toString();
if (eemail.equals(eemail) && ddate.equals(previousDate)) {
present.child(dataSnapshot.getChildren().iterator().next().getKey()).child("code").setValue("0");
}
if (eemail.equals(eemail) && ddate.equals(date)) {
snapshot.getRef().removeValue();
break;
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
});
Please, help me to find out the lacking in my code.
My database structure
Because I do not know the structure of you database, you can't simply copy/paste this snippet; it is your own code with the event listeners removed.
Get the right path to your snapshot with the right and make the change directly, without waiting for a data change.
switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
final String date = df.format(c);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
final String previousDate = df.format(cal.getTime());
final int[] i = {0};
if (switch1.isChecked()) {
Query equery = present.orderByChild("email").equalTo(email);
// TODO Change this:
DataSnapshot dataSnapshot = equery.doSomethingToGettheSnapshot()
if (!dataSnapshot.exists()) {
String code = "1";
PresentStu presentStu = new PresentStu(FirebaseAuth.getInstance().getCurrentUser().getEmail(), date, code);
String uploadId = present.push().getKey();
present.child(uploadId).setValue(presentStu);
} else {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String eemail = snapshot.child("email").getValue().toString();
String ddate = snapshot.child("date").getValue().toString();
if (eemail.equals(eemail) && ddate.equals(date)) {
i[0]++;
break;
}
}
// Toast.makeText(User.this,""+i[0]+"",Toast.LENGTH_SHORT).show();
if (i[0] < 1){
String code = "1";
PresentStu presentStu = new PresentStu(FirebaseAuth.getInstance().getCurrentUser().getEmail(), date, code);
String uploadId = present.push().getKey();
present.child(uploadId).setValue(presentStu);
}
}
}
} else {
Query equery = present.orderByChild("email").equalTo(email);
// TODO Change this:
DataSnapshot dataSnapshot = equery.doSomethingToGettheSnapshot()
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String eemail = snapshot.child("email").getValue().toString();
String ddate = snapshot.child("date").getValue().toString();
if (eemail.equals(eemail) && ddate.equals(previousDate)) {
present.child(dataSnapshot.getChildren().iterator().next().getKey()).child("code").setValue("0");
}
if (eemail.equals(eemail) && ddate.equals(date)) {
snapshot.getRef().removeValue();
break;
}
}
}
}
}
});
I've try for hours to read the 0 and 1 in products branch. Please someone well-experienced in firebase database help me :(
private void showData(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
Food uInfo = new Food();
uInfo.setName(ds.child("products").getValue(Food.class).getName());
uInfo.setIngredients(ds.child("products").getValue(Food.class).getIngredients());
//display all the information
Log.d(TAG, "showData: name: " + uInfo.getName());
Log.d(TAG, "showData: ingredients: " + uInfo.getIngredients());
ArrayList<String> array = new ArrayList<>();
array.add(uInfo.getName());
array.add(uInfo.getIngredients());
[ArrayAdapter adapter = new][1] ArrayAdapter(this,android.R.layout.simple_list_item_1,array);
mListView.setAdapter(adapter);
}
}
You're doing it wrong.
First, make sure your model class Food contains all the fields you wanna parse.
public class Food
{
private String NDB_number;
private String long_name;
private String ingredients_english;
public String getNDB_number() {
return NDB_number;
}
public void setNDB_number(String NDB_number) {
this.NDB_number = NDB_number;
}
public String getLong_name() {
return long_name;
}
public void setLong_name(String long_name) {
this.long_name = long_name;
}
public String getIngredients_english() {
return ingredients_english;
}
public void setIngredients_english(String ingredients_english) {
this.ingredients_english = ingredients_english;
}
public Food(String NDB_number, String long_name, String ingredients_english)
{
this.long_name = long_name;
this.NDB_number = NDB_number;
this.ingredients_english = ingredients_english;
}
}
then you can parse the products as follows
// Get a reference to our Products
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("foodnutrientstest").child("Products");
// Attach a listener to read the products
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
Food food = ds.getValue(Food.class);
//display all the information
Log.d(TAG, "showData: name: " + food.getLong_name());
Log.d(TAG, "showData: ingredients: " + food.getIngredients_english());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
Cheers :)
To get that data, simply uste the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference productsRef = rootRef.child("Products");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String NDB_number = ds.child("NDB_number").getValue(String.class);
String ingredients_english = ds.child("ingredients_english").getValue(String.class);
String long_name = ds.child("long_name").getValue(String.class);
Log.d(TAG, NDB_number + " / " + ingredients_english + " / " + long_name);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
productsRef.addListenerForSingleValueEvent(valueEventListener);
I have used the String class to get your data because your fields are not correctly named and the object from the database will to be able to be mapped into a Food object. Having that data, you can now create a new object of your Food class and use in the way I need.
A more appropriate names for your fields would be:
private String ndbNumber;
private String ingredientsEnglish;
private String longName;
Kotlin solution:
class products {
lateinit var productsDataModel: Products_data_model
lateinit var productList:ArrayList<Products_data_model>
val firebasereference=FirebaseDatabase.getInstance().reference.child("foodnutrientstest").child("products")
.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
}
override fun onDataChange(p0: DataSnapshot) {
for(data in p0.children)
{
val ndb=p0.child("NDB_Number").getValue().toString()
val ingredient=p0.child("ingreidents_english").getValue().toString()
val long_name=p0.child("long_name").getValue().toString()
productsDataModel=Products_data_model(ndb,ingredient,long_name)
productList.add(productsDataModel)
}
display(productList)
}
})
private fun display(productList: java.util.ArrayList<Products_data_model>) //here you can get all data
{
for(i in 0 until productList.size)
{
Log.d("ndb_name",productList[i].name)
Log.d("ingredient name",productList[i].ingredient)
Log.d("long name",productList[i].long_name)
}
}
}
product_data_model.kt
class Products_data_model {
var name:String
var ingredient:String
var long_name:String
constructor(name:String,ingredient:String,long_name:String)
{
this.name=name
this.ingredient=ingredient
this.long_name=long_name
}
}
Below image shows my Firebase database structure:
All data retrieved successfully. Here is my model class.
public class Post
{
public String lastname;
public String postid;
public long timestamp;
public HashMap<String,Boolean> count;
public Post()
{
}
public Post(String lastname, long timestamp, String postid,HashMap count)
{
this.lastname=lastname;
this.timestamp=timestamp;
this.postid=postid;
this.count=count;
}
public HashMap<String, Boolean> getCounts() {
return count;
}
public void setCounts(HashMap<String, Boolean> count) {
this.count = count;
}
In Main Activity i used to get data
mAdapter = new PostAdapter(MainActivity.this);
getAllPost(null);
postList.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (!recyclerView.canScrollVertically(1))
{
loaded=loaded+10;
if (totalPost== mAdapter.getItemCount())
{
Toast.makeText(MainActivity.this, "no more post", Toast.LENGTH_SHORT).show();
}
else
{
getAllPost(mAdapter.getLastItemId());
}
}
}
});
postList.setAdapter(mAdapter);
private void getAllPost(final String nodeId)
{
final Query query;
final int left= (int) (totalPost-mAdapter.getItemCount());
Toast.makeText(this, String .valueOf(left), Toast.LENGTH_SHORT).show();
if (nodeId == null)
{
query = PostRef
.orderByChild("timestamp")
.limitToLast(mPostsPerPage);
}
else
{
if (left<10)
{
query = PostRef
.orderByChild("timestamp")
.limitToFirst(left);
}
else
{
Long time=Long.parseLong(nodeId);
query = PostRef
.orderByChild("timestamp").endAt(time)
.limitToLast(10);
}
}
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<Post> userModels = new ArrayList<>();
for (DataSnapshot userSnapshot : dataSnapshot.getChildren())
{
userModels.add(userSnapshot.getValue(Post.class));
}
if (!(nodeId ==null))
{
if (left>10)
{
userModels.remove(9);
}
}
Collections.reverse(userModels);
mAdapter.addAll(userModels);
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
And in adapter:
public class PostAdapter extends RecyclerView.Adapter<PostHolder>
{
List<Post> mPost;
Context mContext;
public PostAdapter(Context c) {
this.mPost = new ArrayList<>();
mContext=c;
}
#NonNull
#Override
public PostHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
return new PostHolder(LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.all_post_layout, viewGroup, false));
}
#Override
public void onBindViewHolder(#NonNull final PostHolder postHolder, final int i) {
final String PostKey=mPost.get(i).getPostid();
FirebaseAuth mAuth=FirebaseAuth.getInstance();
final String currentUserID=mAuth.getCurrentUser().getUid();
final DatabaseReference post=FirebaseDatabase.getInstance().getReference().child("Posts");
showCounts(postHolder,i);
setCountsButton(postHolder,i,currentUserID);
tapOnCounts(postHolder,i,currentUserID,post,PostKey);
}
private void tapOncounts(final PostHolder postHolder, final int i, final String currentUserID, final DatabaseReference post, final String postKey)
{
postHolder.countsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if (mPost.get(i).getCounts() !=null)
{
if(mPost.get(i).getCounts().containsKey(currentUserID))
{
post.child(postKey).child("counts").child(currentUserID).removeValue();
postHolder.countsButton.setImageResource(R.drawable.discounts);
}
else
{
postHolder.countsButton.setImageResource(R.drawable.counts);
post.child(postKey).child("counts").child(currentUserID).setValue(true);
}
}
else
{
postHolder.countsButton.setImageResource(R.drawable.counts);
post.child(postKey).child("counts").child(currentUserID).setValue(true);
}
}
});
}
private void setcountsButton(final PostHolder postHolder, int i, String currentUserID)
{
if (mPost.get(i).getCounts() !=null)
{
if(mPost.get(i).getCounts().containsKey(currentUserID))
{
postHolder.countsButton.setImageResource(R.drawable.counts);
}
else
{
postHolder.countsButton.setImageResource(R.drawable.discounts);
}
}
}
private void showCounts(PostHolder postHolder, int i)
{
if((mPost.get(i).getCounts() !=null))
{
postHolder.noOfcounts.setText(String.valueOf(mPost.get(i).getCounts().size()));
}
else
{
postHolder.noOfcounts.setText("0");
}
}
#Override
public int getItemCount() {
return mPost.size();
}
public void addAll(List<Post> newPost) {
int initialSize = mPost.size();
mPost.addAll(newPost);
notifyItemRangeInserted(initialSize, newPost.size());
}
public String getLastItemId() {
return String.valueOf(mPost.get(mPost.size() - 1).getTimestamp());
}
}
All is successfully but whenever total no. of child change(new child added OR old child removed) in count node recylerview is not update. It will only update when i tried to go another activity and come to rerun in MainActivity.
To get realtime updates, you should use Query's addValueEventListener(ValueEventListener listener) method:
Add a listener for changes in the data at this location.
When using addListenerForSingleValueEvent(ValueEventListener listener):
Add a listener for a single change in the data at this location.
Edit:
To get the size of your list, please change the following line of code:
holder.count.setText(String.valueOf(mPost.get(i).getCount().size));
to
holder.count.setText(String.valueOf(getItemCount());
Whenever total number of child changes then your list of Post modal also changes i.e. userModels in your case. Hence whenever your list of model changes your adapter needs to be notified. Hence my guess is to add notifyDataSetChanged to adapter.
Try this:
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<Post> userModels = new ArrayList<>();
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
userModels.add(userSnapshot.getValue(Post.class));
}
mAdapter.notifyDataSetChanged(); //<<changes made HERE
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
})
For this to work I hope userModels is instance variable to your MainActivity and is set to mAdapter during initialization.
I am using Firebase with my Android application. I am trying to use Firebase as a NOSQL database and this is my data retrieval object.
public class FirebaseManager {
private static final String DB_REF = "mainframeradio";
private static final String STREAM_REF = "streams";
public static List<MediaStream> getMediaStreams(Context context) {
final List<MediaStream> mediaStreams = new ArrayList<>();
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference dbRef = db.getReference(STREAM_REF);
dbRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, Object> streams = (Map<String, Object>) dataSnapshot.getValue();
if (!streams.isEmpty()) {
for (Object stream : streams.values()) {
String protocol = (String) ((Map) stream).get("protocol");
String host = (String) ((Map) stream).get("host");
int port = (int) ((Map) stream).get("port");
String media = (String) ((Map) stream).get("media");
String metadata = (String) ((Map) stream).get("metadata");
String streamName = (String) ((Map) stream).get("streamName");
MediaStream mediaStream = new MediaStream(protocol, host, port, media, metadata, streamName);
mediaStreams.add(mediaStream);
}
} else {
L.d("No media streams found on the server.");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
L.w("Couldn't read the stream info from Firebase.");
}
});
return mediaStreams;
}
}
The thing is the event does not get triggered from the activity I am calling it from.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
// Set components.
this.playerView = findViewById(R.id.playerView);
this.songTitleTextView = findViewById(R.id.songTitleTextView);
this.albumArt = findViewById(R.id.albumArt);
// Hide both the navigation and status bar (immersive).
ViewManager.setFullscreenImmersive(getWindow());
List<MediaStream> mediaStreams = FirebaseManager.getMediaStreams(this);
System.out.print(mediaStreams);
}
All I want to do is retrieve the data from firebase. This is the database.
Any help would be appreciated.
Try this to retrieve the data:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("streams");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String hosts=datas.child("host").getValue().toString();
String medias=datas.child("media").getValue().toString();
String metadata=datas.child("metadata").getValue().toString();
String ports=datas.child("port").getValue().toString();
String protocol=datas.child("protocol").getValue().toString();
String steamname=datas.child("streamName").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
the datasnapshot is streams,you then will be able to iterate inside the child 0 and get the data