Show list of data on my firebase database - android

Hello I'm trying to show the data's that i have inputted in my activity, but the problem is i don't have any idea how to, I'm at lost on the data snapshot one. I'm trying to like only show the name and email
My database
my code and progress so far
public class AdminActivity extends AppCompatActivity {
private DrawerLayout mdrawerl;
private ActionBarDrawerToggle mtoggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin);
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Accounts").child("Users");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
collectName((Map<String,Object>)dataSnapshot.getValue());
}
private void collectName(Map<String, Object> value) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
reference that i used How to get all child's data in firebase database?

1- Create a model class that will hold the objects of user. In your case it would be
public class User {
private String email;
private String name;
private int type;
public User() {
}
public User(String email, String name, int type) {
this.email= email;
this.name= name;
this.type= type;
}
}
2 - Create a ArrayList that will hold items of User
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ArrayList<User> userList = new ArrayList();
for (DataSnapshot child :
dataSnapshot.getChildren()) {
User user = child.getValue(User.class);
userList.add(user )
}
//Here you have all user you can pass ```userList``` to your method furthur
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Hope this will help you.

Related

How to retrieve nested data from firebase

This is the structure of data from my firebase:
I have problem to retrieve all "menukedai" data. By using the code below, data from "menukedai" didnt come out. For your information, the data of "menukedai" will come from the user.
This is my attempt:
foodDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads").child("menukedai");
foodDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
foodmenu foodmenu = postSnapshot.getValue(foodmenu.class);
fooddata.add(foodmenu);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(foodlist.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
This is my foodmenu class.
package com.example.trialfoodbuddy;
public class foodmenu {
private String Foodimage;
private String Foodname;
private CharSequence Foodprice;
public foodmenu(){
//empty constructor needed
}
public foodmenu(String foodimage, String foodname, CharSequence foodprice){
Foodimage = foodimage;
Foodname = foodname;
Foodprice = foodprice;
}
public String getFoodimage(){
return Foodimage;
}
public String getFoodname(){
return Foodname;
}
public CharSequence getFoodprice(){
return Foodprice;
}
public void setFoodimage(String foodimage){
Foodimage = foodimage;
}
public void setFoodname(String foodname){
Foodname = foodname;
}
public void setFoodprice(CharSequence foodprice){
Foodprice = foodprice;
}
}
I Believe you want to get the information nested under "menukedai" so you will need to add another loop for that information
foodDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
foodDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot uploadSnapshot : dataSnapshot.getChildren()) {
// this is where you actually getting the information
for(DataSnapshot menuItemSnapshot : uploadSnapshot.child("menukedai").getChildren()){
foodmenu foodmenu = menuItemSnapshot.getValue(foodmenu.class);
fooddata.add(foodmenu);
}
}
}
// Log the values and check them to make sure you getting the data you want if always nice so I added it for you here
Log.i("Values","My values are:"+foodmenu);
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(foodlist.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Normally speaking, You should always use the variable names in your class in your Database so when you pulling the information, your constructor would know what value assign to which variable in your class.

get right data for specific user from Firebase

I have a chat app and I'm trying to pull down the chat groups that the logged in user is part of. I'm struggling to get down the right groups. Here is my firebase structure. All the members are under the "members" child inside a group. I'm displaying the groups in a recyclerview that works fine. This has of course work for any user that logs in and a user can be part of many different groups. I hope you get the idea and can help me. Thanks
My code:
private FirebaseDatabase mDatabase;
private DatabaseReference mDatabaseReference;
private FirebaseAuth mAuth;
private FirebaseUser mUser;
private String projectId;
private List<DataService> grouplist;
private RecyclerAdapter recyclerAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser();
mDatabaseReference = mDatabase.getReference().child("groups");
mDatabase = FirebaseDatabase.getInstance();
mDatabaseReference.keepSynced(true);
grouplist = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
protected void onStart() {
super.onStart();
grouplist.clear();
mDatabaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
DataService groupData = dataSnapshot.getValue(DataService.class);
grouplist.add(groupData);
recyclerAdapter = new RecyclerAdapter(Main.this, grouplist);
recyclerView.setAdapter(recyclerAdapter);
recyclerAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
DataService.java
public class DataService {
public String subject;
public String projectName;
public String endDate;
public String members;
public String userid;
public String creationDate;
public String dropbox;
public String evernote;
public String googleDocs;
public DataService() {
}
public DataService(String subject, String projectName, String endDate, String members, String userid, String creationDate, String dropbox, String evernote, String googleDocs) {
this.subject = subject;
this.projectName = projectName;
this.endDate = endDate;
this.members = members;
this.userid = userid;
this.creationDate = creationDate;
this.dropbox = dropbox;
this.evernote = evernote;
this.googleDocs = googleDocs;
}
public String getCreationDate() {
return creationDate;
}
public void setCreationDate(String creationDate) {
this.creationDate = creationDate;
}
public String getDropbox() {
return dropbox;
}
public void setDropbox(String dropbox) {
this.dropbox = dropbox;
}
public String getEvernote() {
return evernote;
}
public void setEvernote(String evernote) {
this.evernote = evernote;
}
public String getGoogleDocs() {
return googleDocs;
}
public void setGoogleDocs(String googleDocs) {
this.googleDocs = googleDocs;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public String getmembers() {
return members;
}
public void setmembers(String members) {
this.members = members;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
}
Using the actual database structure, you cannot get all the groups a user is in, unless you make some changes to your database. In your case, you should consider augmenting your database structure to allow a reverse lookup by creating another node, named groups under each user object, in which you should add all the group ids from which the user is appart of. So your database structure should look like this:
Firebase-root
|
--- users
|
--- userId
|
--- groups
|
--- groupIdOne: true
|
--- groupIdTwo: true
To get all the groups a user is appart, just attach a listener on the groups node and there are all the groups that you need.
But you'll be thinking, why to do this? Why to duplicate data? Well, there is no problem with duplicating data, when it comes to Firebase. This is a quite common practice, which is named denormalization and for that, I recommend you see this video, Denormalization is normal with the Firebase Database.
When you are duplicating data, there is one thing that need to keep in mind. In the same way you are adding data, you need to maintain it. With other words, if you want to update/detele an item, you need to do it in every place that it exists.

How to list data from Firebase database to listview? Android

I am trying to create a system where I can enter a reminder into the Android app, have it sent to Firebase to be accessed to all devices with the app, and have that reminder come up on a notification. I still need to make the interface that I can send things to Firebase from the app, but I am having trouble retrieving the data. Right now it doesn't like my listView.setAdapter(arrayAdapter) line because it thinks I am calling a null object reference. This is my code:
public class MainActivity extends AppCompatActivity {
ListView listView;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
ArrayList<String> arrayList = new ArrayList<>();
ArrayAdapter<String> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Users");
Toast.makeText(this, "ok", Toast.LENGTH_SHORT).show();
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String value=dataSnapshot.getValue(String.class);
arrayList.add(value);
arrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(arrayAdapter);
}//public void onChildAdded(DataSnapshot dataSnapshot, String s) end
class User {
public String username;
public String email;
public User() {
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public User(String username, String email) {
this.username = username;
this.email = email;
}
}//class User end
public void writeNewUser(String userId, String name, String email) {
User user = new User(name, email);
}
#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) {
}
});
}//protected void onCreate(Bundle savedInstanceState) end
}
There are some unused classes, but my main question is, Why is the array null? And why does this crash the app when I try to run it on the emulator?
Also, the only things in my database are parent Users and its one child, "goy" (as a test child).

