How To Pull Firebase Data Into A Variable - android

I'm currently learning Firebase and Android Studios. I'm trying to pull data from my firebase into specific variables.
This is the code in specific I'm confused about, I understand the code I'm just not sure how to make setUserName be stored in moverName.
private void showData(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
moverInfo mInfo = new moverInfo();
mInfo.setUserName(ds.child(userID).getValue(moverInfo.class).getUserName()); //set & get the name
mInfo.setLicense(ds.child(userID).getValue(moverInfo.class).getLicense()); //set & get license number
mInfo.setVehReg(ds.child(userID).getValue(moverInfo.class).getVehReg()); //set & get veh reg
//String moverName = dataSnapshot.getValue(moverInfo.class).setUserName();
}
}
I'm trying to set the userName pulled into moverName which is an empty variable that is attached to my gui.

Try this:
moverInfo mInfo = ds.getValue(moverInfo.class)
if you have the same variable names in Firebase as in your moverInfo POJO class your model will be filled correctly.

Related

Retrieve data from multiple push ids under a single child in firebase realtime database

I am new to android studio and programming and am currently trying to make my first app. In firebase RTDB, I have multiple push ids under a single child that keep on increasing in number as the user presses certain buttons, and they all store only an integer. I want to retrieve the data from all those push ids(or keys, I don't really know what they are actually called) under the child and then sum the integers up and display the result in a textView and do it every time a new field is added. How can I do that? So far I only know how to normally send and receive data to childs sub-childs like this but i have never ever used push ids or keys before:
String recieve = datasnapshot.child("Child").child("subchild").getText().toString();
String send = "send";
databaseReferenc.child("Child").child("sunchile").setValue(send);
The data tree in firebase is as follows:
Assuming that Australia is a direct child of your Firebase Realtime Database root, to sum all those values, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference australiaRef = rootRef.child("Australia");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int total = 0;
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String value = Integer.parseInt(ds.getValue(String.class));
total += value;
}
Log.d("TAG", "total: " + total);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
australiaRef.addListenerForSingleValueEvent(valueEventListener);
One more thing. Because you are storing numbers, it best to store them as long values and not as String values.

Children in firebase are deleted after I close the app, how to let the data stay?

