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
}
}
Related
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);
}
I had error that said
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.g.Model.Cart
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(com.google.firebase:firebase-database##16.0.5:423)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database##16.0.5:214)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(com.google.firebase:firebase-database##16.0.5:79)
at com.google.firebase.database.DataSnapshot.getValue(com.google.firebase:firebase-database##16.0.5:212)
at com.example.gerobokgo.Customer.ViewCart$2.onDataChange(ViewCart.java:107)>
This error happen on my ViewCart page
if (currentUser != null) {
userID = currentUser.getUid();
cust_id = firebaseAuth.getUid();
databaseReference = FirebaseDatabase.getInstance().getReference("Cart").child("Customer List").child(cust_id);
recyclerView = findViewById(R.id.rv);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
CartList = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
for (DataSnapshot cart : ds.getChildren()) {
CartList.add(cart.getValue(Cart.class));
}
}
CartAdapter cartAdapter = new CartAdapter(CartList);
recyclerView.setAdapter(cartAdapter);
// total.setText( String.valueOf(totalPrice));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
public class Cart {
public String cart_id;
public String pro_id;
public String cust_id;
public String brand_id;
public String pro_name;
public String pro_price;
public String pro_image;
public String pro_category;
public String quantity;
public String size;
public String date;
public Cart () {
}
public Cart(String cart_id, String pro_id, String cust_id, String brand_id, String pro_name, String pro_price, String pro_image, String pro_category, String quantity, String size,String date) {
this.cart_id = cart_id;
this.pro_id = pro_id;
this.cust_id = cust_id;
this.brand_id = brand_id;
this.pro_name = pro_name;
this.pro_price = pro_price;
this.pro_image = pro_image;
this.pro_category = pro_category;
this.quantity = quantity;
this.size = size;
this.date=date;
}
this is my database
You have two nested loops in your onDataChange:
CartList = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
for (DataSnapshot cart : ds.getChildren()) {
CartList.add(cart.getValue(Cart.class));
}
}
But if I look at the JSON at the location you attach the listener to, I see only the date level. So in that case, you need only one loop:
CartList = new ArrayList<>();
for (DataSnapshot cart : dataSnapshot.getChildren()) {
CartList.add(cart.getValue(Cart.class));
}
The nested loop would only be needed if a user could have multiple carts per day, but your current data model only allows one cart per day.
From your code it looks like you are iterating a layer too deep in your structure. Easy Fix: Replace
for (DataSnapshot ds : dataSnapshot.getChildren()) {
for (DataSnapshot cart : ds.getChildren()) {
CartList.add(cart.getValue(Cart.class));
}
}
with
for (DataSnapshot cart : dataSnapshot.getChildren()) {
CartList.add(cart.getValue(Cart.class));
}
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
Okay so I got it to run showing the User ID but not score. I then began making some changes, forgot what I'd changed and now I'm back to null null again. I feel like I may have deleted something or misspelled something.
dbref.addValueEventListener(new com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ArrayList<String> list = new ArrayList<>();
list.clear();
for(DataSnapshot ds :dataSnapshot.getChildren()) {
Score Result = ds.getValue(Score.class);
String userId = String.valueOf(Result.getUserId());
String score = String.valueOf(Result.getScore());
list.add(userId);
list.add(score);
}
adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, list);
LvRanking.setAdapter(adapter);
}
Here's my model:
public class Score {
private String userId, score;
public Score() {}
public Score(String userId, String score) {
this.userId = userId;
this.score = score;
}
public String getUserId() {
return userId;
}
public String getScore() {
return score;
}
#Override
public String toString() {
return "Score{" +
"userId='" + userId + '\'' +
", score='" + score + '\'' +
'}';
}
}
Database:
Link to my database screenshot
This is a classic issue with asynchronous APIs. In order to make it work, change your model class according to Java Naming Conventions. Your class should look like this:
public class Score {
private String userId, score;
public Score() {}
public Score(String userId, String score) {
this.userId = userId;
this.score = score;
}
public String getUserId() {
return userId;
}
public String getScore() {
return score;
}
#Override
public String toString() {
return "Score{" +
"userId='" + userId + '\'' +
", score='" + score + '\'' +
'}';
}
}
Also note that onDataChange() method has an asynchronous behavior, which means that is called even before you are trying to add those objects of Score class to the list. In other words, your list will always be empty outside that method. A quick fix would be to move the declaration of your list inside onDataChange() and do what you want to do with it or, if you want to dive into the asynchronous world and use my answer from this post.
Assuming the score node is a direct child of your Firebase root, to display the data using the String class, please use the following code:
ListView listView = (ListView) findViewById(R.id.list_view);
List<String> list = new ArrayList<>();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, list);
listView.setAdapter(arrayAdapter);
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference scoreRef = rootRef.child("score");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userId = ds.child("userId").getValue(String.class);
String score = ds.child("score").getValue(String.class);
list.add(userId + " / " + score);
Log.d("TAG", userId + " / " + score);
}
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, task.getException().getMessage());
}
};
scoreRef.addListenerForSingleValueEvent(eventListener);
And this how you can display data using the Score class.
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Score score = ds.getValue(Score.class);
String userId = score.getUserId();
String score = score.getScore();
Log.d("TAG", userId + " / " + score);
list.add(score);
}
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, task.getException().getMessage());
}
};
scoreRef.addListenerForSingleValueEvent(eventListener);
filepath.addOnSuccessListener(upload data first) then get it and use it....
I want to get a string from this:
, but it has a unique key parent. How do I get string from db? I tried:
firebaseAuth = FirebaseAuth.getInstance();
fUID =firebaseAuth.getCurrentUser().getUid();
itemsUrl ="https://nextweaverproject.firebaseio.com/users/" + fUID ;
mDatabase = FirebaseDatabase.getInstance();
final DatabaseReference myRef = mDatabase.getReferenceFromUrl(itemsUrl);
myRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Map<String, Object> td = (HashMap<String,Object>) dataSnapshot.getValue();
List<Object> values = new ArrayList<Object>(td.values());
strFb = new ArrayList<String>();
strFb.add(values.get(0).toString());
// strFb.add(urlLong);
Log.v("test"," " + strFb.get(strFb.size()-1));
}
But It returns all objects in db.
You can use child to get data from the database tree:
myRef.child("Scenes").child("Scene").("******").
(*****).addChildEventListener(new ChildEventListener() {
this way you should chain your fields.
You can use also addValueEventListener, addListenerForSingleValueEvent.
You can read about them here:
https://firebase.google.com/docs/database/android/retrieve-data
Thank you all. I found my solution by this:
myRef.child("Scenes").child("Scene").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot children : dataSnapshot.getChildren()) {
for (DataSnapshot child : children.getChildren()) {
//Log.v("key1"," " + child.getKey());
if(child.getKey().equals("Thumb")){
for (DataSnapshot child2 : child.getChildren()) {
//Log.v("key2"," " + child2.getValue(String.class));
for (DataSnapshot child3 : child2.getChildren()) {
//Log.v("key3"," " + child3.getKey());
if(child3.getKey().equals("LongUrl")){
Log.v("key4"," " + child3.getValue(String.class));
thumbUrl.add(child3.getValue().toString());
}
}
}
}
}
Log.v("keyResult"," " + thumbUrl);
// Log.v("key2"," " + thumbUrl);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Result here :Result