using Map to get object of custom class - android

I'm new at using maps, how can we get object of custom Class from Map..
i.e.
feedSendModelClass:
public class feedSendModelClass {
private String content;
private String picThumbnail;
private String picurl;
private String videourl;
private String videoThumbnail;
private String mTime;
public feedSendModelClass() {
//blank for firebase
}
public String getTime() {
return mTime;
}
public void setTime(String time) {
mTime = time;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getVideoThumbnail() {
return videoThumbnail;
}
public void setVideoThumbnail(String videoThumbnail) {
this.videoThumbnail = videoThumbnail;
}
public String getVideourl() {
return videourl;
}
public void setVideourl(String videourl) {
this.videourl = videourl;
}
public String getPicurl() {
return picurl;
}
public void setPicurl(String picurl) {
this.picurl = picurl;
}
public String getPicThumbnail() {
return picThumbnail;
}
public void setPicThumbnail(String picThumbnail) {
this.picThumbnail = picThumbnail;
}
}
Map
Map<String, feedSendModelClass> feedKeys = (Map<String,feedSendModelClass>) dataSnapshot.getValue();
Datasnapshot:
DataSnapshot { key = feedsMetaPool, value = {20160708155218759={content=bzzzhss, picurl=https://firebasestorage.googleapis.com/v0/b/rootssahaj.appspot.com/o/feedsImages%2FnonThumbs%2F201607081552353353553518759sahaj9917730102?alt=media&token=ce1c6e7c-28c5-442e-9405-4468bf5fc204, time=08 Jul, picThumbnail=https://firebasestorage.googleapis.com/v0/b/rootssahaj.appspot.com/o/feedsImages%2Fthumbs%2F20353353535355353160708155218759sahaj9917730102?alt=media&token=14d33963-f3da-4407-a08f-ab0afce21ace}, 20160708164100152={content=sj sjs skss sksssvsjm, picurl=https://firebasestorage.googleapis.com/v0/b/rootssahaj.appspot.com/o/feedsImages%2FnonThumbs%2F201607081641003535152sahaj9917730102?alt=media&token=323c4a27-1850-4bc9-adea-34e5319ac506, time=08 Jul, picThumbnail=https://firebasestorage.googleapis.com/v0/b/rootssahaj.appspot.com/o/feedsImages%2Fthumbs%2F20160708164100152sahaj9917730102?alt=media&token=0b064b46-2f14-49af-b3e6-7a573f6c2d3f}, 20160708142314069={content=dadax, picurl=https://firebasestorage.googleapis.com/v0/b/rootssahaj.appspot.com/o/feedsImages%2FnonThumbs%2F2016070rdgdg54353535358142314069sahaj9917730102?alt=media&token=19d03f11-d12f-43c1-96f5-ca397a9179c9, time=08 Jul, picThumbnail=https://firebasestorage.googleapis.com/v0/b/rootssahaj.appspot.com/o/feedsImages%2Fthumbs%2F20160735353508142314069sahaj9917730102?alt=media&token=ab9c73eb-ec44-46ae-9daa-6fc508cb08a6} }
This has become tricky for me..Thanks..
There could be some other way round to do it through firebase

If you are asking how you retrieve the feedSendModelClass object from the map named feedKeys, then this syntax should work:
feedKeys.get(key)
The key is your String, and the object is the feedSendModelClass object. However, first you'd need to put key and value pairs into the map (so it's not empty), with feedKeys.put(key, value), where the key is a String and value is the feedSendModelClass.
If this totally doesn't answer your question, I apologize, but from your description, it is a bit difficult to understand what you need help with.
On an unrelated note, it would be more appropriate to name your class FeedSendModelClass, as per Java conventions classes start with a capital letter.

If you're using Firebase then you can use a ChildEventListener. It calls the onChildAdded() method once for every initial child in the node and everytime a new child is added. Then you can add the Object to an ArrayList directly (or do whatever you want with it)
ArrayList<feedSendModelClass> feedKeysArrayList = new ArrayList<>();
DatabaseReference feedKeysRef = FirebaseDatabase.getInstance().getReference("path/to/the/feedkeys");
feedKeysRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
feedKeysArrayList.add(dataSnapshot.getValue(feedSendModelClass.class));
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
// Add appropriate code
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
// Add appropriate code
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
// Add appropriate code
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Add appropriate code
}
});

