Fetch data from firebase in Android - 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

Related

Why my constructor in RecyclerView is getting called late?

I am creating a recyclerView for my project for which I am using 2 functions in onCreate,
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
System.out.println("dsdsds");
pref = getSharedPreferences("pref", Context.MODE_PRIVATE);
dbReff = FirebaseDatabase.getInstance().getReference().child("CartItem");
dbToken = FirebaseDatabase.getInstance().getReference().child("TokenNumber");
CreateList();
BuildRecyclerView();
}
Here I am creating a list which is set in adapter in the first function,
cartItemArrayList = new ArrayList<>();
dbReff.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
if(!data.child("name").getValue().toString().equals("notToDisplayThisItem")) {
cartItemArrayList.add(new CartItemIdQuant(
data.child("id").getValue().toString(),
data.child("quant").getValue().toString(),
data.child("name").getValue().toString(),
data.child("price").getValue().toString()
));
Log.e("THE DATA", data.toString());
}
}
Log.e("INHERE","");
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
and the 2nd function is as followed,
recyclerView = findViewById(R.id.recyclerCartView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
cartAdapter = new CartAdapter(cartItemArrayList);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(cartAdapter);
log.e("Message"," from build recyclerVIew");
and my class for the data item is as followed,
public class CartItemIdQuant {
private String ID;
private String Quant;
private String Name;
private String Price;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getPrice() {
return Price;
}
public void setPrice(String price) {
Price = price;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public String getQuant() {
return Quant;
}
public void setQuant(String quant) {
Quant = quant;
}
public CartItemIdQuant(String NewID, String NewQuant,String NewName,String NewPrice){
ID = NewID;
Quant = NewQuant;
Name = NewName;
Price = NewPrice;
Log.e("the" , "Method Called From Constructor");
}
public CartItemIdQuant(){
}
}
here the log of Data that I receive and print in the 1st function is printed and the log I print in the constructor is then printed after 2 seconds. I want to know the reason for the delay in the call, as I have to put a delay for it to work properly which I do not want.
Please help me, thank you in advance.
EDIT:
here as per the comment, is the logcat in which the message from the 2nd function is called before the list could be created.
2020-02-21 15:20:03.434 547-547/com.chinuEvent.chinuevent E/Message: from build recyclerVIew
2020-02-21 15:20:03.837 547-547/com.chinuEvent.chinuevent E/the: Method Called From Constructor
2020-02-21 15:20:03.838 547-547/com.chinuEvent.chinuevent E/THE DATA: DataSnapshot { key = 02, value = {price=15, name=Orange, id=02, quant=3} }
It is actually completely normal to set the adapter to the view before the data is loaded. In many cases (some of) the data is loaded (or modified) asynchronously, and you'll often want to show those updates as they come in.
All you need to do for that is notify the adapter that its underlying data has changed. The adapter will then notify the view(s), and those will repaint with the updated data.
To notify the adapter, call its notifyDataSetChanged() in your onDataChange handler after you've modified cartItemArrayList:
dbReff.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
if(!data.child("name").getValue().toString().equals("notToDisplayThisItem")) {
cartItemArrayList.add(new CartItemIdQuant(
data.child("id").getValue().toString(),
data.child("quant").getValue().toString(),
data.child("name").getValue().toString(),
data.child("price").getValue().toString()
));
}
}
cartAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // never ignore possible errors
}
});

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).

Show list of data on my firebase database

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.

using Map to get object of custom class

