Retrieve specific data from firebase - android

I'm new to firebase, I tried to look into the documentation and youtube but just couldn't figure it out.
I have a simple id and display_name structure database in firebase:
AppName{
users{
HzIYTbIbSzSlinF1Aa52WYUcD4E2{
display_name: "Greg Nks"
}
}
And I want the data to get into a User object, with Id(string) and display_name(string)
I tried to test my retrieving data, but I cant get it.
this is my code:
public void initializeVariables(View view){
mToolBar = view.findViewById(R.id.users_appBar);
usersRv = view.findViewById(R.id.friends_list_rv);
mLayoutManager= new LinearLayoutManager(view.getContext());
myDataset = new ArrayList<>();
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user!=null){
}
}
};
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//remember it will called in the start of the fragment
showData(dataSnapshot); //TODO fix the reading from firebase
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void showData(DataSnapshot dataSnapshot){
User u= dataSnapshot.getValue(User.class);
u=null;
}
Thanks!

Class User {
private String display_name;
private String userKey;
public User(){
}
public User(String name,String key){
display_name = name;
userKey = key;
}
public void setDisplay_name(Sring name)
{
display_name = name;
}
public String getDisplay_name()
{
return display_name;
}
public void setUserKey(Sring key)
{
userKey = key;
}
public String getUserKey()
{
return userKey;
}
}
now change this statment
User u= dataSnapshot.getValue(User.class);
by this :
String key = datasnapshot.getKey();
String name = datasnapshot.child('display_name').getValue().toString();
User user = new User(name, key);

Related

retrieve data from firebase to textview returns null how to fix?

I'm trying to retrieve data from firebase to a texview but it returns null, and I was wondering how I can retrieve the respective data based on the uid only of the connected user.
I tried in different ways today all afternoon but without any success, someone could help me. I've researched and tried all the stackoverflow and internet solutions as well.
I need to retrieve only the "name" field of the structure of the respective connected user.
am i doing something wrong?
any help is welcome.
I need to retrieve only the "name" field of the structure of the respective connected user.
MainActivity Code
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
Button btn_send;
EditText et_contact, et_message;
TextView textView52;
private FirebaseAuth auth;
private User usuario = new User();
private DatabaseReference firebaseDatabase;
private ValueEventListener valueEventListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
btn_send = (Button)findViewById(R.id.btn_send);
et_contact = (EditText)findViewById(R.id.et_contact);
et_message = (EditText)findViewById(R.id.et_message);
textView52 = (TextView)findViewById(R.id.textView52);
PermissionToConnect();
btn_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String number = et_contact.getText().toString();
String message = et_message.getText().toString();
try{
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(number, null, message, null, null);
Toast.makeText(MainActivity.this, "Sent", Toast.LENGTH_SHORT).show();
}catch (Exception e){
Toast.makeText(MainActivity.this, "Sending Failed", Toast.LENGTH_SHORT).show();
}
}
});
DatabaseReference databaseRef= FirebaseDatabase.getInstance()
.getReference();
databaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String data = dataSnapshot.child("Users").child("email").child("name").getValue(String.class);
textView52.setText(data);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
-
User Class code
User Class
public class User {
public String name, email, phone;
public User(){
}
public User(String name, String email, String phone) {
this.name = name;
this.email = email;
this.phone = phone;
}
}
Change this:
databaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String data = dataSnapshot.child("Users").child("email").child("name").getValue(String.class);
textView52.setText(data);
}
Into this:
databaseRef.child("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
String data = ds.child("name").getValue(String.class);
textView52.setText(data);
}
}
You need to add Users as a reference and then iterate to get the name or email.
Another way if you are using firebase auth is to retrieve the current user ID thus removing the iteration.

Firebase to Android

