I have a button which updates the int data value in database but I want to do an addition of a value to an existing integer data in Firebase Realtime Database not just by replacing it with another value.
The current integer value is 400 in the child of "points". I wanted to add a number to it and then update it.
For example, if I add 200, it will update the data inside the firebase and then display 600 there.
Would really appreciate if anyone can help me with this?
Main code:
Button btnDone;
DatabaseReference DBR;
int z = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tapcard);
btnDone = findViewById(R.id.buttonDone);
DBR = FirebaseDatabase.getInstance().getReference().child("Member");
btnDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DBR.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
int count = (int) dataSnapshot.getChildrenCount();
for (z = 1; z < count + 1; z++) {
DBR = FirebaseDatabase.getInstance().getReference().child("Member").child(String.valueOf(z));
DBR.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
dataSnapshot.getRef().child("points").setValue(100);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Intent i = new Intent(TapCardActivity.this, HomeActivity.class);
startActivity(i);
}
});
}
Rewards class:
public class RewardsClass implements Serializable {
private String Name;
private String Description;
private int img;
private int points;
public RewardsClass(String name, String description, int img, int points) {
Name = name;
Description = description;
this.img = img;
this.points = points;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public int getImg() {
return img;
}
public void setImg(int img) {
this.img = img;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
}
The easiest way to add a value to a property in the Realtime Database is by using the (pretty new) increment() operation.
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("Member").child(String.valueOf(z));
userRef.child("points").setValue(ServerValue.increment(200));
Also see:
How quickly can you atomically increment a value on the Firebase Realtime Database?
Related
I struggle to get data from Firebase for Android.
Please see my code.
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
Logger.log("onChildAdded:" + previousChildName);
// Logger.log( dataSnapshot.child("topicid").getValue(String.class));
//dataSnapshot.child("topicid").getValue();
mComment = new ArticleComment();
mComment = dataSnapshot.getValue(ArticleComment.class);
}
Here is ArticleComment class
public class ArticleComment {
private Date mCommentTime;
private String mComment;
private String mUID;
private String mName;
private int mColorRed;
private int mColorGreen;
private int mColorBlue;
public ArticleComment(){
}
public ArticleComment(Date time, String comment,String name,String uid,int[] color){
this.mCommentTime = time;
this.mComment = comment;
this.mName = name;
this.mUID = uid;
this.mColorRed=color[0];
this.mColorGreen=color[1];
this.mColorBlue=color[2];
}
public Date getTime(){
return mCommentTime;
}
public void setTime(Date time){
mCommentTime =time;
}
public String getComment(){
return mComment;
}
public void setComment(String comment){
mComment =comment;
}
public String getName(){
return mName;
}
public void setName(String name){
mName=name;
}
public String getUID(){
return mUID;
}
public void setUID(String uid){
mUID=uid;
}
public int getColorRed(){
return mColorRed;
}
public int getColorGreen(){
return mColorGreen;
}
public int getColorBlue(){
return mColorBlue;
}
public void setColor(int red,int green, int blue)
{
mColorRed=red;
mColorGreen=green;
mColorBlue=blue;
}
#Exclude
public Map<String, Object> toMap(){
HashMap<String, Object> hashmap = new HashMap<>();
hashmap.put("time", mCommentTime);
hashmap.put("UID", mUID);
hashmap.put("name", mName);
hashmap.put("comment", mComment);
hashmap.put("colorRed", mColorRed);
hashmap.put("colorBlue", mColorBlue);
hashmap.put("colorGreen", mColorGreen);
return hashmap;
}
}
And here is my DB information.
I could get only
mCommentTime;
mComment;
mName;
But I can't get
mUID;
mColorRed;
mColorGreen;
mColorBlue;
Is there something wrong with my code?
Actually datasnapshot has data but it didn't copy to mComment
Hi! Thank you, friends, gave me feedback here is all code.
public class CommentsActivity extends AppCompatActivity {
private DatabaseReference myRef;
private DatabaseReference mTopicRef;
private RecyclerView mRecyclerView;
private RecyclerArticleAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private List<ArticleComment> myDataset = new ArrayList<ArticleComment>();
private ArticleComment mComment;
private Topic mTopic;
private EditText mTitleEditText;
private String mUserName;
private String mUid;
private int mRedColor=100;
private int mBlueColor=100;
private int mGreenolor=100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comments);
//Add action button
Intent intent =getIntent();
String id = intent.getStringExtra("ID");
String date = intent.getStringExtra("Date");
String title = intent.getStringExtra("Title");
String topic = intent.getStringExtra("Topic");
mUserName = intent.getStringExtra("UserName");
mUid = intent.getStringExtra("UID");
SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(this);
mRedColor= pref.getInt("ColorRed",255);
mGreenolor=pref.getInt("ColorGreen",255);
mBlueColor=pref.getInt("ColorBlue",255);
mRecyclerView = findViewById(R.id.recyclerView_article);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
//Reference DB
FirebaseDatabase database = FirebaseDatabase.getInstance();
myRef = database.getReference("Main").child("Comments").child(id);
mTopicRef = database.getReference("Main").child("Topics").child(id);
List<String> topicinfo=new ArrayList<String >();
topicinfo.add(date);
topicinfo.add(title);
topicinfo.add(topic);
// Set TestAdapter as the adapter for RecyclerView.
mRecyclerView.setAdapter(mAdapter);
mAdapter = new RecyclerArticleAdapter(myDataset,topicinfo){
/* #Override
protected void onCheckedChangedRecycle(CompoundButton comButton, final boolean isChecked){
mTopicRef.runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
Topic t = mutableData.getValue(Topic.class);
String id = mutableData.child("topicid").getValue(String.class);
t.setTopicID(id);
if (t == null) {
return Transaction.success(mutableData);
}
if (isChecked==true) {
// Unstar the post and remove self from stars
t.setRate(t.getRate()+1);
} else {
// Star the post and add self to stars
t.setRate(t.getRate()-1);
}
// Set value and report transaction success
mutableData.setValue(t);
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b,
DataSnapshot dataSnapshot) {
// Transaction completed
}
});
} */
};
mRecyclerView.setAdapter(mAdapter);
findViewById(R.id.button2).setOnClickListener(button1ClickListener);
mTitleEditText = findViewById(R.id.editText2);
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
mComment = new ArticleComment();
mComment = dataSnapshot.getValue(ArticleComment.class);
Logger.log("onChildAdded:addItem" + previousChildName);
mAdapter.addItem(mAdapter.getItemCount()-1, mComment);
Logger.log("onChildAdded:scrollToPosition" + previousChildName);
mAdapter.updateItem(mAdapter.getItemCount()-1,mComment);
mLayoutManager.scrollToPosition(mAdapter.getItemCount()-1);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
myRef.addChildEventListener(childEventListener);
}
View.OnClickListener button1ClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// finish();
Logger.log("onClick");
if(mTitleEditText.getText().toString().equals("")){
return;
}
//setting color
int color[]=new int[3];
color[0]= mRedColor;
color[1]=mGreenolor;
color[2]=mBlueColor;
mComment = new ArticleComment(new Date(),mTitleEditText.getText().toString(),mUserName,mUid,color);
sendTopic(mComment,myRef);
//Delete all text
mTitleEditText.setText("");
}
};
// Sending topic to DB
public void sendTopic(ArticleComment test,DatabaseReference ref) {
String key = ref.push().getKey();
Map<String, Object> map = new HashMap<>();
map.put(key, test.toMap());
ref.updateChildren(map);
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
finish();
return true;
}
return true;
}
Is it enough information?
Firebase follows JavaBean naming conventions to determine the name of the JSON property from the Java code. And in that convention getUID and setUID map to a property uID with a lowercase u.
To make the Firebase client adopt your naming convention, annotate the getter and setter with a #PropertyName:
#PropertyName("UID")
public String getUID(){
return mUID;
}
#PropertyName("UID")
public void setUID(String uid){
mUID=uid;
}
I'm not immediately sure why the other properties don't work. When this happens, I find it most useful to write an object of the type of Firebase, to see what it generates.
**
If you want to store values in a model .Then your variable name should
be same as Firebase node or else you need to typeConvert it .
**
private Date mCommentTime;
private String mComment;
private String mUID;
private String mName;
private int mColorRed;
private int mColorGreen;
private int mColorBlue;
Replace above with
private int time;
private String comment;
private String UID;
private String name;
private int colorRed;
private int colorBlue;
private int colorGreen;
now make getters,setters,constructor etc. using above nodes. (Now you will be able to get all the values ) .
Hope its gonna help you :)
JSON Image Link
i want to get all the images from my firebase database with this code
FirebaseDatabase mFirebaseInstance = FirebaseDatabase.getInstance();
mFirebaseInstance.getReference("actors").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To solve this, you need to loop through the DataSnapshot object using getChildren() method. So please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("actors").orderByChild("image");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String image = ds.child("image").getValue(String.class);
Log.d(TAG, image);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
query.addListenerForSingleValueEvent(valueEventListener);
The output in your logcat, will be all the image urls.
You can better use addListenerForSingleValueEvent instead of addValueEventListener as it will be called once so it will be very helpful, please try below code
ArrayList<String> arr_imageList = new ArrayList<>();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
reference.child("actors").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
arr_imageList.clear();
if (dataSnapshot.exists()) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
ActorsModel actorsModel = dataSnapshot1.getValue(ActorsModel.class);
if (actorsModel != null && actorsModel.getImage() != null) {
arr_imageList.add(actorsModel.getImage());
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
and please add model class for ActorsModel which is below
public class ActorsModel implements Serializable {
private String children;
private String country;
private String description;
private String dob;
private String height;
private String image;
private String name;
private String spouse;
public ActorsModel() {
}
public ActorsModel(String children, String country, String description, String dob, String height, String image, String name, String spouse) {
this.children = children;
this.country = country;
this.description = description;
this.dob = dob;
this.height = height;
this.image = image;
this.name = name;
this.spouse = spouse;
}
public String getChildren() {
return children;
}
public void setChildren(String children) {
this.children = children;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSpouse() {
return spouse;
}
public void setSpouse(String spouse) {
this.spouse = spouse;
}
}
Fetching Data:
private void fetchResults() {
mDatabaseReference.child("Users").child(id).child("Quiz").child("Results").child(id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot resultSnapshot: dataSnapshot.getChildren()) {
String user = resultSnapshot.getKey();
String score = resultSnapshot.getValue(String.class);
Results results = new Results(user, score);
resultsList.add(results);
}
mAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
Saving Data:
String name = RecieversName;
HashMap<String, String> userMap = new HashMap<>();
userMap.put(name, String.valueOf(mScore));
mRef.child("Users").child(RecieversId).child("Quiz").child("Results").child(UID).setValue(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Intent intent = new Intent(TakingQuiz.this, TakingQuizDone.class);
intent.putExtra("RecieversId",RecieversId);
intent.putExtra("Score", mScore.toString());
startActivity(intent);
finish();
}
}
});
Adapter:
public class AdapterQuiz extends RecyclerView.Adapter<AdapterQuiz.ResultViewHolder>{
private FirebaseAuth mAuth;
private List<Results> mResultsList;
public AdapterQuiz(List<Results>mResultsList)
{
this.mResultsList = mResultsList;
}
public class ResultViewHolder extends RecyclerView.ViewHolder{
public TextView name;
public TextView score;
public ResultViewHolder(View view)
{
super(view);
name = (TextView)view.findViewById(R.id.name);
score = (TextView)view.findViewById(R.id.score);
}
}
#Override
public ResultViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View V = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_activity_results,parent,false);
mAuth = FirebaseAuth.getInstance();
return new ResultViewHolder(V);
}
#Override
public void onBindViewHolder(ResultViewHolder holder, int position) {
Results results = mResultsList.get(position);
holder.name.setText(results.getName());
holder.score.setText(results.getScore());
}
#Override
public int getItemCount() {
return mResultsList.size();
}
}
Results Class
public class Results {
private String Name;
private String Score;
public Results() {
}
public Results(String Name, String Score) {
this.Name = Name;
this.Score = Score;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getScore() {
return Score;
}
public void setScore(String score) {
Score = score;
}
}
I have worked quite sometime on RecyclerView and Firebase but usually I would display a constant 'name' and a variable 'value' but here both name and variable is not decided by me... when the user finishes the quiz and his score will be displayed in the recyclerview but its just showing blank without any error... I'm not sure if this is the right way of fetching this kind of data... can anyone help me out please
Database - https://ibb.co/eMWkFJ
Results results;
String name, score;
private void fetchResults() {
mDatabaseReference.child("Users").child(id).child("Quiz").child("Results").child(id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
name = childDataSnapshot.getKey().toString();
score = childDataSnapshot.child(name).getValue());
results = new Results(user, score);
resultsList.add(results);
mAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
I hope this will do your job.
To solve this, you first need to set the adapter before notifying it for changes. So please use the following line of code:
mRecyclerView.setAdapter(mAdapter);
Instead of this:
mAdapter.notifyDataSetChanged();
This last line of code should be used only when some changes take place in your database and in order to notify the adapter, this must be set in the fist place.
I have a Firebase databse structure like this :
the firebase database structure
Now I want to access the items in the node "comingSoonPages" to a model class. How can i get the reference to these different user specified items in that node?
The database reference :
mUpcomingDatabaseReference = mFirebaseDatabase.getReference().child("comingSoonPages").child("blrKoramangala")
now the listener to the reference is as :
mValueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapShot : dataSnapshot.getChildren()){
Log.e("snap" , String.valueOf(snapShot));
try{
UpcomingProperty property = snapShot.getValue(UpcomingProperty.class);
Log.e("name" , String.valueOf(property.getName()));
}catch (Exception ex){
ex.printStackTrace();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mUpcomingDatabaseReference.addValueEventListener(mValueEventListener);
when i try to log the names in each of the nodes , i get NPE and the value is null.
The model class in which i am mapping is :
public class UpcomingProperty implements Serializable {
//private Amenities amenities;
private List<String> amenities;
private Coordinates coordinates;
private Image image;
private String link;
private String location;
private String name;
private Text text;
private List<String> sortParameter;
private EarlyBird earlyBird;
public UpcomingProperty(){}
public List<String> getAmenities() {
return amenities;
}
public void setAmenities(List<String> amenities) {
this.amenities = amenities;
}
public Coordinates getCoordinates() {
return coordinates;
}
public void setCoordinates(Coordinates coordinates) {
this.coordinates = coordinates;
}
public Image getImage() {
return image;
}
public void setImage(Image image) {
this.image = image;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Text getText() {
return text;
}
public void setText(Text text) {
this.text = text;
}
public List<String> getSortParameter() {
return sortParameter;
}
public void setSortParameter(List<String> sortParameter) {
this.sortParameter = sortParameter;
}
public EarlyBird getEarlyBird() {
return earlyBird;
}
public void setEarlyBird(EarlyBird earlyBird) {
this.earlyBird = earlyBird;
}
}
Thanks.
the extended firebase node :
extended node values
To get that data, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference comingSoonPagesRef = rootRef.child("comingSoonPages");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.child("name").getValue(String.class);
Log.d("TAG", name);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
comingSoonPagesRef.addListenerForSingleValueEvent(eventListener);
The out will be the only the names. But you can get also all the other values in the same way.
If you want to use the model class, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference comingSoonPagesRef = rootRef.child("comingSoonPages");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
UpcomingProperty upcomingProperty = ds.getValue(UpcomingProperty.class);
Log.d("TAG", upcomingProperty.getName());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
comingSoonPagesRef.addListenerForSingleValueEvent(eventListener);
You'll have the same output.
Assuming that comingSoonPages holds a list of item, You need to add a ChildEventListener on the comingSoonPages reference if you want to access all the child nodes of that.
DatabaseReference upcomingItemsRef = mFirebaseDatabase.getReference().child("comingSoonPages");
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
if(dataSnapshot.exists()) {
// Handle each individual node like blrKoramangala, cyberHub here.
String key = dataSnapshot.getKey();
// Get the UpcomingProperty object here.
UpcomingProperty property = dataSnapshot.getValue(UpcomingProperty.class);
Log.d(TAG, "property.getName():" + property.getName();
}
}
// Other methods of ChildEventListener go here
};
upcomingItemsRef.addChildEventListener(childEventListener);
You can read more about working with lists of data here.
However, if that's not a list, here's what you're doing wrong:
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Don't do this. It will get the children of blrKoramangala and
// those won't be of UpcomingProperty type.
// Remove and replace with dataSnapshot.exists()
for (DataSnapshot snapShot : dataSnapshot.getChildren()){
...
}
}
Error log:
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.netgalaxystudios.timeclock.Subscription
at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
at com.mypackage.appname.RegisterSubscriptionActivity$1.onDataChange(RegisterSubscriptionActivity.java:81)
Points to :
Subscription subscription = child.getValue(Subscription.class);
Firebase DB:
I followed the tutorials and this seems to be exactly how they structure it, so not sure why it doesnt like me converting to my class?
RegisterSubscriptionActivity.java:
public class RegisterSubscriptionActivity extends Activity {
//Firebase Database References
DatabaseReference mDatabase;
DatabaseReference mDatabaseMicro;
DatabaseReference mDatabaseSmall;
DatabaseReference mDatabaseMedium;
DatabaseReference mDatabaseLarge;
DatabaseReference mDatabaseEnterprise;
DatabaseReference mListItemRef;
ArrayList subscriptionInfo;
ArrayList<Subscription> myListItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_subscription);
myListItems = new ArrayList<Subscription>();
mDatabase = FirebaseDatabase.getInstance().getReference("Subscription");
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> children = dataSnapshot.getChildren();
for(DataSnapshot child : children) {
Subscription subscription = child.getValue(Subscription.class);
myListItems.add(subscription);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d("Cancelled",databaseError.toString());
}
});
Log.i("LIST OF DATA: ", myListItems.toString());
}
}
Subscription.java:
public class Subscription {
String name, number, price;
public Subscription() {}
public Subscription(String name, String number, String price) {
this.name = name;
this.number = number;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put("NAME", name);
result.put("NUMBER", number);
result.put("PRICE", price);
return result;
}
}
To get the values of name, number and price, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference yourRef = rootRef.child("Subscription").child("Micro");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("name").getValue(String.class);
String number = dataSnapshot.child("number").getValue(String.class);
String price = dataSnapshot.child("price").getValue(String.class);
Log.d("TAG", name + " / " + price + " / " + price);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
yourRef.addListenerForSingleValueEvent(eventListener);