Firebase data not able to get immediately - android

I don't know why when I try to call getFromRealm() I can't retrieve it on the first time, in order to get the data I have to close and re-open the app.
Am I doing it in the wrong way? I have tried by using Sqlite, but they are having the same problem. Anyone can help?
My goals is to get data immediately and retrieve on the spot.
Below is the code.
MainActivity:
public class MainActivity extends AppCompactActivity {
private static final String TAG = "MainActivity";
public String mName;
public String mEmail;
private Realm mRealm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRealm = Realm.getInstance(this);
mDatabase = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
saveToRealm();
getFromRealm();
Log.d(TAG, "Name: " + mName); // Here show null at first open the app
Log.d(TAG, "Email: " + mEmail); // Here show null at first open the app
}
}
This is save data to Realm method:
public void saveToRealm() {
ValueEventListener postListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Users details = dataSnapshot.getValue(Users.class);
Log.d(TAG, String.valueOf(dataSnapshot));
String name = details.getName();
String email = details.getEmail();
details.setName(name);
details.setEmail(email);
mRealm.beginTransaction();
mRealm.copyToRealmOrUpdate(details);
mRealm.commitTransaction();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "getUser:onCancelled", databaseError.toException());
}
};
mDatabase.child("User")
.child("Details")
.addValueEventListener(postListener);
}
This is the get data method:
public void getFromRealm() {
RealmResults<Users> results =
mRealm.where(Users.class).findAll();
try{
Users c = results.get(0);
mName = c.getName();
mEmail = c.getEmail();
} catch (Exception e) {
Log.e(TAG, String.valueOf(e));
}
}
This is the object class:
public class Users extends RealmObject {
#PrimaryKey
private long id;
private String name;
private String email;
public Users() {
}
public void setId(long id) {
this.id = id;
}
public long getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
}

Retrieve data from where you are store something like this..
public void saveToRealm() {
ValueEventListener postListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Users details = dataSnapshot.getValue(Users.class);
Log.d(TAG, String.valueOf(dataSnapshot));
String name = details.getName();
String email = details.getEmail();
details.setName(name);
details.setEmail(email);
mRealm.beginTransaction();
mRealm.copyToRealmOrUpdate(details);
mRealm.commitTransaction();
getFromRealm();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "getUser:onCancelled", databaseError.toException());
}
};
mDatabase.child("User")
.child("Details")
.addValueEventListener(postListener);
}
As it will take someTime like seconds to get Data from firebase data so retrieve data after only whenever you store.
Try to get your data like this way..
public void getFromRealm() {
RealmResults<Users> results = mRealm.where(Users.class).findAll();
try {
for(int i=0;i<results.size();i++){
mName = results.get(i).getName();
mEmail = results.get(i).getEmail();
}
} catch (Exception e) {
Log.e(TAG, String.valueOf(e));
}
}

Related

Android how to call updates child item based on the item from another child as input