Fetch data from firebase in Android

Not able to fetch the data it gives "Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()".Not Able to find any solution please help.
The Code is
public class AdminUser extends AppCompatActivity {
private TextView tv1,tv2;
private DatabaseReference mDatabase;
private FirebaseAuth auth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_user);
auth = FirebaseAuth.getInstance();
String username=FirebaseAuth.getInstance().getCurrentUser().getUid();
mDatabase= FirebaseDatabase.getInstance().getReference().child(username);
tv1=(TextView)findViewById(R.id.textView6);
tv2=(TextView)findViewById(R.id.textView8);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// String name=dataSnapshot.getValue().toString();
String name=dataSnapshot.child("name").getValue(String.class).toString() ;
String address=dataSnapshot.child("address").getValue(String.class).toString();
tv1.setText(name);
tv2.setText(address);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
This 2 lines:
String name=dataSnapshot.child("name").getValue(String.class).toString() ;
String address=dataSnapshot.child("address").getValue(String.class).toString();
are causing your problem, go to the Firebase documentation and read about how to read data from the realtime database here
https://firebase.google.com/docs/database/android/read-and-write
Edit
To give you an example specific to your question, first you need to create a Plain Old Java Object (POJO) class that represent the data you have in your database, for example.
public class User {
private String name;
private String address;
public User() {
//Empty constructor required by firebase
// serialize the data retrieved and convert
// it to an object of this class
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Then in your valueEventListener you can do something like this
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Serialize your retrieved data to a User object
User user = dataSnapshot.getValue(User.class);
//Now you have an object of the User class and can use its getters like this
tv1.setText(user.getName());
tv2.setText(user.getAddress());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Hope this helps

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

Categories

Resources