I'm new at using maps, how can we get object of custom Class from Map..
i.e.
feedSendModelClass:
public class feedSendModelClass {
private String content;
private String picThumbnail;
private String picurl;
private String videourl;
private String videoThumbnail;
private String mTime;
public feedSendModelClass() {
//blank for firebase
}
public String getTime() {
return mTime;
}
public void setTime(String time) {
mTime = time;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getVideoThumbnail() {
return videoThumbnail;
}
public void setVideoThumbnail(String videoThumbnail) {
this.videoThumbnail = videoThumbnail;
}
public String getVideourl() {
return videourl;
}
public void setVideourl(String videourl) {
this.videourl = videourl;
}
public String getPicurl() {
return picurl;
}
public void setPicurl(String picurl) {
this.picurl = picurl;
}
public String getPicThumbnail() {
return picThumbnail;
}
public void setPicThumbnail(String picThumbnail) {
this.picThumbnail = picThumbnail;
}
}
Map
Map<String, feedSendModelClass> feedKeys = (Map<String,feedSendModelClass>) dataSnapshot.getValue();
Datasnapshot:
DataSnapshot { key = feedsMetaPool, value = {20160708155218759={content=bzzzhss, picurl=https://firebasestorage.googleapis.com/v0/b/rootssahaj.appspot.com/o/feedsImages%2FnonThumbs%2F201607081552353353553518759sahaj9917730102?alt=media&token=ce1c6e7c-28c5-442e-9405-4468bf5fc204, time=08 Jul, picThumbnail=https://firebasestorage.googleapis.com/v0/b/rootssahaj.appspot.com/o/feedsImages%2Fthumbs%2F20353353535355353160708155218759sahaj9917730102?alt=media&token=14d33963-f3da-4407-a08f-ab0afce21ace}, 20160708164100152={content=sj sjs skss sksssvsjm, picurl=https://firebasestorage.googleapis.com/v0/b/rootssahaj.appspot.com/o/feedsImages%2FnonThumbs%2F201607081641003535152sahaj9917730102?alt=media&token=323c4a27-1850-4bc9-adea-34e5319ac506, time=08 Jul, picThumbnail=https://firebasestorage.googleapis.com/v0/b/rootssahaj.appspot.com/o/feedsImages%2Fthumbs%2F20160708164100152sahaj9917730102?alt=media&token=0b064b46-2f14-49af-b3e6-7a573f6c2d3f}, 20160708142314069={content=dadax, picurl=https://firebasestorage.googleapis.com/v0/b/rootssahaj.appspot.com/o/feedsImages%2FnonThumbs%2F2016070rdgdg54353535358142314069sahaj9917730102?alt=media&token=19d03f11-d12f-43c1-96f5-ca397a9179c9, time=08 Jul, picThumbnail=https://firebasestorage.googleapis.com/v0/b/rootssahaj.appspot.com/o/feedsImages%2Fthumbs%2F20160735353508142314069sahaj9917730102?alt=media&token=ab9c73eb-ec44-46ae-9daa-6fc508cb08a6} }
This has become tricky for me..Thanks..
There could be some other way round to do it through firebase
If you are asking how you retrieve the feedSendModelClass object from the map named feedKeys, then this syntax should work:
feedKeys.get(key)
The key is your String, and the object is the feedSendModelClass object. However, first you'd need to put key and value pairs into the map (so it's not empty), with feedKeys.put(key, value), where the key is a String and value is the feedSendModelClass.
If this totally doesn't answer your question, I apologize, but from your description, it is a bit difficult to understand what you need help with.
On an unrelated note, it would be more appropriate to name your class FeedSendModelClass, as per Java conventions classes start with a capital letter.
If you're using Firebase then you can use a ChildEventListener. It calls the onChildAdded() method once for every initial child in the node and everytime a new child is added. Then you can add the Object to an ArrayList directly (or do whatever you want with it)
ArrayList<feedSendModelClass> feedKeysArrayList = new ArrayList<>();
DatabaseReference feedKeysRef = FirebaseDatabase.getInstance().getReference("path/to/the/feedkeys");
feedKeysRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
feedKeysArrayList.add(dataSnapshot.getValue(feedSendModelClass.class));
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
// Add appropriate code
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
// Add appropriate code
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
// Add appropriate code
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Add appropriate code
}
});

Categories

Resources