Related

How to increment value in Firebase database android

Hopefully someone can help me with this. Lets say I have a post and I want to track down the number of clicks it gets. How do I go about incrementing the value in the database (Firebase). For example the post has one click that count as 1 then it has another click that counts as 2 then so on and so fourth. I tried doing something but I'm getting this error. I really need your help on this. Thanks in advance
Error message
Can't convert object of type java.lang.Long to type com.myapp.poopy.Model_Information
My code
databaseReference = FirebaseDatabase.getInstance("https://poopy-43981.firebaseio.com/").getReference().child("Post").child(getid);
int count;
count = count ++;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
databaseReference.child("clicks").setValue(count+1);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
Json
{
"Post" : {
"lG71ennq86UIZ5a5Oqh8oaYAXe03" : {
"-MHNWmVK3rBnvnr0qcph" : {
"clicks" : 0,
"id" : "-MHNWmVK3rBnvnr0qcph",
}
}
},
Model_class
public Model_Information(String category, String headline, String mImageUrl,String created,String time,String id,String status ) {
this.mImageUrl = mImageUrl;
this.category = category;
this.headline = headline;
this.created=created;
this.time=time;
this.id=id;
this.status=status;
}
public Model_Information() {
}
public String getstatus() {
return status;
}
public void setstatus(String status) {
status = status;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
public String getmImageUrl() {
return mImageUrl;
}
public void setmImageUrl(String mImageUrl) {
this.mImageUrl = mImageUrl;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getHeadline() {
return headline;
}
public void setHeadline(String headline) {
this.headline = headline;
}
//Class using model class
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String previousChildName) {
if (dataSnapshot.exists()) {
progressBar.setVisibility(View.GONE);
for (DataSnapshot postsnapshot : dataSnapshot.getChildren()) {
myUploads.clear();
Model_Information upload = postsnapshot.getValue(Model_Information.class);
myUploads.add(upload);
aAdapter = new Adapter(MainActivity2.this, myUploads);
recyclerView.setAdapter(aAdapter);
aAdapter.notifyDataSetChanged();
recyclerView.invalidate();
}
}
}
To be able to update the clicks value you need to know the complete path to that value. In your use-case there seem to be two variables in that path:
the UID
a push ID
Once you know both values, increment the value can be done with the (relatively new) ServerValue.increment operation like this:
DatabaseReference rootReference = FirebaseDatabase.getInstance("https://poopy-43981.firebaseio.com/");
DatabaseReference userReference = rootReference.child("Post").child(getid);
DatabaseReference countReference = userReference.child("-MHNWmVK3rBnvnr0qcph").child("clicks");
countReference.setValue(ServerValue.increment(1));

get right data for specific user from Firebase

I have a chat app and I'm trying to pull down the chat groups that the logged in user is part of. I'm struggling to get down the right groups. Here is my firebase structure. All the members are under the "members" child inside a group. I'm displaying the groups in a recyclerview that works fine. This has of course work for any user that logs in and a user can be part of many different groups. I hope you get the idea and can help me. Thanks
My code:
private FirebaseDatabase mDatabase;
private DatabaseReference mDatabaseReference;
private FirebaseAuth mAuth;
private FirebaseUser mUser;
private String projectId;
private List<DataService> grouplist;
private RecyclerAdapter recyclerAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser();
mDatabaseReference = mDatabase.getReference().child("groups");
mDatabase = FirebaseDatabase.getInstance();
mDatabaseReference.keepSynced(true);
grouplist = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
protected void onStart() {
super.onStart();
grouplist.clear();
mDatabaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
DataService groupData = dataSnapshot.getValue(DataService.class);
grouplist.add(groupData);
recyclerAdapter = new RecyclerAdapter(Main.this, grouplist);
recyclerView.setAdapter(recyclerAdapter);
recyclerAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
DataService.java
public class DataService {
public String subject;
public String projectName;
public String endDate;
public String members;
public String userid;
public String creationDate;
public String dropbox;
public String evernote;
public String googleDocs;
public DataService() {
}
public DataService(String subject, String projectName, String endDate, String members, String userid, String creationDate, String dropbox, String evernote, String googleDocs) {
this.subject = subject;
this.projectName = projectName;
this.endDate = endDate;
this.members = members;
this.userid = userid;
this.creationDate = creationDate;
this.dropbox = dropbox;
this.evernote = evernote;
this.googleDocs = googleDocs;
}
public String getCreationDate() {
return creationDate;
}
public void setCreationDate(String creationDate) {
this.creationDate = creationDate;
}
public String getDropbox() {
return dropbox;
}
public void setDropbox(String dropbox) {
this.dropbox = dropbox;
}
public String getEvernote() {
return evernote;
}
public void setEvernote(String evernote) {
this.evernote = evernote;
}
public String getGoogleDocs() {
return googleDocs;
}
public void setGoogleDocs(String googleDocs) {
this.googleDocs = googleDocs;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public String getmembers() {
return members;
}
public void setmembers(String members) {
this.members = members;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
}
Using the actual database structure, you cannot get all the groups a user is in, unless you make some changes to your database. In your case, you should consider augmenting your database structure to allow a reverse lookup by creating another node, named groups under each user object, in which you should add all the group ids from which the user is appart of. So your database structure should look like this:
Firebase-root
|
--- users
|
--- userId
|
--- groups
|
--- groupIdOne: true
|
--- groupIdTwo: true
To get all the groups a user is appart, just attach a listener on the groups node and there are all the groups that you need.
But you'll be thinking, why to do this? Why to duplicate data? Well, there is no problem with duplicating data, when it comes to Firebase. This is a quite common practice, which is named denormalization and for that, I recommend you see this video, Denormalization is normal with the Firebase Database.
When you are duplicating data, there is one thing that need to keep in mind. In the same way you are adding data, you need to maintain it. With other words, if you want to update/detele an item, you need to do it in every place that it exists.

Method to find object by ID with firebase in Android

Well, I want to create this method, but since you're not able to return from listener's methods, I just can't figure it out a way to give the user when firebase finds it:
public static User findByID(#NonNegative final int id) {
getDatabase().orderByChild("id")
.equalTo(id)
.limitToFirst(1)
.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
dataSnapshot.getValue(User.class); // this one must be returned
}
#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) {}
});
}
Creating a variable to receive value and return doesn't work as well, since firebase takes a bit long to find the user.
Data retrieval is asynchronous in Firebase, so you cannot return. I think there are two ways to overcome the problem you are facing.
First Way
If data should be returned somewhere in the same class in which findById() exists, then you can do as follows:
class A {
private TextView nameTextView;
...
public void findById(#NonNegative int id) {
userRef().orderByChild("id")
.equalTo(id)
.limitToFirst(1)
.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
User user = dataSnapshot.getValue(User.class);
onUserRetrieved(user);
}
...
});
}
private void onUserRetrived(User user) {
// Now you can do whatever you want with the "user"
// For instance, update name field in the layout...
nameTextView.setText(user.getName);
...
}
}
Second Way
If you need to notify an instance of another class, you can pass a listener to the function as parameter and then call a method in that listener as a way of notifying the caller. An example caller would look like as follows:
class Caller {
...
private void someFunction() {
...
String userId = 1; // Get user id somehow
DatabaseUtil.findUserById(userId, new DatabaseUtil.Listener() {
#Override
public void onUserRetrieved(User user) {
// Now you can do whatever you want with the "user"
}
});
...
}
}
whereas your static function may reside in a class as follows:
class DatabaseUtil {
public static void findUserById(#NonNegative int id, Listener listener) {
FirebaseDatabase.getInstance().getreference("user")
.orderByChild("id")
.equalTo(id)
.limitToFirst(1)
.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
User user = dataSnapshot.getValue(User.class);
listener.onUserRetrieved(user);
}
...
});
}
interface Listener {
void onUserRetrieved(User user);
}
}

