Firebase won't trigger data change event - java

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

Related

Android Java firestore databse curd opartion not working

in my case, I can add different documents and different fields to my data collection in my firestore database. that means add curd operation is working well but I want complete my delete and update function to fulfill my application. my problem is I can't edit/delete my "description" and "title". I have initialized the variable as "DocumentReference" I think the problem is having that. anyone feel free to help me to solve this issue. thank you!
i have to make EDIT and DELETE functions. but them not working with every documents
public class MainActivity extends AppCompatActivity {
FirebaseAuth fAuth;
private static final String TAG = "MainActivity";
private static final String KEY_TITLE = "title";
private static final String KEY_AUDIOLIST = "audiolist";
private EditText editTextTitle;
private EditText editTextAudiolist;
private TextView textViewData;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference notebookRef = db.collection("Category");
private DocumentReference noteRef = db.document("Category/mindRelax");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextTitle = findViewById(R.id.edit_text_title);
editTextAudiolist = findViewById(R.id.edit_text_audioList);
textViewData = findViewById(R.id.text_view_data);
}
#Override
protected void onStart() {
super.onStart();
notebookRef.addSnapshotListener(this, new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot queryDocumentSnapshots, FirebaseFirestoreException e) {
if (e != null) {
return;
}
String data = "";
for (QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots) {
Note note = documentSnapshot.toObject(Note.class);
note.setDocumentId(documentSnapshot.getId());
String documentId = note.getDocumentId();
String title = note.getTitle();
String audiolist = note.getAudiolist();
data += "ID: " + documentId
+ "\nTitle: " + title + "\nAudiolist: " + audiolist + "\n\n";
}
textViewData.setText(data);
}
});
}
public void addNote(View v) {
String title = editTextTitle.getText().toString();
String audiolist = editTextAudiolist.getText().toString();
Note note = new Note(title, audiolist);
notebookRef.add(note);
}
public void loadNotes(View v) {
notebookRef.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
String data = "";
for (QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots) {
Note note = documentSnapshot.toObject(Note.class);
note.setDocumentId(documentSnapshot.getId());
String documentId = note.getDocumentId();
String title = note.getTitle();
String audiolist = note.getAudiolist();
data += "ID: " + documentId
+ "\nTitle: " + title + "\nAudiolist: " + audiolist + "\n\n";
}
textViewData.setText(data);
}
});
}
public void updateAudiolist(View v) {
String audiolist = editTextAudiolist.getText().toString();
String title = editTextTitle.getText().toString();
Map<String, Object> note = new HashMap<>();
note.put( KEY_AUDIOLIST, audiolist);
note.put( KEY_TITLE, title);
noteRef.set(note, SetOptions.merge());
noteRef.update(KEY_TITLE,title, KEY_AUDIOLIST, audiolist);
}
public void deleteAudiolist(View v) {
Map<String, Object> note = new HashMap<>();
note.put(KEY_AUDIOLIST, FieldValue.delete());
noteRef.update(note);
noteRef.update(KEY_AUDIOLIST, FieldValue.delete());
}
public void deleteNote(View v) {
noteRef.delete();
}
public void logout (View view){
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getApplicationContext(),Login.class));
finish();
}
}

Update Firebase database data

I am trying to update my databse:
This is my code, but it doesn't seem to update the database. (Write access is set to true in Firebase settings)
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("items").child("1").child("itemAvailability").setValue("Not Available");
Java class
public class Item {
String itemName;
String itemAvailability;
public Item(String itemName, String itemAvailability) {
this.itemName = itemName;
this.itemAvailability = itemAvailability;
}
public Item() {
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemAvailability() {
return itemAvailability;
}
public void setItemAvailability(String itemAvailability) {
this.itemAvailability = itemAvailability;
}
}
You can do something like this with a Map Data structure.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
DatabaseReference itemRef = ref.child("items/1/itemAvailability");
Map<String, Object> itemUpdates = new HashMap<>();
itemUpdates.put("itemAvailability", "Not Available");
itemRef.updateChildrenAsync(itemUpdates);
This will take the item 1's availability and update it's availability to Not Available
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("items").child("1").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
HashMap<String, Object> updateMap = new HashMap<>();
updateMap.put("itemAvailability", "Not Available");
ref.updateChildren(updateMap);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Might work for you.
Here is the code for Firebase real-time database Insert, Update & Delete operation(CRUD).
//****UPDATE
var database = firebase.database();
let userRef = database.ref('myroot/items/');
userRef.child("1").child("itemAvailability").update("Not Available").then().catch();
//****Insert
var database = firebase.database();
let userRef = database.ref('myroot/items/');
userRef.child("1").child("itemAvailability").set("Not Available").then().catch();
//****Delete
let itemId=1;
let userRef = database.ref('myroot/items/' + itemId);
userRef.remove().then().catch();

Firebase : Can't convert object of type java.lang.String to type com.example.g.Model.Cart

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));
}

