Pulling data from Firebase into an Android Application - android

Above is my firebase database I am trying to pull from.
As you can see I have a "table" called "Make". I have succesfully been able to pull this data into a Listview within my app. The code for this is below.
I now need to pull all the data from "VW_Data" table. This table has over 1000 childen named as "0" up to "1000" with the same headings in each such as "Bearing", "Altitude" etc but with different values. I would like to be able to pull "Bearing" value only from ALL 1000 children of "VW_Data" and display in a list.
However i have attempted only to try pull "VW_Data/0/Bearing" multiple ways which have not worked.
Here is my updated code for this class:
public class Graphview extends Activity
{
//Holds the values gathered from firebase
final ArrayList<String> graphlist = new ArrayList<>();
ArrayAdapter<String> arrayAdapter;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//Sets the layout according to the XML file
setContentView(R.layout.activity_graphview);
//XML variable
final ListView listViewG = findViewById(R.id.listviewG);
DatabaseReference database = FirebaseDatabase.getInstance().getReference().child("VW_Data");
database.addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
for (DataSnapshot datas : dataSnapshot.getChildren())
{
String bearing = (String) datas.child("Bearing").getValue();
//Add the info retrieved from datasnapshot into the ArrayList
graphlist.add(bearing);
arrayAdapter = new ArrayAdapter<>(Graphview.this, R.layout.itemview, graphlist);
listViewG.setAdapter(arrayAdapter);
//Will refresh app when the data changes in the database
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}//End onCreate()

Try this :
DatabaseReference database = FirebaseDatabase.getInstance().getReference().child("VW_Data");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> verticalSnapshotItr = dataSnapshot.getChildren();
if (verticalSnapshotItr != null) {
for (DataSnapshot verticalItemSnapshot : verticalSnapshotItr) {
String altitude = (String) verticalItemSnapshot.child("Altitude").getValue();
// Parse rest keys here
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

Try this:
DatabaseReference db = FirebaseDatabase.getInstance()
.getReference()
.child("VW_Data");
db.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
String bearing = datas.child("Bearing").getValue().toString();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
snapshot is at VW_Data then use the for loop, you will be able to iterate inside "0" and retrieve the value bearing

Related

Firebase DataSnapshot on how to display result in text view

I had already done on the data update part and now i would like to extract the data and display it based on user input. I have a edit text column for user to key-in and text view to display the data that i stored in Firebase. May i know what is the best coding to work on this ? I found alot of them are using DataSnapshot but they directly read specific value from android studio while i would like to read the value from user input.[https://i.stack.imgur.com/aYrOF.png]
Edittext key in -> 978
TextView shows = 12
tv_displayIsland=(TextView)findViewById(R.id.tv_displayIsland);
et_scanIsbn=(EditText)findViewById(R.id.et_scanIsbn);
database= FirebaseDatabase.getInstance().getReference();
database.addValueEventListener(new ValueEventListener() {
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
-- need the coding to read the et_scanIsbn and display in tv_displayIsland--
}
}
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
You can retrieve the value of et_scanIsbn by doing the following:
String sbn = et_scanIsbn.getText().toString();
Then you can do:
database.child("Island").orderByChild("isbn").equalTo(sbn).addValueEvent....
Inside the onDataChange you can display the retrieved value inside the TextView:
for(DataSnapshot ds : dataSnapshot.getChildren()){
String island = ds.child("island").getValue(String.class);
tv_displayIsland.setText(island);
This is my code now.
package com.example.scanning;
public class Scan extends AppCompatActivity {
DatabaseReference database;
TextView tv_displayIsland;
EditText et_scanIsbn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
tv_displayIsland = (TextView) findViewById(R.id.tv_displayIsland);
et_scanIsbn = (EditText) findViewById(R.id.et_scanIsbn);
String sbn = et_scanIsbn.getText().toString();
database = FirebaseDatabase.getInstance().getReference();
database.child("Island").orderByChild("isbn").equalTo(sbn).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String island = ds.child("island").getValue(String.class);
tv_displayIsland.setText(island);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}

How to collect numerical values within children using Firebase database

Hi I am trying to develop an application. I can tell you I'm new to this. I want to aggregate the number values of children under a title using Firebase database. How can I achieve this?
Example Children1 = "10" Children2 = "20" I want Children1 + Children2 = 30
You can try this
private FirebaseDatabase database = FirebaseDatabase.getInstance();
private final DatabaseReference myRef = database.getReference("IndexOfYourDatabase"); //Init your ref according to your index
private int res = 0;
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot messageSnapshot : dataSnapshot.getChildren()) {
res += Integer.parseInt(messageSnapshot.child("").getValue().toString()); //acces to the value of every child and count them in res.
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
Don't forget to replace IndexOfYourDatabase by gour Index
By this way you implement a for loop to add up the values of your children
If you want to calculate single values from different childrens then use below code :-
FirebaseDatabase.getInstance().getReference().child("database root name").child("database root field key").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int val1 = Integer.parseInt(dataSnapshot.child("childern1").getValue().toString();
int val2 = Integer.parseInt(dataSnapshot.child("childern2").getValue().toString();
int total = val1 +val2;
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
If you want to calculate number of records,
private int totalval= 0;
FirebaseDatabase.getInstance().getReference().child("database root name").child(database root key name).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot innerChild : dataSnapshot.child("childern1").getChildren()) {
totalVal + = Integer.parseInt(innerChild.child("").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Populate textView from firebase database

I am trying to populate a TextView from a firebase database. Here is the sample json file.
{
"Player" : {
"Club" : "Valley Rovers",
"Name" : "John Murphy"
}
}
Here is my android code:
public class MainActivity extends AppCompatActivity {
private TextView mPlayer;
private DatabaseReference mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPlayer = (TextView) findViewById(R.id.player);;
mDatabase = FirebaseDatabase.getInstance().getReference("Player").child("Name");
final String player = mDatabase.push().getKey();
mDatabase.child("Name").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Check for null
if (player == null) {
Log.e(TAG, "User data is null!");
return;
}
mPlayer.setText(player);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
I want to add the name John Murphy to the firebase database and doing so the TextView mPlayer will populate with John Murphy.
You are getting the child "Name" twice on your code (leading to Player/Name/Name). Remove it from the mDatabase initialization:
mDatabase = FirebaseDatabase.getInstance().getReference("Player");
And you're never really getting the value from the DataSnapshot received. To do so, use this:
mDatabase.child("Name").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String playerName = dataSnapshot.getValue(String.class);
mPlayer.setText(playerName);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
In case someone wants to use POJO approach to this problem in future, follow the example below:
Remove the child("Name") from mDatabase.child("Name").addValueEventListener(new ValueEventListener()
unless you want to fetch the "Name" child only. Also remember to effect the correction made on mDatabase initialization.
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// String playerName = dataSnapshot.getValue(String.class);
PlayerModel playerModel = dataSnapshot.getValue(PlayerModel.class);
((TextView)findViewById(R.id.textviewName)).setText(playerModel.getName());
((TextView)findViewById(R.id.textviewClub)).setText(playerModel.getClub());
// mPlayer.setText(playerName);
}

How to prevent redundancy of keys that are in Firebase database when I retrieve them random?

This is my randomly retrieving data codes:
mDataSelect.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> lst = new ArrayList<String>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Collections.shuffle(lst);
lst.add(String.valueOf(ds.getKey()));
randomGenerator = new Random();
int index = randomGenerator.nextInt(lst.size());
String item = lst.get(index);
idofcaps.setText(item);
final DatabaseReference capsSelect = mDataSelect.child(item);
capsSelect.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dss) {
String post_Image = (String) dss.child("Image").getValue();
Picasso.with(StartCapsActivity.this).load(post_Image).into(caps);
String post_name = (String) dss.child("Translation").getValue();
translation.setText(post_name);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
I have a next button in my screen which has the same code for retrieve another image from database. However, I don't want to retrieve same image again. How can I prevent this redundancy?
Create an arraylist then add the retrieved key. Then remove possible duplicate keys. How do I remove repeated elements from ArrayList?

Make an ArrayList from Firebase Data

I have an ArrayList defined in my Android app for my MainActivity.
I've been running into difficulties trying to understand how to retrieve the interests of the user and add it to my array list.
Here's how my Firebase data is set up:
I understand that I must load the data asynchronously, but I'm confused as to how I should go about that.
here's my code for trying to add to the ArrayList:
public class MainActivity extends AppCompatActivity {
private DatabaseReference eventDatabase;
private DatabaseReference usersDatabase;
private FirebaseAuth mAuth;
private String currentUserID;
private ArrayList<String> userInterests = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
eventDatabase = FirebaseDatabase.getInstance().getReference().child("Event");
usersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
usersDatabase.child(currentUserID).child("interests").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot : dataSnapshot.getChildren()){
boolean isInterested = (Boolean)postSnapshot.getValue();
if (isInterested){
userInterests.add(postSnapshot.getKey());
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
System.out.println(userInterests);
I want the ArrayList to consist of the user's interests, if it is false in the database, it won't be added to the list. Example: [COMPETITION, CULTURE, EDUCATION...etc]
When it returns the list in the console, I just see an empty list -- "[]"
This is what you want.
usersDatabase.child(currentUserID).child("interests").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot : dataSnapshot.getChildren()){
boolean isInterested = (Boolean)postSnapshot.getValue();
if (isInterested) {
userInterests.add(postSnapshot.getKey());
}
}
If you are using firebase with Android, then i would suggest you to use firebase-ui components, Firebase UI, it will be very helpful
Or Instead of trying to cast in Boolean, try with String and the convert it to Boolean

Categories

Resources