How to retrieve the key:true Firebase pattern in Android - 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.

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.

fetching related data using the same uid

i trying to read related data from dataorder which related using userID from datauser.
private void cobacoba(){
FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser();
String userid = user.getUid();
DatabaseReference databaseUser = FirebaseDatabase.getInstance().getReference("datauser");
databaseUser.child(userid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String nama = dataSnapshot.getValue(dataUser.class).getUserId();
hey.setText("haloo "+nama);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
i use code above to read data from datauser but how do i read the related data on dataorder ?
i try the same way to read the idOrder from dataorder but the value always null. can some one help please ?
FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser();
final String userid = user.getUid();
DatabaseReference databaseOrder = FirebaseDatabase.getInstance().getReference("dataorder");
databaseOrder.child(userid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
final String idorder = dataSnapshot.getValue(dataOrder.class).getIdOrder();
if (!TextUtils.isEmpty(idorder)){
status.setText(idorder);
FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser();
final String userid = user.getUid();
final DatabaseReference databaseOrder = FirebaseDatabase.getInstance().getReference("dataorder");
databaseOrder.child(userid).child(idorder).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String haritanggal = dataSnapshot.getValue(dataOrder.class).getHaritanggalOrder();
String jamlapangan = dataSnapshot.getValue(dataOrder.class).getLapanganjamOrder();
idordeer.setText("Order ID = "+idorder);
jamtanggal.setText("Tanggal dan Waktu = "+jamlapangan+" Tanggal "+haritanggal);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}else {
status.setText("no current order");
}
status.setText("id anda= "+idorder+" ....."); //<<<id value always null, why ?????
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
using code above, i discover idOrder always null thats why i cannot access the data inside it, because i don't have the key. any sugestion please ?
Please check your query :
databaseUser.child(userid).child(idorder)
instead use :
databaseOrder.child(userid).child(idorder)

Retrieve specific data from firebase

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

Firebase database and search functionality

I need a help in firebase database,
I am willing to create an app for a city like Kolkata, to find buses between different local stations, I want to save the data in database and user will input where to where they want to go, after clicking on search, list of available data will be shown,
But I need help in how should I save the data to fetch it easily with less complicated code.
You can save data easily with firebase
private void writeNewUser(String userId, String name, String email) {
User user = new User(name, email);
mDatabase.child("users").child(userId).setValue(user);
}
You can search from firebase like below
DatabaseReference mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference();
Query query = mFirebaseDatabaseReference.child("users").orderByChild("name").equalTo("Fazal");
query.addValueEventListener(valueEventListener);
ValueEventListener valueEventListener = new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
for (DataSnapshot postSnapshot : dataSnapshot.getChildren())
{
//TODO get the data here
User user = dataSnapshot.getValue(User.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
};
EDIT:
Firebase dont have a great SQL like searches built in. You can either sort by values/key or you can equalto
https://firebase.google.com/docs/database/android/retrieve-data
for further details check fire-base documentation
https://firebase.google.com/docs/database/android/read-and-write
when you write data into firebase database used below code ..
make pojo class for insert data..
public class City {
public String name, code;
public City(String name, String code) {
this.name = name;
this.code = code;
}
}
then after when you insert data into firebase used below code..
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_layout);
mFirebaseDatabase = mFirebaseInstance.getReference("usersDb/UserTable");//define your database name and table name
}
// below method used insert data..
private void insertData(){
City city=new City("Ahmedabad","380016"); // you can add data also runtime.
mFirebaseDatabase.child(city.name).setValue(user);
}
// below method used to search data..
private void sqlQuery(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("usersDb").child("UserTable").orderByChild("name").equalTo("vikas#gmail.com");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot issue : dataSnapshot.getChildren()) {
Log.d("Value::",issue.getValue(User.class).email);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

How can I give access to certain objects in Firebase database based on id

I have this data structure:
The red arrows points at animal IDs, and the blue arrow points at user IDs. Every user have one or many animals.
I have tried different methods for showing only the animals that have id that is stored in the current user node.
Example: If I have UID = 48onHXIxgDP465j5WW16oo7psNm2 (the first one in "users") I want to show the data from: "dog2" and "dog3".
Now iIhave the following code that gets snapshot from the "animals" node in the database, and then gets data from every child.
myAnimalRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
list = new ArrayList<AnimalCard>();
for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){
AnimalCard value = dataSnapshot1.getValue(AnimalCard.class);
AnimalCard animal = new AnimalCard();
String name = value.getName();
int age = value.getAge();
String url = value.getUrl();
animal.setName(name);
animal.setAge(age);
animal.setUrl(url);
list.add(animal);
}
recyclerViewSetAdapter();
progressDialog.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG1, "failed to read value: " + databaseError.toException());
}
});
How can get my code to filter out every animal that does not have their ID in the user node?
The reason I want to make the user get access with an UID stored in the database is because later on I want to make it so that multiple users can get access to the same animal.
To achieve this, you need to query your database twice. Please use the following code:
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
String uid = firebaseUser.getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = usersRef.child("users").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String aid = ds.getKey();
DatabaseReference animalRef = rootRef.child("animals").child(aid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dSnapshot) {
int age = dSnapshot.child("age").getValue(Integer.class);
String name = dSnapshot.child("name").getValue(String.class);
String url = dSnapshot.child("url").getValue(String.class);
Log.d("TAG", age + " / " + name + " / " + url);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
animalRef.addListenerForSingleValueEvent(valueEventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(eventListener);
In which uid is the id of the logged-in user and aid is the id of the animal. Your output will be:
11 / dog1 / http...
12 / dog2 / http...
Hope you find this helpfull.!
Get Object in Your Model Class and Store that Object in List for Further user.!
You can get specific object as well simple using
mdatabaseRef.child("animals").orderByChild().equalTo("value")
and also you can add check on key by orderByKey()
private FirebaseAuth mAuth;
private FirebaseDatabase mdatabase;
private DatabaseReference mdatabaseRef;
mAuth = FirebaseAuth.getInstance();
mdatabase = FirebaseDatabase.getInstance();
mdatabaseRef = mdatabase.getReference();
ArrayList<User> allUserList = new ArrayList<>();
Array<Animal> allAnimalList=new ArrayList<>();
mdatabaseRef.child("animals").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
String key = childSnapshot.getKey();
Animal animal = childSnapshot.getValue(Animal.class);
allAnimalList.add(animal );
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mdatabaseRef.child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
String key = childSnapshot.getKey();
User user = childSnapshot.getValue(User .class);
allUserList.add(user);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I ended up taking Alex Mamo's answer and tweak with a litte bit.
This is the code i'am using:
uid = currentUser.getUid();
mRootRef = FirebaseDatabase.getInstance().getReference();
final DatabaseReference myUserRef = mRootRef.child("users").child(uid);
Log.d(TAG1, uid);
myUserRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
list = new ArrayList<AnimalCard>();
for(DataSnapshot ds : dataSnapshot.getChildren()){
String aid = ds.getKey();
DatabaseReference myAnimalRef = mRootRef.child("animals");
Query query = myAnimalRef.orderByKey().equalTo(aid);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds2 : dataSnapshot.getChildren()){
AnimalCard value = ds2.getValue(AnimalCard.class);
AnimalCard animal = new AnimalCard();
String name = value.getName();
int age = value.getAge();
String url = value.getUrl();
animal.setName(name);
animal.setAge(age);
animal.setUrl(url);
list.add(animal);
}
recyclerViewSetAdapter();
progressDialog.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The main difference is that i'am using a query to filter out every Animal that does not have the aID that the currentUser have.

Categories

Resources