I would like to put this fields "age, email, firstname" [you can see clicking in the Tree of Firebase above] in three Strings "userAge, userEmail, userName" and put then in a text view, when I use this code to get the name
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference();
String userId;
String userName;
//.
//.
//.
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user == null) {
finish();
} else {
userId = user.getUid();
ref.child("users").child(userId).child("firstname").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
userName = dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
textview.setText(userName);
I can get the name and put in the String userName, and show it in the text view
but when I try tpo get the 3 fields with this code:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference();
String userId, UserName, userEmail, userAge
//.
//.
//.
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user == null) {
finish();
} else {
userId = user.getUid();
ref.child("users").child(userId).child("firstname").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
userName = dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
ref.child("users").child(userId).child("email").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
userEmail = dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
ref.child("users").child(userId).child("age").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
userAge = dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
textview.setText(userName + ", " + userAge + "Years - " + useremail);
The App doesn't get the fields and closes, have another way to do this?
Use Integer.class instead of String.class for I saw your data on Firebase is NOT in a quote so it should be retrieve in Integer format.
ref.child("users").child(userId).child("age").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
userAge = dataSnapshot.getValue(Integer.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
}
Actually your issue might be because age is an integer and you are trying to retrieve it as a string. Can you try commenting out age part of the code and see if it works?

arrayList always loaded with user info from Firebase database regardless of which user is signed in?

In showdata method witch load FirebaseUser info when I run the app and signed in with any user , arrayList in the method is always loaded with User_03 info ,
debugging show that:
DataSnapshot ds is loaded with right value of signed in user ( right key and info ) .
uInfo ( the object which carry signed in user info) loaded with right data from database .
uInfo.setName(ds.getValue(UserInformations.class).getName()); = undefined .
I think there is something wrong in arryList size .
the attached screen shot I take it when arrive to breakpoint in line : toastMassege("it's Done") .
public class AddToDatabase extends AppCompatActivity {
private static final String TAG = "AddToDatabase";
private ListView userInfolist ;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
String userId;
UserInformations uInfo =new UserInformations();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_to_database);
userInfolist = (ListView) findViewById(R.id.userInfolist);
mAuth = FirebaseAuth.getInstance();
FirebaseDatabase mFirebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference myRef = mFirebaseDatabase.getReference();
FirebaseUser user = mAuth.getCurrentUser();
userId = user.getUid();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
toastMassege(" You are successfly signed in with " +
user.getEmail());
} else {
Log.d(TAG, "onAuthStateChanged:signed_out");
toastMassege(" You are successfly signed out ");
}
}
};
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
showData(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError error) {
}
});
}
private void showData(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
uInfo.setName(ds.getValue(UserInformations.class).getName());
uInfo.setEmail(ds.getValue(UserInformations.class).getEmail());
uInfo.setPhone_num(ds.getValue(UserInformations.class).getPhone_num());
ArrayList<String> arrayList=new ArrayList<>();
int listSize = arrayList.size();
arrayList.add(uInfo.getName());
arrayList.add(uInfo.getEmail());
arrayList.add(uInfo.getPhone_num());
ArrayAdapter<String> adapter =new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,arrayList);
userInfolist.setAdapter(adapter);
toastMassege("its Done ");
}
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
private void toastMassege(String massege) {
Toast.makeText(this, massege, Toast.LENGTH_SHORT).show();
}
}
this is class UserInformations
class UserInformations {
public String email,name,phone_num ;
UserInformations() {
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone_num() {
return phone_num;
}
public void setPhone_num(String phone_num) {
this.phone_num = phone_num;
}
}
This is happening because you are have declared the ArrayList<String> arrayList=new ArrayList<>(); inside the for loop. This means that you are creating a new instance of ArrayList class every time you iterate.
In order to solve this, just move the decration outside for loop like this:
private void showData(DataSnapshot dataSnapshot) {
ArrayList<String> arrayList=new ArrayList<>(); //Moved outside
for(DataSnapshot ds : dataSnapshot.getChildren()){
uInfo.setName(ds.getValue(UserInformations.class).getName());
uInfo.setEmail(ds.getValue(UserInformations.class).getEmail());
uInfo.setPhone_num(ds.getValue(UserInformations.class).getPhone_num());
int listSize = arrayList.size();
arrayList.add(uInfo.getName());
arrayList.add(uInfo.getEmail());
arrayList.add(uInfo.getPhone_num());
ArrayAdapter<String> adapter =new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,arrayList);
userInfolist.setAdapter(adapter);
toastMassege("its Done ");
}
}

How to a read user Information from Firebase database and display as a List in Android App

I am new here and I'd be glad if anyone can help me.What I want to do is get UID and Username of all the users and display it in a list.
Here is my related code:
mDatabase = FirebaseDatabase.getInstance().getReference();
listView = (ListView) v.findViewById(R.id.listview);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot user : dataSnapshot.getChildren()){
**// Not sure what to do here**
array.add(username);
}
ArrayAdapter adapter = new ArrayAdapter(getContext(), android.R.layout.simple_list_item_1, array);
listView.setAdapter(adapter);
}
My Users Class which I use to Insert User Information
public class User {
public String username;
public String phone;
public User() {
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public User(String username, String phone) {
this.username = username;
this.phone = phone;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPhone() {
return phone;
}
}
And this is how my Database Looks like
Firebase Database
Please use this code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String phone = ds.child("phone").getVelue(String.class);
String username = ds.child("username").getValue(String.class);
Log.d("TAG", phone + " / " + username);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(eventListener);
And your uotput will be:
uo / pol
809151699 / shivam
//and so on
Hope it helps.

How to retrieve the key:true Firebase pattern in Android

I'm new with firebase and I have some doubts that I've spend some time in try to find a solution:
This is my database looks:
user
- l5tCeZmcZtXLITJugdtfHsK647s1
email: "myemail#sample.com"
name: "Bob"
- userType
guestType: 1
- wedding
Kke0cr5NUGEgg3rq_Mf: true
That I'm trying to do is how get the userType data and the wedding data, that is done with the pattern that said the firebase documentation key:true.
This is that I'm doing and I can see that I have all the collection data, but not idea how can I get the data for the labels userType and wedding:
FirebaseUser currentUser = ApplicationConfig.getCurrentUser();
if (currentUser != null) {
DatabaseReference mDatabaseReference = FirebaseDatabase.getInstance().getReference("user");
Query queryFirebase = mDatabaseReference = FirebaseDatabase.getInstance().getReference("user").child(currentUser.getUid());
queryFirebase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
My model;
public class User implements Serializable{
private String name;
private String email;
private int guestType;
private Wedding weeding;
private String uid;
public User() {
}
}
Thanks in advance
Please use this code:
DatabaseReference mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("user").child(currentUser.getUid()).child("userType");
mDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int guestType = (int) dataSnapshot.child("guestType").getValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
In the same way you can retrieve the value of that id in the wedding node.
Hope it helps.

Categories

Resources