Fetch data from firebase in Android

Not able to fetch the data it gives "Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()".Not Able to find any solution please help.
The Code is
public class AdminUser extends AppCompatActivity {
private TextView tv1,tv2;
private DatabaseReference mDatabase;
private FirebaseAuth auth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_user);
auth = FirebaseAuth.getInstance();
String username=FirebaseAuth.getInstance().getCurrentUser().getUid();
mDatabase= FirebaseDatabase.getInstance().getReference().child(username);
tv1=(TextView)findViewById(R.id.textView6);
tv2=(TextView)findViewById(R.id.textView8);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// String name=dataSnapshot.getValue().toString();
String name=dataSnapshot.child("name").getValue(String.class).toString() ;
String address=dataSnapshot.child("address").getValue(String.class).toString();
tv1.setText(name);
tv2.setText(address);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
This 2 lines:
String name=dataSnapshot.child("name").getValue(String.class).toString() ;
String address=dataSnapshot.child("address").getValue(String.class).toString();
are causing your problem, go to the Firebase documentation and read about how to read data from the realtime database here
https://firebase.google.com/docs/database/android/read-and-write
Edit
To give you an example specific to your question, first you need to create a Plain Old Java Object (POJO) class that represent the data you have in your database, for example.
public class User {
private String name;
private String address;
public User() {
//Empty constructor required by firebase
// serialize the data retrieved and convert
// it to an object of this class
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Then in your valueEventListener you can do something like this
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Serialize your retrieved data to a User object
User user = dataSnapshot.getValue(User.class);
//Now you have an object of the User class and can use its getters like this
tv1.setText(user.getName());
tv2.setText(user.getAddress());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Hope this helps

Child List from Firebase with android

I'm trying to get the value of my firebase tree
I got a class get_categories
public class get_categories {
private String Name;
public get_categories(){
}
public String getName(){
return Name;
}
}
Then I declared the firebase
mRef = new Firebase("https://...../Users/Categories");
And try to retrieve my data with OnChildEventListener
mRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.e("Count " ,""+dataSnapshot.getChildrenCount());
//Log.e("VALUES " ,""+dataSnapshot.child("Details").getValue());
get_categories getCatName = dataSnapshot.child("Details").getValue(get_categories.class);
Log.e("NAME " ,""+getCatName.getName());
}
#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(FirebaseError firebaseError) {
}
});
But I got an error
Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "Name" (class com.app.pierre.myapp.get_categories), not marked as ignorable (0 known properties: ]) at [Source: java.io.StringReader#9d0f705; line: 1, column: 10] (through reference chain: com.app.pierre.myapp.get_categories["Name"])
What am I doing wrong ?
I used this case as reference:
https://www.firebase.com/docs/android/guide/retrieving-data.html
Well first change your Model like this,
public class GetCategories {
private String Name;
public GetCategories(){
}
public GetCategories(String name){
this.Name = name;
}
public String getName(){
return Name;
}
}
and Push data using Model class Constructor..
GetCategories model = new GetCategories("yourValues");
mReference.child("Details").push().setValue(model);
and Now you can get it like this way..
mRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
for (DataSnapshot eventSnapshot : dataSnapshot.getChildren()) {
GetCategories newPost = eventSnapshot.getValue(GetCategories.class);
Log.e("NAME " ,""+ newPost.getName());
}
}
#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(FirebaseError firebaseError) {
}
});
The name of the property on your JSON starts with an uppercase letter. But by the rules of JavaBean properties, getName() correspond to a property called name (with a lowercase n). So the two don't match up.
One way to get this working is to not use a setter, but instead use a public field:
public class get_categories {
public String Name;
}
With this you're bypassing the JavaBean logic and get a direct mapping.

Categories

Resources