I have simple sales management function, I want to record sells and update stock at a time when button clicked, to make it work I have three methods
1: Record sales from which I call two methods "UpdatadeStockAfterSells" and "SaveSalesData" since these two methods depend on fetch data from the database.
2: "UpdatadeStockAfterSells" that update stock in after sells
3: "SaveSalesData" is for recording sales.
"SaveSalesData" is working fine but when I try to update stock app keep on crashing, I really don't know where do I get it wrong.
The concept is "I call two methods inside another method so that they can use some fetch data as their inputs.
// for stock
mDatabaseReference = FirebaseDatabase.getInstance().getReference("stocks");
//for sales record
mDatabaseReference1 = FirebaseDatabase.getInstance().getReference("saleRecords");
public class recordSalesModel {
String productName;
String Quantity;
public recordSalesModel(){ }
public recordSalesModel(String productName) {
this.productName = productName;
}
public recordSalesModel(String productName, String quantity) {
this.productName = productName;
Quantity = quantity;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getQuantity() {
return Quantity;
}
public void setQuantity(String quantity) {
Quantity = quantity;
}
}
// Save sales
public void SaveSalesData(String name, String quantity) {
recordSalesModel recordSalesModel = new recordSalesModel(name, quantity);
String uploadId = mDatabaseReference1.push().getKey();
mDatabaseReference1.child(uploadId).setValue(recordSalesModel, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
Toast.makeText(getContext(), "Error : "+ databaseError, Toast.LENGTH_LONG).show();
}
});
Toast.makeText(getContext(), " successful Inserted", Toast.LENGTH_LONG).show();
}
// Update stock
public void UpdatadeStockAfterSells(String ChildKey, String quantity_sold, String stock_Remaining_Quantity, String Stock_Quantity) {
double NewRemainingStock = Double.valueOf(stock_Remaining_Quantity) - Double.valueOf(quantity_sold);
double NewRemainingStockPercentage = (Double.valueOf(NewRemainingStock) / Double.valueOf(Stock_Quantity)) * 100;
mDatabaseReference.child(ChildKey).child("percentageRemain").setValue(String.valueOf(NewRemainingStockPercentage), new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
Toast.makeText(getContext(), "Error : ==> "+databaseError, Toast.LENGTH_LONG).show();
}
});
mDatabaseReference.child(ChildKey).child("remainingQuantity").setValue(String.valueOf(NewRemainingStock), new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
Toast.makeText(getContext(), "Error : ==> "+databaseError, Toast.LENGTH_LONG).show();
}
});
Toast.makeText(getContext(), " UPDATED", Toast.LENGTH_LONG).show();
}
// Method to record sell
public void RecoredSales() {
final String spiner_seleceted_name = areaSpinner.getSelectedItem().toString();
final String Selling_Quantity = quantity.getText().toString();
mDatabaseReference.orderByChild("productName").equalTo(spiner_seleceted_name).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot areaSnapshot : dataSnapshot.getChildren()) {
String stockRemainingQuantity = areaSnapshot.getValue(UploadStockModel.class).getRemainingQuantity();
String stockQuantity = areaSnapshot.getValue(UploadStockModel.class).getQuantity();
String KeyDb = areaSnapshot.getKey();
SaveSalesData(spiner_seleceted_name, Selling_Quantity );
UpdatadeStockAfterSells(KeyDb, Selling_Quantity, stockRemainingQuantity, stockQuantity);
}}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

Query Firebase list with object value