Read data from firebase realtime database

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
}
}

Firebase - how to enumerate all child values' contents?

I'm developing an Android app in Android Studio which lists events based on categories (music, sport, business, theatre). Every event has a name, description, location and time. This is how the events are stored in Firebase when a user posts events through my application:
How can I retrieve e.g. all childs and its contents in the Music category? I have four String arrays to display events (currently manually) like this:
String[] name = {"Eminem","Rihanna"};
String[] desc = {"Concert","Live Show"};
String[] location = {"Miami","Florida"};
String[] time = {"bllablla","bllablla"};
I want to populate the string arrays automatically from firebase, however I'm not sure how to get contents for every child element from Music element? If needed, I can post the Java code which populates the database as well.
Edit: I've tried this:
DatabaseReference info = FirebaseDatabase.getInstance().getReference("Events").child("Music");
info.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot val: dataSnapshot.getChildren()) {
// Retreive all Music childs and then retreive all data of them childs?
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
There is probably no easier solution than to download all of your music data, loop through all children and create corresponding arrays manually -
1) Create a class to map your firebase music record to -
class MusicRecord{
String date;
String eventDescription;
String eventName;
String location;
}
2) Load data, loop through children, retrieve MusicRecords and populate your arrays
protected void loadData(){
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Events").child("Music");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> recordsSnaphots = dataSnapshot.getChildren();
int count = (int) dataSnapshot.getChildrenCount();
int i = 0;
String[] names = new String[count];
String[] descriptions = new String[count];
String[] locations = new String[count];
String[] times = new String[count];
for(DataSnapshot recordSnapshot: recordsSnaphots){
MusicRecord record = recordSnapshot.getValue(MusicRecord.class);
if(record != null) {
names[i] = record.eventName;
descriptions[i] = record.eventDescription;
locations[i] = record.location;
times[i] = record.date;
i++;
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Based on your post, you'll have to do several things :
Create a model
You'll have to create a POJO that describes the structure of the data you have in your Firebase realtime database. In your case, create a class FirebaseEvent that has a Date and three Strings (eventDescription,eventName,location).
Instantiate your class
Based on your last snippet, instantiate your class with the data from your Firebase realtime database. Firebase API is still a bit tedious with this, but this is yet the most common way to do it
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
GenericTypeIndicator<HashMap<String,FirebaseEvent>> ti =
new GenericTypeIndicator<HashMap<String,FirebaseEvent>>() {};
HashMap<String,FirebaseEvent> retrievedEvents = childSnapshot.getValue(ti);
}
Now, what you have is a HashMap with keys like "Eminem" and "Rihanna" and the corresponding value that is a FirebaseEvent.
I choose to use an ArrayList for a dynamic data structure.
I also took a snapshot of my database:
public class MainActivity extends AppCompatActivity {
List<String> name= new ArrayList<String>();
List<String> location= new ArrayList<String>();
List<String> date= new ArrayList<String>();
private DatabaseReference mDatabase;
public static final String TAG= "YOUR-TAG-NAME";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabase = FirebaseDatabase.getInstance().getReference().child("Events").child("Music");
// Read from the database
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
for (DataSnapshot values: dataSnapshot.getChildren()) {
//query for the parent of the date "Eminem"
String key = values.getKey().toString();
name.add(key);
//query for location in the music category
date.add(values.child("location").getValue().toString());
//query for date in the music category
date.add(values.child("date").getValue().toString());
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
}
}

Categories