This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 3 years ago.
I am reading User class from database with this code :
mDatabase.orderByChild("name")
.equalTo(s1)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
User user = userSnapshot.getValue(User.class);
}
}
I want to display content of User object in a new activity. How do I pass User object to new activity?
Using Intent, you can share data between two activities.
In your case, you have to make user object parcelable.
Implement Parcelable interface in your user class.
Send the user object in intent like
intent.putExtra("user", userObject)
In your second activity get user object from intent :
User user = (User) getIntent().getExtras().getParcelable("user")
You Can Transfer Data Using Following Way:
Passing Data Through Intent(based on Key value or In Bundle Format)
Using Interface
Creating a Method in Another Activity and Call This method From First Activity (Using Public Method)
Related
HelloBelow is my database structure
I want to first get results from post object and using "userid" from that I want to get results from Users Object.
I want to update ViewModel with the above results that contain fields that are in both the objects
How to achieve this ?
I have written code to get the result from post object but how to again make call to get user object and update viewmodel and livedata object
private static final DatabaseReference POST_REF =
FirebaseDatabase.getInstance().getReference("/Post");
private final FirebaseQueryLiveData liveData = new
FirebaseQueryLiveData(POST_REF);
#NonNull
public LiveData<DataSnapshot> getDataSnapshotLiveData() {
return liveData;
}
There are different ways to model you database to archive this, It is always good to follow best practices see: https://firebase.google.com/docs/database/android/structure-data#best_practices_for_data_structure
In this case, since you only want the Profile Pic and name I would save it directly into the object:
{
"Posts":{
"post1":
{
"likes":23,
"userId":"id",
"user":
{
"imageUrl":"url",
"name":"Name"
}
}
}
}
Of course, the tradeoff is that the image URL won’t be updated if the user node gets updated (unless you code something to update it in a Cloud Function for example)
On the other hand, you could also perform those two calls to the Firebase Realtime Database (one to get the post, and the other to get the user data):
ValueEventListener postListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get Post object and use the values to update the UI
Post post = dataSnapshot.getValue(Post.class);
ValueEventListener userListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot userDataSnapshot) {
post.setUser(userDataSnapshot.getValue(User.class);)
}
};
mUserReference.addListenerForSingleValueEvent(userListener);//only fetch data once
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
};
mPostReference.addValueEventListener(postListener);
EDIT:
Having the user object inside the post would work using the architecture components (Just be sure to have the proper class to deserialize), on the other hand, since you are using the FirebaseQueryLiveData https://firebase.googleblog.com/2017/12/using-android-architecture-components.html and may want to avoid writing the user on that post node, I think you can have both ViewModels with different Database references, and once the data is fetched you could just update the post object e.g. post.setUser(user) with the user obtained from the other ViewModel Observer and then update the UI. You could also have a HashMap to keep track of what post needs what user, although this answer looks like a way to go: https://stackoverflow.com/a/46483213/1537389. Hope that helps
I have an existing array that I created locally and import to Firebase and my array looks like this.
These both elements are objects created that have some many information related to appointments.
Now i am trying to create a new element with the same form, for example:
2--
|__ And the object I have created in my app
I have only managed or eliminate the rest of the elements (with setValue(object))
Appointment newAppointment = new Appointment.Builder()
.fechacita(dateSelected)
.horacita(hourSelected)
.usertoken(mAuthManager.getCurrentUserId())
.oficina(centerSelected)
.build();
mDatabaseRef.child("LISTACITAS").setValue(newAppointment);
or create it with an ID that when recovering the data causes a crash in the application due to the deserialization of the objects that are not equal.
The Appointment object that I want to insert is
public class Appointment implements Parcelable {
private String fechacita;
private String horacita;
private Office oficina;
private String userID;
.....
}
The class is a normal Parcelable class that generates an object with her builder.
Please some help...
try this code
mDatabaseRef.push().setValue(incidentReportUser)
Write it this way (push() adds values instead of overriding).
Ans from here
UPDATE 1
if you want a series in key, not some random value, try this:
get the last key in the list using
Query dbQry = mDatabaseRef.orderByKey().limitToLast(1);
dbQry.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int key = Integer.parseInt(dataSnapshot.getKey());
//Increment the key and add the object here using the earlier method
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
}
I have not checked this as of now, but you could get the idea
This question already has answers here:
Passing custom objects between activities?
(5 answers)
Closed 5 years ago.
I want to send user define object from one activity to another in android application.
I have created user class object and send this user object to my second activity from first activity.
Implement your class with Serializable interface.
Then pass the object using
intent.putExtra("MyClass", obj);
and retrieve object by calling
getIntent().getSerializableExtra("MyClass");
See this post
Make sure your User class implements Parcelable.
public class User implements Parcelable {
...........
...............
}
Send User object to SecondActivity as below:
User userObject = new User();
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("user_data", userObject);
startActivity(intent);
Retrieving the User object in SecondActivity.
User user = (User) getIntent().getParcelableExtra("user_data");
Here is good Tutorial about using Parcelable.
Hope this will help~
Iplemented my user define class to Parcelable interface.
I have an application which uses Firebase as the data store. We are using Tier Pattern to separate our Business Logic(and data access logic) from the User Interface. This is what we were doing in other projects with other data stores.
As an example we want to read data from Firebase that is then set in a class called Stimmungsabfrage. Then we want to work with this data and to present it also in our controllers(textviews, listviews) in an activity (in our UI).
In our data access class we are using the following function to retrieve the data:
root.child(strKey).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
// Hier bekommst du dann letztlich die Stimmungsabfrage
StimmungAbfrage stimmungAbfrage = child.getValue(StimmungAbfrage.class);
}
}})
The problem with this function is that it does return void. So we are not able to return the retrieved object stimmungAbfrage to the user interface.
The only way is to assign the user interface controls right in this function, which we want to avoid, because we want to separate the UI from the data access logic.
How can this be done in Firebase?
Remove for loop:
for (DataSnapshot child : dataSnapshot.getChildren()){}
Simply write:
StimmungAbfrage stimmungAbfrage = child.getValue(StimmungAbfrage.class);
It will not return void.
I have the following data structure on firebase for the user MF0qeRA4p7djfjgXxqwFOck3m6p02. I want to get the value of item3 to populate a single field into the User interface on an Android App. I have been looking through samples on Stackoverflow, but all I have found are outdated and do not work with the current version of firebase. I'm new to firebase completely and this is my first app on android. I've got the oncreate user method to populate the users email address and add the 4 item fields, but retrieving the data I'm completely lost and I am not sure where to even begin.
-Users
---MF0qeRA4p7djfjgXxqwFOck3m6p02
------item1:"1"
------item2:"2"
------item3:"3"
------item4:"4"
According to what I can identify is, you are facing problem retrieving data from this reference. Here is the code:
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users");
databaseReference.child("MF0qeRA4p7djfjgXxqwFOck3m6p02").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, Object> map=(Map<String, Object>)dataSnapshot.getValue();
String item3=(String)map.get("item3");
display(item3);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Hope this helps.
You can create a custom model and inside you can insert elements. Something like this:
public class Item {
private List<Object> ojects;
}
There you can save instance of Item on database. In this case you have more controll. Other case is to use push() method, that will generate a new encoded key, something like this:
mDatabase.child("items").push().put(new Object());