Hi i am using DatabaseReference#push method to add object to reference.
This object has property id.
Next time i have id and i wish to get that user object from that list, how can i get that. I there any simple way to directly Query, or we need to pull all objects and compare each id with the one i require,
here is my object code
#IgnoreExtraProperties
public final class User {
private Integer id;
private String name;
private String secret;
public User() {
}
public User(Integer id, String name, String secret) {
this.id = id;
this.name = name;
this.secret = secret;
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public String getSecret() {
return secret;
}
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setSecret(String secret) {
this.secret = secret;
}
}
This is how i am adding it to firebase console mReference.push().setValue(user); , also i want to know that can we omit thos random generated id for node, becuase i will not be having that kp*** id instead i will be havind id of user object
Her is how i am try to query more code :)
public final class UserReference implements ChildEventListener {
private static final String TAG = UserReference.class.getSimpleName();
private static final List<User> userList = new ArrayList<>();
static {
userList.add(new User(1, "user1", "secret1"));
userList.add(new User(2, "user2", "secret2"));
}
private static final String USER = "users";
private final DatabaseReference mReference;
private Query mSingleUserQuery;
UserReference(FirebaseDatabase database) {
mReference = database.getReference(USER);
// mReference.addChildEventListener(this);
}
//One time use method
public void saveUser() {
for (User user : userList) {
mReference.push().setValue(user);
}
}
public void findUserById(final String id, final OnDbCompleteListener<User> userListener) {
mSingleUserQuery = mReference.orderByChild("id").equalTo(id);
mSingleUserQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Logger.info(TAG, "Key: " + dataSnapshot.getValue());
sendDataAndUnregister(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Logger.info(TAG, dataSnapshot.getKey());
sendDataAndUnregister(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Logger.info(TAG, dataSnapshot.getKey());
sendDataAndUnregister(dataSnapshot);
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
Logger.info(TAG, dataSnapshot.getKey());
sendDataAndUnregister(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
databaseError.toException().printStackTrace();
}
private void sendDataAndUnregister(DataSnapshot dataSnapshot) {
mSingleUserQuery.removeEventListener(this);
userListener.onComplete(dataSnapshot.getValue(User.class));
}
});
}
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Logger.info(TAG, "added: " + dataSnapshot.getKey());
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Logger.info(TAG, "changed: " + dataSnapshot.getKey());
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Logger.info(TAG, "removed: " + dataSnapshot.getKey());
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
Logger.info(TAG, "moved: " + dataSnapshot.getKey());
}
#Override
public void onCancelled(DatabaseError databaseError) {
Logger.info(TAG, "Error: " + databaseError.getMessage());
}
}
Database Class
public final class MySuperCoolDatabase {
private FirebaseDatabase mDatabase;
private UserReference mUserReference;
public MySuperCoolDatabase() {
mDatabase = FirebaseDatabase.getInstance();
mUserReference = new UserReference(mDatabase);
}
public UserReference getUserReference() {
return this.mUserReference;
}
}
Its call:
MySuperCoolDatabase database = new MySuperCoolDatabase();
UserReference userReference = database.getUserReference();
userReference.findUserById("1", new OnDbCompleteListener<User>() {
#Override
public void onComplete(User user) {
Logger.info(TAG, "YAYA");
}
});
DbUpdateListener:
public interface OnDbCompleteListener<T> {
void onComplete(T t);
}
Thanks to #FrankvanPuffelen i had to do following changes, because i was storing id as Integer so i should request for Integer only.
public void findUserById(final Integer id, final OnDbCompleteListener<User> userListener) {
mSingleUserQuery = mReference.orderByChild("id").equalTo(id);
...
}
From
public void findUserById(final String id, final OnDbCompleteListener<User> userListener) {
mSingleUserQuery = mReference.orderByChild("id").equalTo(id);
...
}
Also along with this changes i had to add index as suggested in console by firebase war logger here is the rules files
{
"rules": {
".read": true,
".write": false,
"users": {
".indexOn": "id"
}
}
}
For pushing value directly into node, you could use -
User user = "detail of your user";
// On firebase reference push value on id directly.
ref.child("1").setValue("user);
Here "1" is an id which is going to be primary key for your user detail.
Update -
public void saveUser() {
for (User user : userList) {
mReference.child(user.id).setValue(user);
}
}

Firebase DataSnapshot Null values

My app allows you to add a Player to a node, once they have been added I am using the below method to search by phoneNum to see if that player exists in the 'users' node.
Where I am having trouble is that I need to be able to access the values from the datasnapshot for the user within the found matching node. e.g.return the value of the user id. When I attempt this it keeps showing as a null value and when I try to log to the console it complains that it is a null value which doesn't make sense as the if statement should take care of this.
The method is able to find if a player exists in the the users node and displays a Toast message to indicate this.
Code:
public void checkPlayerNum(final String phoneNum) {
DatabaseReference mDatabaseReference =
FirebaseDatabase.getInstance().getReference().child("users");
if (!TextUtils.isEmpty(phoneNum)) {
final Query phoneNumReference = mDatabaseReference.orderByChild("phoneNum").equalTo(phoneNum);
ValueEventListener phoneNumValueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
// String key = String.valueOf(dataSnapshot.getValue());
User mUser = dataSnapshot.getValue(User.class);
String uId = mUser.getUid();
// Log.d("TAG",uId);
Toast.makeText(getApplicationContext(), "* found **"+ uId , Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "****NOT FOUND****", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
phoneNumReference.addListenerForSingleValueEvent(phoneNumValueEventListener);
} else {
Log.e("Error","phoneNum is null");
}
}
final Query query = mFirebaseDatabase.orderByChild("phoneNum").equalTo("userPhoneNumber");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
//here means the value exist
//do whatever you want to do
} else {
//here means the value not exist
//do whatever you want to do
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
Use this to check whether the data exist or not.
you need to do this at two steps , first check if the user exists. then you get user info by your userId.
DatabaseReference mDatabaseReference;
public void checkPlayerNum(final String phoneNum,final String userId) {
mDatabaseReference =
FirebaseDatabase.getInstance().getReference().child("users");
if (!TextUtils.isEmpty(phoneNum)) {
final Query phoneNumReference = mDatabaseReference.orderByChild("phoneNum").equalTo(phoneNum);
ValueEventListener phoneNumValueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
// user exists
getUserInf(userId);
} else {
Toast.makeText(getApplicationContext(), "****NOT FOUND****", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
phoneNumReference.addListenerForSingleValueEvent(phoneNumValueEventListener);
} else {
Log.e("Error","phoneNum is null");
}
}
get user info by userId. mDatabaseReference is the same as before . define it as member field .
void getUserInf(String userId) {
userValueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// get user data
User mUser = dataSnapshot.getValue(User.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mDatabaseReference.child(userId).addListenerForSingleValueEvent(userValueEventListener);
}
your user Pojo should be like below.
public class User {
String email,name,phoneNum,uid;
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 getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
}
Thanks everybody I managed to achieve it by using childEventListener
public void checkingNumber(final String phoneNum){
DatabaseReference mDatabaseReference =
FirebaseDatabase.getInstance().getReference().child("users");
final Query query = mDatabaseReference;
query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot.getValue() != null) {
// String key = String.valueOf(dataSnapshot.getValue());
User mUser = dataSnapshot.getValue(User.class);
// String uId = mUser.getUid();
// usersDatabase.child(mUser.getUid());
// Log.d("TAG",uId);
if(mUser.getPhoneNum().equals(phoneNum)) {
String uId= mUser.getUid();
String email = mUser.getEmail();
String name = mUser.getName();
Toast.makeText(getApplicationContext(), "* found **" + " " + uId + " " + " " + email + " " + name, Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(), "****NOT FOUND****", Toast.LENGTH_LONG).show();
}
}
#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) {
}
});
}

