Import data from Firebase to list - android

I wanna import from Firebase list and sublist. Firebase Database looks something like this:
List_1
sublist_1 name
sublist_2 data
sublist_3 age
sublits 4 Location
List_2
sublist_1 name
sublist_2 data
sublist_3 age
sublits 4 Location
List_3
sublist_1 name
sublist_2 data
sublist_3 age
sublits 4 Location
This is what I have for now in Android Studio:
#Override
protected void onStart() {
super.onStart();
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mCursa);
mListViewCurse.setAdapter(adapter);
Firebase curseRef = mRootRef.child("List_1");
curseRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String message = dataSnapshot.getValue(String.class);
Log.v("E_CHILD_ADDED", message);
mCursa.add(message);
adapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
String message = dataSnapshot.getValue(String.class);
Log.v("E_CHILD_CHANGED", message);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
String message = dataSnapshot.getValue(String.class);
Log.v("E_CHILD_REMOVED", message);
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
This is the output:
name
data
age
location
Could someone please tell me what I need to add so I can see all the lists in my Android app?

Related

How to get child object's value inside a key from a list of data (using childeventlistener in firebase: android studio)

Ok so I've been looking for related articles regarding this, I've made a few experiments but I can't understand why I can't still get the values of note, date_time and vaccine objects... I'm planning on putting them in a ListView and I already got the key from the list of data using ChildEventListener
lastlastref = myRef.child(babyid).child("baby_features").child("immunization_records");
lastlastref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String string = dataSnapshot.getValue(String.class);
}
#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) {
}
});
and then I've tried using EventListener to get the values inside of it
lastlastref = myRef.child(babyid).child("baby_features").child("immunization_records");
lastlastref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String string = dataSnapshot.getValue(String.class);
DatabaseReference newRef = lastlastref.child(string);
newRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
note = snapshot.child("note").getValue(String.class);
vaccine = snapshot.child("vaccine").getValue(String.class);
timestamp = snapshot.child("date_time").getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
arrayList.add(vaccine + "" + timestamp + "" + note);
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) {
}
});
But the app still crashes and logcat says "Can't pass null for argument 'pathString' in child()"
You set up your reference to:
lastlastref = myRef.child(babyid).child("baby_features").child("immunization_records");
So each child node under this location is a JSON object like this:
{
"date_time": "November/16/2018...",
"note": "hhjj...",
"vaccine": "Measles"
}
But in your onChildAdded, you're trying to retrieve a single string value. Since the above JSON object is not a single string value, the getValue(String.class) returns null.
To get the values, you can call getValue() on the individual properties:
lastlastref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String date_time = dataSnapshot.child("date_time").getValue(String.class);
String note = dataSnapshot.child("note").getValue(String.class);
String vaccine = dataSnapshot.child("vaccine").getValue(String.class);
}
You can also create a minimal class to wrap each record, and read that. The simplest version of that is:
public class ImmunizationRecord {
public String date_time;
public String note;
public String vaccine;
}
And the reading would then be done with:
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String record = dataSnapshot.getValue(ImmunizationRecord.class);
}
A small side note about the way you store date_time. This format will lead to problems as you progress, since it is not sortable. If you need to store time stamps, store them as milliseconds since the epoch, or in a string format that allows them to be sorted (e.g. 2018-11-16T11:29:00).

How can I search data from firebase in android

I'm doing my project.
My project is App for finding room in my campus.
In my database there are room name, floor, building room and location.
I want to find all records that have a keyword that the user want to find.
And show data about that room.
My firebase
Refer this link for complete code
http://www.amalhichri.net/android-firebase-realtime-database-basic-cruds/
private void findperson(String name){
Query deleteQuery = myDatabaseReference.orderByChild("fullName").equalTo(name);
deleteQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Iterable snapshotIterator = dataSnapshot.getChildren();
Iterator iterator = snapshotIterator.iterator();
while((iterator.hasNext())){
Log.d("Item found: ",iterator.next().getValue().toString()+"---");
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}`enter code here`
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d("Item not found: ","this item is not in the list");
}
});
}
Change your firebase url to
"YourFireBaseUrl/room/cb1201" to get the data of room no cb1201
you will get the data in JSON format

Minimize Downloads from Firebase

