This is my database and I wanna retrieve a data (which is underline in red color) from firebase to Listview .
This is the picture of my XML code
This is the my java code:
public class TimeTableActivity extends AppCompatActivity {
ListView table01;
DatabaseReference Trainline;
ArrayList<String> arrayList= new ArrayList<>();
ArrayAdapter<String> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_time_table);
Trainline= FirebaseDatabase.getInstance().getReference("Time_table");
table01 = findViewById(R.id.table01);
arrayAdapter = new ArrayAdapter<String>( TimeTableActivity.this, android.R.layout.simple_list_item_1);
table01.setAdapter(arrayAdapter);
Trainline.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
}
#Override
public void onChildChanged(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot snapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
In the onChildAdded you can:
Read the value from the snapshot
Add it to the list that the adapter is based on
Tell the adapter to refresh itself
In code:
arrayAdapter = new ArrayAdapter<String>(TimeTableActivity.this,
android.R.layout.simple_list_item_1, arrayList);
// 👆 Add this
Trainline.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
String value = snapshot.child("time_table").getValue(String.class); // 👈 1. Get the value
arrayList.add(value); // 👈 2. Add to the array
arrayAdapter.notifyDataSetChange(); // 👈 3. Tell the adapter to repaint.
}
...
When you read data in the firebase database, you should retrieve the entire data. So, there is no way to fetch only specific fields from the data returned on reading a path.
Because of that, if it's possible for your case, I would suggest you to add new data in firebase with the purpose of queries that only retrieve the information that you need.
For doing that, you can have a separate node that can be called something like TimeTable-SpecificList. Now, in this table, have user uid as your child keys, and each entry shall have only a timeTableSpecific field which you want to fetch.
Example:
replicaTimeTable :{
key1: {
timeTableSpecific: "Colombo-Gampaha ..."
},
key2: {
timeTableSpecific: "Colombo-Kandy ..."
},
key3: {...},
}
This solution to minimize download redundancy and optimize for speed then is the way to go!
Reference: Fetch particular fields from Firebase database
Related
My Firebase Database is being accessed twice, once for Feed_modell and another for Book and showing duplicate data, how can I fetch Firebase data from different models (Book and Feed_modell) one time in a List.
I tried to fetch data from the Feed_modell model and then the Book template, but my Firebase fetch the 4 data into the Feed_modell and then again the same four data into the Book.
private RecyclerViewFeedAdapter Adapter;
private List<Object> feedList;
private void loadtheFeed() {
feedList.clear();
dbs = FirebaseDatabase.getInstance().getReference("feedPosts");
Query query = dbs.child(feedReceivingKey);
childEventListener1 = query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Feed_modell post = dataSnapshot.getValue(Feed_modell.class);
Book book = dataSnapshot.getValue(Book.class);
feedList.add(post);
feedList.add(book);
Adapter.notifyDataSetChanged();
}
#Override
public void onChildChanged( DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved( DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved( DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled( DatabaseError databaseError) {
}
});
}
Read my Firebase once for both models.
I have an android project where I retrieve data from firebase. everything is working fine but when I delete object in firebase console, it does not reflect back in the app.
Here is the link of the image:
So, suppose I delete david hafiz child node in firebase, it does not delete in the app. I have tried a lot but can't find the correct way. I am new to android programming and I hope somebody can help me. Thank You.
Update
mDatabase = FirebaseDatabase.getInstance();
mReference = mDatabase.getReference().child("Students").child("Marks");
mReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.d("value", "" + dataSnapshot);
fetchData(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return view;
}
private void fetchData(DataSnapshot dataSnapshot) {
StudentData value = dataSnapshot.getValue(StudentData.class);
Log.v("StudentData Fragment", "" + dataSnapshot.getValue());
// Get an iterator.
Iterator<StudentData> ite = mMarksList.iterator();
while (ite.hasNext()) {
StudentData iteValue = ite.next();
if (iteValue.equals(value))
ite.remove();
}
mMarksList.add(value);
Collections.sort(mMarksList, new MarksComparator());
String title = mReference.getKey();
// specify an adapter
mAdapter = new MyAdapter(getContext(), mMarksList, title);
mAdapter.notifyDataSetChanged();
mRecyclerView.setAdapter(mAdapter);
}
There are four relevant methods in ``:
onChildAdded
onChildRemoved
onChildChanged
onChildMoved
You only implemented onChildAdded, which is called in two cases:
When you first attach the listener, onChildAdded is called for each existing child.
When a child is later added, onChildAdded is called for that child.
When you delete a node from the Firebase console, the onChildRemoved method is called. But since you left that method empty, your app doesn't do anything when you remove data from the console.
To make your app behave correctly, you'll need to implement onChildRemoved. Typically this involves finding the UI element matching the snapshot and removing it.
You can store keys in order to update or remove it e.g:
ArrayList<String> mKeys = new ArrayList<String>();
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String key = dataSnapshot.getKey();
mKeys.add(key);
adapter.notifyDataSetChanged();
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
String key = dataSnapshot.getKey();
int index = mKeys.indexOf(key);
mMarksList.remove(/*index*/); // or data
adapter.notifyDataSetChanged();
}
You might be interested how to update too.
I am building my first project in android using Firebase.
I have build a Firebase's database which is having main node as post, media as its child node, media node can contain multiple values for a particular post or can have one value inside it.
So i want to fetch media child node values with particular post node.
Could you please help me out.
Any help will deeply appreciated.
Please check the screenshots below.
Firebase ref = new Firebase(YOUR_FIREBASE_URL);
String postNode ="KddShng........";
ref.child("posts/"+postNode).child("media").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.e("!_##_Key : >",dataSnapshot.getKey()); // you will get key of Media node
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
First you need to read docs to know how to retrieve data from firebase.
and your data will be like this ...
final Firebase ref = new Firebase("URL/posts");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
//u can handle your variables name in GetData class
GetData posts = userSnapshot.getValue(GetData.class);
In another way..
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("posts");
String user_id = firebaseAuth.getCurrentUser().getUid();
databaseReference.child(user_id).child("media").getValue("user_id").getValue(etc);
You might save last line as String to reuse it anywhere.
UPDATE:
And to Fitch data You have to use Firebase adapter, example
Try something like this
FirebaseDatabase.getInstance().getReference("posts").child(UID).child("media");
Where UID is the key of the particular post node.
PS: this returns something like a promise, for which you need to attach a listener for. (because this is real time)
If just want to fetch the value once, you can do like this.
FirebaseDatabase.getInstance().getReference("posts").child("your_post_item_id").child("media").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot children : dataSnapshot.getChildren()) {
YourMediaModel mediaItem = children.getValue(YourMediaModel.class);
//add you mediaItem to list that you provided
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
Im struggling a little with my code. I have searched and tried many methods. My aim is remove the previous entry that Firebase has provided to my app, the firebase data is coming from an embedded device.I want to replace the value in my android app.
Firebase is working ok, The app will display the new value provided by firebase but will not delete the previous entry.
I still have plenty to do but want to fix the basics before moving on.
So basically the OnChildChanged will display new firebase entries, i just want the previous entry deleted from the Android Application when a new value comes in from Firebase.
I have looked into removeValue and setValue with no avail
public class MainActivity extends AppCompatActivity {
DatabaseReference fDatabase;
ListView listview;
ArrayList<String> list = new ArrayList<>();
ArrayAdapter <String> adapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.listview);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, list);
listview.setAdapter(adapter);
fDatabase = FirebaseDatabase.getInstance().getReference();
fDatabase.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String value = dataSnapshot.getValue(String.class);
list.add(value);
adapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
String value = dataSnapshot.getValue(String.class);
list.remove(value);
adapter.notifyDataSetChanged();
list.add(value);
adapter.notifyDataSetChanged();
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
String value = dataSnapshot.getValue(String.class);
list.remove(value);
adapter.notifyDataSetChanged();
list.add(value);
adapter.notifyDataSetChanged();
}
Looks like when you assign value it's getting the new entry, so when you call list.remove it isn't removing the old entry since it's actually trying to remove any instance of the new entry.
See if there's any way you can map the old entry to the new entry so the list knows what to remove since the content of value is different between old and new.
I'm using Firebase database and I'm retrieving data from it. When my database has data, addChildEventListener working well but when my database hasn't data, addChildEventListener not working. Bellow, this is my code:
mDatabase = FirebaseDatabase.getInstance().getReference().child("music");
public void getListMusicFromFirebase() {
mDatabase.addChildEventListener(this);
}
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
updateMusic(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
updateMusic(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
updateMusic(dataSnapshot);
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
private void updateMusic(DataSnapshot dataSnapshot) {
mListMusic.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String title = snapshot.getValue(Music.class).getTitle();
String artist = snapshot.getValue(Music.class).getArtist();
String year = snapshot.getValue(Music.class).getYear();
String duration = snapshot.getValue(Music.class).getDuration();
String uri = snapshot.getValue(Music.class).getUri();
Music music = new Music(title, artist, year, duration, uri);
mListMusic.add(music);
}
if (mListMusic.size() > 0) {
bindingListMusic();
return;
}
mBinding.tvDataEmpty.setText("No data");
mDialog.dismiss();
}
I check my list. If size of it greater than 0, I will bind it to recyclerview and opposite, I will notify it haven't data, it working well when having data but when I delete all data from Firebase database, my code can't perform updateMusic() method.
Please help.
To initiate your listener you should have the required data in your firebase database. AddChildEvent listener requires a predefined parent where you will attach it on app launch(or whenever you want) . If there is no parent the listener will never be attached or initiated.
This will result in no response when you later add a parent and add childs to it. So, always make sure that the parent to which you adding childEventListener is already present and the value is not null.
Hope this helps.