Populate textView from firebase database - android

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

Related

In Android Studio, retrieving Data from Firebase does not work

When running the app the data is not retrieved but when debugging i can see where it is in terms of the database link.
When it runs and get to addValueEventListener, it doesn't go into the function which is pretty weird, don't know if this is because its async or not but either way data from Firebase does not get retrieved.
public GarbageItems(int itemNum) {
String itemId = String.valueOf(itemNum);
database = FirebaseDatabase.getInstance();
gameObjectRef = database.getReference().child("gameObjects");
itemInformationGrabber(gameObjectRef, itemId);
}//GarbageItems(Constructor)
private void itemInformationGrabber(DatabaseReference gameObjectRef, String itemId) {
DatabaseReference dataReference = gameObjectRef.child(itemId);
DatabaseReference itemColor = dataReference.child("Color");
itemColor.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange( DataSnapshot dataSnapshot) {
String color = dataSnapshot.getValue(String.class);
setColor(color);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
This is in a different classs that calls GarbageItem
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
colorTextView = findViewById(R.id.ColorTextView);
itemTextView = findViewById(R.id.ItemNameTextView);
GarbageItems garbageItems = new GarbageItems(1);
Color = garbageItems.getColor();
}
try this...
private void itemInformationGrabber(DatabaseReference gameObjectRef, String itemId) {
DatabaseReference dataReference = gameObjectRef.child(itemId);
DatabaseReference itemColor = dataReference.child("Color");
itemColor.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange( DataSnapshot dataSnapshot) {
for(Datasnapshot dataSnap : dataSnapshot.getChildren()){
String color = dataSnap.child("Color").getValue(String.class);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Hope it helps you :)

onClick update to firebase database not working

I'm trying to update the identity value of the user with onClick method of the update button but it is not working and no value is being updated.
Here is my activity (I used the Query to get to the user unique ID):
public class Update extends AppCompatActivity {
EditText identity;
DatabaseReference ref;
Button update;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check);
update = (Button) findViewById(R.id.button_update);
identity = (EditText) findViewById(R.id.edit_text_identity);
mStorageRef = FirebaseStorage.getInstance().getReference("uploads");
String key = getIntent().getExtras().get("androidId").toString();
final Query userQuery = FirebaseDatabase.getInstance().getReference().child("Users").orderByChild("androidId");
userQuery.equalTo(key).addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot foodSnapshot: dataSnapshot.getChildren()) {
final String userUID = foodSnapshot.getKey();
ref = FirebaseDatabase.getInstance().getReference().child(userUID);
identity.setText(getIntent().getStringExtra("identity"));
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ref.child("identity").setValue("noo");
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
}
);
}
}
My database structure is like:
{
"Users" : {
"uid1" : {
"name" : "Josh",
"identity": "yes"
},
"uid2" : {
"name" : "June",
"identity": "no"
}
}
}
And there is no error showing in the logcat. What might be the problem here?
The problem here is that the ref you've used is not pointing exactly to the node you want to be updated. You can use this to do so:
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("Users").child(uidYouWant);
rootRef.child("identity").setValue("noo");
}
});
Also to get the uidYouWant instead of using query you can go though all the nodes to get the one you want, using orderByChild() and equalTo() directly like this:
ref.orderByChild("androidID").equalTo(key).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot data: dataSnapshot.getChildren()){
// do what you want to
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

Pulling data from Firebase into an Android Application

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

getting multiple node in firebase

I got problem with my app that i develop using Android Studio and Firebase.
I want to get data from firebase and compare it with another data from firebase and show it in a listview.
The data that i want, is the string in the follow image.
The problem here is, I dont know how to get multiple string from the database.
This is the code that i having been trying:
public class testActivity extends AppCompatActivity {
private DatabaseReference applydatabase;
String app;
String applied;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
app = getIntent().getExtras().getString("id");
applydatabase = FirebaseDatabase.getInstance().getReference().child("Apply").child(app).child("Applyid");
applydatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
applied = dataSnapshot.getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
You can use DataSnapshot.getChildren() to get the child nodes and loop over them.
applydatabase = FirebaseDatabase.getInstance().getReference().child("Apply").child(app).child("Applyid");
applydatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String first = null, second = null;
for (DataSnapshot child: dataSnapshot.getChildren()) {
if (first == null) {
first = child.getValue(String.class);
} else if (second == null)
second = child.getValue(String.class);
}
}
// TODO: compare first and second
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});

Firebase - retrieve data in Android

I have a data looks like this:
{
"courses" : {
"Business" : {
"-KOBuojCGl_KVNgCx6l3" : {
"courseCode" : "BUS2202",
"courseName" : "Business Mathematics"
},
"-KOCH9RvYkwIamb0oxi8" : {
"courseCode" : "BUS2302",
"courseName" : "Business Fundamentals"
}
},
"Computing & IT" : {
"-KOBukFDN8eDjzF77haS" : {
"courseCode" : "SDT2201",
"courseName" : "System Designs"
},
"-KOBuriS_C5njfhAkV_P" : {
"courseCode" : "SDT3201",
"courseName" : "Computer Project"
},
"-KOD-E81rtXhzEmSeRPx" : {
"courseCode" : "SDT2202",
"courseName" : "System Designs Year 2"
},
}
}
}
And an UI looks like this:
When user selects Business Fundamentals, textview1 should display BUS2302 and textview2 should display Business Fundamentals.
Codes I'm trying now:
public class MainActivity extends AppCompatActivity{
private TextView tv1, tv2;
private DatabaseReference mRef;
private String code, name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRef = FirebaseDatabase.getInstance().getReference().child("courses").child("Business");
tv1 = (EditText) findViewById(R.id.textview1);
tv2 = (EditText) findViewById(R.id.textview2);
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
CourseDetails courseDetails = dataSnapshot.getValue(CourseDetails.class);
code = courseDetails.getCourseCode();
name = courseDetails.getCourseName();
tv1.setText(code);
tv2.setText(name);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
CourseDetails class:
public class CourseDetails {
private String courseCode;
private String courseName;
public CourseDetails() {
}
public CourseDetails(String courseCode, String courseName) {
this.courseCode = courseCode;
this.courseName = courseName;
}
public String getCourseCode() {
return courseCode;
}
public void setCourseCode(String courseCode) {
this.courseCode = courseCode;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
}
When I run the codes, both the textviews just blank, and no error message. When I changed mRef ValueEventListener to this:
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
tv1.setText(dataSnapshot.getValue().toString());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The whole JSON data printed out in textview1, so I know my data is there. But when I use getCourseCode() and getCourseName(), the textviews are blank. Any suggestions?
I have another question which the codes will be used to get the push key of a course, then only display the course code and name accordingly. The question can be found here
In your MainActivity for mRef it reference till node Business of the database which has further two children with keys which I think are generated using push. So, I think you have to iterate over it's children. Can you try something like below:
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// for each children
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
CourseDetails courseDetails = snapshot.getValue(CourseDetails.class);
code = courseDetails.getCourseCode();
name = courseDetails.getCourseName();
tv1.setText(code);
tv2.setText(name);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
If this gives some result apart from null, then may have to work in mapping textViews with respective to key.

Categories

Resources