Here's how I put value in firebase:
exDBKey1 = exerciseList.get(position).getExerciseId();
exerciseName = exerciseList.get(position).getExerciseName();
weekExerciseModel = new WeekExerciseModel(exerciseName, exDBKey1);
executedExercises.child(userID).child("WeeklyExercises").child(exerciseWeek)
.child(exerciseDay).push().setValue(weekExerciseModel);
Here's my firebase which gets deleted after I re-open the app:
The dynamic data are from this code
exerciseReference.addListenerForSingleValueEvent (new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
WeekExerciseModel weekExerciseModel = dataSnapshot1.getValue(WeekExerciseModel.class);
if("Very Active".equalsIgnoreCase(weekExerciseModel.getStatus()) &&
"1".equalsIgnoreCase(weekExerciseModel.getExerciseDay()) &&
"2".equalsIgnoreCase(weekExerciseModel.getExerciseWeek()) &&
"Gain".equalsIgnoreCase(weekExerciseModel.getUserGoal())
&& "None".equalsIgnoreCase(weekExerciseModel.getUserDisease())){
exerciseList.add(weekExerciseModel);
Log.e("exercisenameSnapshot", String.valueOf(dataSnapshot1.getKey()));
}
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("FitureUser", Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("exerciseIDW2D1", weekExerciseModel.getExerciseId());
// editor.putInt("exerciseSum",day);
editor.putString("exerciseDay","Day 1");
editor.putString("exerciseWeek","Week 2");
editor.putString("exercisenameSnapshot", String.valueOf(dataSnapshot1.getKey()));
editor.apply();
It looks like this after it gets deleted
Can you try with static values but also try
executedExercises.child(userID).child("WeeklyExercises").child(exerciseWeek).child(exerciseDay).setValue(weekExerciseModel);
And see if this helps.
Also, how are you calling your firebase database path - .getInstance().getReference() line when you open the app?
My next question would be on why you have a key map of exDBKEY1 in your weekExerciseModel but the key name is showing as exerciseID in your database when it probably should show as exDBKEY1 just like how your exerciseName variable shows as exerciseName for the key name. You might need to show more of the code such as where the exerciseID comes form because it looks like a firebaseUID which means it's going to the database to get it which could be clearing out your data from wherever else the code for that UID is.
Instead of using the same Parent node which later I found out that is what's causing the wiped out data. So I made a new Parent node still the same process but it only contains the data that I need.

Why am I getting the value from another key

Here is my data structure. I only want to get the "regular" key from the first key which is the -LZHfDw9kqC-3rBf4VRh
Here is my code:
String rates = null;
DataSnapshot ratesSnapshot = dataSnapshot.child(key).child("promos");
Adapter_RoomsModel roomsModel = new Adapter_RoomsModel();
for (DataSnapshot ds : ratesSnapshot.getChildren()) {
rates = ds.getKey();
roomsModel.setRateName(rates);
}
My output :
-LZHfDw9kqC-3rBf4VRh
regular
-LZQu0HReRqMhbnWgFJg
regular
This is working as expected. If you want only a single child value, your query will have to give the entire path to that location. For example, you will need to call out promos/-LZHfDw9kqC-3rBf4VRh/regular. You can't use wildcards.
If you don't know the name of a node, perhaps because it's a random push ID, then you need to query those children for the one(s) you want.

Android , Firebase JSON string

I am new to Android and Firebase.. I have stored data in Firebase DB by importing JSON file. Now I am trying to retrieve data in Android textbook. But I am unable to stringify the JSON data, which I did in JavaScript. Also I am not able to get the data in the numerical order, which I am getting in JavaScript.
Following the code DB structure:
// Initialize with secondary app.
FirebaseApp.initializeApp(this /* Context */, SITEINFO, "secondary_SITEINFO");
// Retrieve secondary app.
FirebaseApp secondary_siteinfo = FirebaseApp.getInstance("secondary_SITEINFO");
// Get the database for the other app.
FirebaseDatabase secondaryDB_siteinfo = FirebaseDatabase.getInstance(secondary_siteinfo);
final Query query1 = secondaryDB_siteinfo.getReference("");
fetch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
query1.orderByChild("01-SITEID").equalTo("EKM01").addListenerForSingleValueEvent
(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String Value1 = dataSnapshot.getValue().toString();
My Javascript code
var ref = firebase.database().ref('/').orderByChild("01-SITEID").equalTo(input_final)
ref.on("child_added", function(snapshot) {
var obj = JSON.stringify(snapshot.val());
The Firebase native SDKs for Android and iOS return native types for their respective language. They don't return JSON, nor do they have built-in options to convert the data they return to JSON.
If you need to convert the Java objects to JSON for your app, you will have to implement it yourself (or find a library).
Update
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
To process the result of your query (in the correct order), use DataSnapshot.getChildren():
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot: DataSnapshot.getChildren()) {
System.out.println(childSnapshot.getKey()+": "+childSnapshot.child("01-SITEID").getValue());
}
}

"Failed to bounce to type" when synchronizing local sqlite db with firebase db

I have stored the data on Firebase as follows:
mlist=dbHandler.getAllContacts(1);
for (int i=0;i<mlist.size();i++) {
reportModel = mlist.get(i);
ref = new Firebase(Config.FIREBASE_URL);
Firebase userRef = ref.child(mUserId);
Map newUserData = new HashMap();
newUserData.put("Sno", reportModel.getSno());
newUserData.put("level", reportModel.getLevel());
newUserData.put("rounds", reportModel.getRounds());
newUserData.put("date", reportModel.getDate());
newUserData.put("time", reportModel.getDatesep());
userRef.push().setValue(newUserData);
mref=userRef.push();
newId=mref.getKey();
}
Now I want to retrieve all the data from the Firebase database for a specific user. I have written the code as:
for (DataSnapshot ds: dataSnapshot.getChildren()) {
reportModel = new ReportModel();
reportModel.setSno(ds.getValue(ReportModel.class).getSno());
reportModel.setLevel(ds.getValue(ReportModel.class).getLevel());
reportModel.setRounds(ds.getValue(ReportModel.class).getRounds());
reportModel.setDatesep(ds.getValue(ReportModel.class).getDatesep());
mlist.add(reportModel);
}
if(mlist.size()>0){
adapter = new ReportAdapter(mContext, R.layout.adapter_layout,
mlist);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
}
But the app is crashing with the error :
com.firebase.client.FirebaseException: Failed to bounce to type
I want that if I delete the data from the ListView then after clicking button the data to be retrieved from Firebase and stored on ListView.
The error stats that Firebase is not able to map its data to the defined class.
Check if:
1) ReportModel has an empty constructor.
2) ReportModel variables and Firebase fields have the same name.
3) Map data the following way:
reportModel = ds.getValue(ReportModel.class);

Categories

Resources