In my NotificationListener of my application I am listening (and syncronizing with my SQLite) to new or changed data from Firebase.
In the first case I would like to check if the status of a loaned book has changed. Therefor I use the following code in onStartCommand:
databaseLoanedBooks.orderByChild("contactId").equalTo(firebase_uid).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
String book_id = dataSnapshot.child("bookId").getValue(String.class);
String book_status = dataSnapshot.child("bookStatus").getValue(String.class);
DatabaseHelper db = new DatabaseHelper(getApplicationContext());
List<String> all_book_ids = db.getAllBookIds();
if (all_book_ids.contains(book_id)){
// some action... check for status, if status=x output of notification
}
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Moreover I would like to check if there is a new message about the loaned book at the server. Therefor I use the following code in onStartCommand of my NotifiactionListener:
final List<String> all_book_ids = db.getAllBookIds();
// iterate through all book-ids the user has loaned at the moment (and saved in SQL)
for (int i = 0; i < all_book_ids .size(); i++) {
final String check_book_id = all_book_ids.get(i);
databaseMessage.child(check_book_id).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
ChatMessage chatMessage = dataSnapshot.getValue(ChatMessage.class);
String message_id = dataSnapshot.child("messageId").getValue(String.class);
String message_book_id = dataSnapshot.child("messageBookId").getValue(String.class);
String message_uid = dataSnapshot.child("messageUid").getValue(String.class);
String message_text = dataSnapshot.child("messageText").getValue(String.class);
String message_time = String.valueOf(chatMessage.getMessageTime());
DatabaseHelper db = new DatabaseHelper(getApplicationContext());
final List<String> all_message_ids = db.getAllMessagesIds();
final List<String> all_book_ids = db.getAllBookIds();
String new_message = getString(R.string.text_new_message);
if (all_book_ids.contains(message_book_id)) {
if (all_message_ids.contains(message_id_changed)) {
// already exists
} else {
ContentValues values_new = new ContentValues();
values_new.put(DatabaseHelper.COLUMN_CHAT_FCM_ID, message_id); values_new.put(DatabaseHelper.COLUMN_CHAT_BOOK_ID, message_book_id);
values_new.put(DatabaseHelper.COLUMN_CHAT_TEXT, message_text_changed); values_new.put(DatabaseHelper.COLUMN_CHAT_BOOK_ID, message_uid);
values_new.put(DatabaseHelper.COLUMN_CHAT_TIME, message_time);
todoUri = getContentResolver().insert(DataContentProvider.CONTENT_URI_CHATS, values_new);
HashMap<String, String> user_session = session.getUserDetails();
// UID from sharedpreferences
String noti_status = user_session.get(SessionManager.KEY_NOTIFICATION);
String user_name_chat_sql = String.valueOf(db.getContactName(message_uid));
String book_name = String.valueOf(db.getBookNameForWA(message_book_id));
user_name_chat_sql = user_name_chat_sql.replaceAll("\\p{P}", "");
book_name = book_name.replaceAll("\\p{P}", "");
showNotificationNewMessage(new_message, user_name_chat_sql, message_text, book_name);
}
}
}
#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) {
}
});
}
With this code I have a data usage of approximately 2 MB per day per user. So my question is: How can I minimize my downloads and following from this my data usage? In the code to check for new messages I tried to use a for-loop to restrict the gathered data only for the books of the respective user, but this is unfortunately not the solution. How can I solve this problem?

How to fetch the username list in listview in Android from Firebase database?

I have registered and saved users through my app and now I want to fetch the list of usernames as shown below from Firebase database. How do I do it in list view? my database is shown below:
ArrayList<MODELCLASSNAME> Users=new ArrayList<>();
DatabaseReference df=FirebaseDatabase.getInstance().getReference().child("users");
df.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapShot user : dataSnapshot.getchildren()){
Users.add(dataSnapshot.getValue(MODELCLASSNAME.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//Now loop through your arraylist
get your database reference
firebaseDatabase = FirebaseDatabase.getInstance();
mPostDb = firebaseDatabase.getReference("User");
Now query your table
Query query = mPostDb.orderByKey();
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapShot user : dataSnapshot){
// Do what ever you whatever you want with this user object
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Try this method:
public void retrieveNames() {
Query myQuery = mDatabase.orderByChild("name").equalTo("INSERT-HERE-A-NAME-FOR-YOUR-SEARCH");
myQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Iterator iterator = dataSnapshot.getChildren().iterator();
//FOR YOUR DATA STRUCTURE -
while (iterator.hasNext()) {
String image_uri = (String) ((DataSnapshot) iterator.next()).getValue();
String name = (String) ((DataSnapshot) iterator.next()).getValue();
String username = (String) ((DataSnapshot) iterator.next()).getValue();
YourUserObject User = new YourUserObject (image_uri, name, username);
YourArrayList.add(User);
}
YourAdapter.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) {
}
});
}

firebase android having trouble retrieving a list of children at a specific location

I am trying to retrieve a list of children at a specific location, but I get only gibberish when I do what I think is right.
My code for retrieving data:
final String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
mDatabase = FirebaseDatabase.getInstance().getReference();
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());
adapter.add(dataSnapshot.child(userId).getChildren().toString());
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Log.d(TAG, "onChildChanged:" + dataSnapshot.getKey());
adapter.add(dataSnapshot.child(userId).getChildren().toString());
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.d(TAG, "onChildRemoved:" + dataSnapshot.getKey());
adapter.add(dataSnapshot.child(userId).getChildren().toString());
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "postComments:onCancelled", databaseError.toException());
Toast.makeText(getActivity(), "Failed to load entries.",
Toast.LENGTH_SHORT).show();
}
};
mDatabase.addChildEventListener(childEventListener);
Screenshot of datastructure
What I am trying to retrieve a list of the children below the userId.
What am I doing wrong?
I don't think you should add the ChildEventListener to the root node of your firebase database since this would download all the data in your database.
Instead, call it on the specific user since you only want it for that UID.
final String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
mDatabase = FirebaseDatabase.getInstance().getReference(userId);
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());
// maybe use a POJO here to collect data easily
// the toString() method is maybe for testing??
adapter.add(dataSnapshot.getValue().toString());
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
// This part should have appropriate code
// Unless of course you actually want to add it
//to the adapter everytime
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
// This part should have appropriate code
// Unless of course you actually want to add it
//to the adapter everytime
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "postComments:onCancelled", databaseError.toException());
Toast.makeText(getActivity(), "Failed to load entries.",
Toast.LENGTH_SHORT).show();
}
};
mDatabase.addChildEventListener(childEventListener);

Categories

Resources