Firebase Chat After login

I want to select displayName show in UserList. but i don't know how to select displayName in Database users plase can you help me.
eg. i select 6Z86LIYRMaM9vtmOrd23kAeICO63 but i want to show displayName
ListView usersList;
TextView noUsersText;
ArrayList<String> al = new ArrayList<>();
int totalUsers = 0;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_users);
usersList = (ListView)findViewById(R.id.usersList);
noUsersText = (TextView)findViewById(R.id.noUsersText);
pd = new ProgressDialog(Users.this);
pd.setMessage("Loading...");
pd.show();
String url = "https://chatapp.firebaseio.com/users.json";
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>(){
#Override
public void onResponse(String s) {
doOnSuccess(s);
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError volleyError) {
System.out.println("" + volleyError);
}
});
RequestQueue rQueue = Volley.newRequestQueue(Users.this);
rQueue.add(request);
usersList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
UserDetails.chatWith = al.get(position);
startActivity(new Intent(Users.this, Chat.class));
}
});
}
public void doOnSuccess(String s){
try {
JSONObject obj = new JSONObject(s);
Iterator i = obj.keys();
String key = "";
while(i.hasNext()){
key = i.next().toString();
if(!key.equals(UserDetails.username)) {
al.add(key);
}
totalUsers++;
}
} catch (JSONException e) {
e.printStackTrace();
}
if(totalUsers <=1){
noUsersText.setVisibility(View.VISIBLE);
usersList.setVisibility(View.GONE);
}
else{
noUsersText.setVisibility(View.GONE);
usersList.setVisibility(View.VISIBLE);
usersList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, al));
}
pd.dismiss();
}
As suggested in the comments, you should go to the firebase documentation and see how you use the SDK.
https://firebase.google.com/docs/database/android/start/
Specific to your question, you need to create a POJO class of your user so that you can later serialize an object when retrieving the user from the db.
User.java
public class User {
private int avatarId;
private String connection;
private Long createAt;
private String displayName;
private String email;
public User() {
}
public int getAvatarId() {
return avatarId;
}
public void setAvatarId(int avatarId) {
this.avatarId = avatarId;
}
public String getConnection() {
return connection;
}
public void setConnection(String connection) {
this.connection = connection;
}
public Long getCreateAt() {
return createAt;
}
public void setCreateAt(Long createAt) {
this.createAt = createAt;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Then you can fetch users info from the db like this.
DatabaseReference databaseRef = FirebaseDatabase.getInstance().getReference()
DatabaseReference userReference = databaseRef.child("users").child("6Z86LIYRMaM9vtmOrd23kAeICO63");
ValueEventListener userListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Create a User POJO class with the same values you have in your db
//and its getters and setters
User user = dataSnapshot.getValue(User.class);
//This is how you get the displayName from a user from the db
user.getDisplayName();
// ...
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
userReference.addValueEventListener(userListener);
I hope this helps

How to read specific value against particular key in Firebase?

My code is as show below:
mFirebaseDatabase = mFirebaseInstance.getReference();
mFirebaseDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
allText.setText(dataSnapshot.child("58ca237b2e2c211dc0c7ed9").child("order_status").getValue(String.class));
Log.d(TAG, "onDataChange: " + dataSnapshot.hasChild("58ca237b2e2c211dc0c7ed9"));
Log.d(TAG, "onDataChange: next " + dataSnapshot.getValue().equals("58ca237b2e2c211dc0c7ed9"));
for (DataSnapshot child : dataSnapshot.getChildren()) {
Log.d(TAG, "onDataChange for: " + child.toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "onCancelled: ");
}
});
The response that I am getting in log is as shown below:
onDataChange for: DataSnapshot { key = 58ca237b2e2c211dc0c7ed9, value = {order_status=2} }
Here, I want to read order_status=2, but I am unable to do it. How can I do that?
My firebase schema is as show below:
You can Send/Receive Data from FireBase following way:
Send data to FireBase
EmpInfo empInfo = new EmpInfo();
empInfo.setName(mEditTextName.getText().toString());
empInfo.setAge(mEditTextAge.getText().toString());
empInfo.setMobile(mEditTextMobileNo.getText().toString());
empInfo.setCity(autoCompleteTextView.getText().toString());
databaseReference.child("Emp_Info").setValue(empInfo);
Get Data from FireBase
databaseReference.child("Emp_Info").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG,"onDataChages invoked ="+dataSnapshot.toString());
//Getting the data from snapshot
EmpInfo empInfo = (EmpInfo)dataSnapshot.getValue(EmpInfo.class);
mTextName.setText(mTextName.getText()+" : "+empInfo.getName());
mTextAge.setText(mTextAge.getText()+" : "+empInfo.getAge());
mTextMobileNo.setText(mTextMobileNo.getText()+" : "+empInfo.getMobile());
mTextCity.setText(mTextCity.getText()+" : "+empInfo.getCity());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Model class
public class EmpInfo {
public String name;
public String age;
public String mobile;
public String city;
public EmpInfo(){
}
public EmpInfo(String name, String age, String mobile,String city) {
this.name = name;
this.age = age;
this.mobile = mobile;
this.city = city;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Hope It will help you !
Create Model of result that you are expecting and then simply do like this, you can manipulate the code that works for you
public static class Post {
public String author;
public String title;
public Post(String author, String title) {
this.author = author;
this.title = title;
}
//Default Constructor
public Post {
}
//Setter and Getter below
-----
// Get a reference to our posts
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("server/saving-
data/fireblog/posts");
// Attach a listener to read the data at our posts reference
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Post post = dataSnapshot.getValue(Post.class);
System.out.println(post.get(------));
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});

Categories

Resources