Retrieve Only 5 Users At a Time :Firebase [Like Instagram]

Retrieve only 5 users at a time :Firebase [like Instagram]

If you are using tableView update your DataSource instead of adding a row at a particular index. using struct is a common aproach.

struct dataS {

var postData : String!
var index_Initial : Int!

init(post : String!, ind : Int!)
{
self.postData = post
self.index_Initial = ind
}

}
  • Declare an array of type dataSourceS

         var dataFeed= [dataS]()
  • For knowing that how many posts you have already retrived , you need to keep the index of each post in the the post node itself.Which can be done by counting the no of children in the post node and incrementing it by one.Or creating a complete separate node of

    noOfPosts: 100, //Lets say there are 100 posts in your DB 

    Posts : {
    Post1:{


    text : asdasdasd,
    index : 12

    },

    Post2:{


    text : asdasddasdasd,
    index : 13

    },.....
    }

Your final code will look something like this:-

 import UIKit
import Firebase

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var dataFeed = [dataS]()
let pagingSpinner = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
var totalNoOfPost : Int!



@IBOutlet weak var customTableView: UITableView!




override func viewDidLoad() {
super.viewDidLoad()

customTableView.delegate = self
customTableView.dataSource = self
}

override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)

FIRDatabase.database().reference().child("Posts").observeSingleEventOfType(.Value, withBlock: {(snap) in

if let postDict = snap.value as? [String:AnyObject]{

self.totalNoOfPost = postDict.count

self.loadMore()
}
})

}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataFeed.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = customTableView.dequeueReusableCellWithIdentifier("customCell") as! customTableViewCell
if dataFeed.count > 0{
cell.poatLabel.text = dataFeed[indexPath.row].postData
}
return cell
}

func loadMore(){

let initialFeedCount : Int = dataFeed.count

if totalNoOfPost - initialFeedCount - 4 > 0{

FIRDatabase.database().reference().child("Posts").queryOrderedByChild("index").queryStartingAtValue(totalNoOfPost - initialFeedCount - 4).queryEndingAtValue(totalNoOfPost - initialFeedCount).observeEventType(.Value, withBlock: {(recievedSnap) in

if recievedSnap.exists(){

for each in recievedSnap.value as! [String:AnyObject]{
let temp = dataS.init(post: each.1["text"] as! String, ind : each.1["index"] as! Int)
self.dataFeed.insert(temp, atIndex: 5 * Int(self.dataFeed.count/5))
self.dataFeed.sortInPlace({$0.index_Initial > $1.index_Initial})
if self.dataFeed.count == initialFeedCount+5{
self.dataFeed.sortInPlace({$0.index_Initial > $1.index_Initial})
self.customTableView.reloadData()

}
}

}
}, withCancelBlock: {(err) in

print(err.localizedDescription)


})

}else if totalNoOfPost - initialFeedCount - 4 <= 0{


FIRDatabase.database().reference().child("Posts").queryOrderedByChild("index").queryStartingAtValue(0).queryEndingAtValue(totalNoOfPost - initialFeedCount).observeEventType(.Value, withBlock: {(recievedSnap) in

if recievedSnap.exists(){

for each in recievedSnap.value as! [String:AnyObject]{

let temp = dataS.init(post: each.1["text"] as! String, ind : each.1["index"] as! Int)

self.dataFeed.insert(temp, atIndex: 5 * Int(self.dataFeed.count/5))
self.dataFeed.sortInPlace({$0.index_Initial > $1.index_Initial})
if self.dataFeed.count == initialFeedCount+4{
self.dataFeed.sortInPlace({$0.index_Initial > $1.index_Initial})
self.customTableView.reloadData()
self.pagingSpinner.stopAnimating()
}
}
}else{

self.pagingSpinner.stopAnimating()
}

}, withCancelBlock: {(err) in

print(err.localizedDescription)


})
}
}

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if (indexPath.row + 1) == dataFeed.count {
print("Displayed the last row!")


pagingSpinner.startAnimating()
pagingSpinner.hidesWhenStopped = true
pagingSpinner.sizeToFit()
customTableView.tableFooterView = pagingSpinner
loadMore()
}
}


}


struct dataS {

var postData : String!
var index_Initial : Int!

init(post : String!, ind : Int!)
{
self.postData = post
self.index_Initial = ind
}

}

How to get the count of total likes from all posts which are posted by one user in android firebase?

Go to databaseReference.child("Posts") and loop through all the posts, find those whose uid child matches the desired user, and keep that subset of post IDs, say in an ArrayList, postsOfTheUser.

Next, go to databaseReference.child("Likes") and loop through all the likes. Ignore all children whose post ID is not in postsOfTheUser, but those whose post ID is in postsOfTheUser, proceed to sum the likes, using getChildrenCount() for each of the posts.

Return only needed values from Firebase

Sorry, there is no machanism in Firebase to query by a list, you'd need to run through the list and query each element, which is very inefficient. What I recommend is: as you're already bringing all elements from the "Users" node, store them in a secondary data structure and filter that.

 for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Users user = snapshot.getValue(Users.class);
assert user != null;
String contact_found = user.getPhone_number();
mContactsFromFirebase.add(user);//this data structure now takes users

}



private List<User> findSignedUpContacts(Map<String, String> contactsStored, List<User> firebaseUsers) {

List<User> values = new ArrayList<>();
for (User user : firebaseUsers) {
if(contactsStored.containsKey(user.getPhone_number())
{
values.add(user);
}
}
return values;
}

Now values have the data about the users that are matched with the ones in your phone.

How to retrieve data from all the Users using Firebase and Swift

Looks like you misspelled the location key for your dictionary:

let location = userDict["Location"] as! [String: AnyObject]

Replace it with:

let location = userDict["location"] as! [String: AnyObject]

You can always put a breakpoint at the print line and see what your location dictionary looks like with po location in console.

How to retrieve all the user details from database in firebase

Your question isn't very clear. By user data, if you mean the user object of the other users, then simply put, you can not obtain the user object of the other users regardless of their sign-in method. You can only obtain your own user object by the FirebaseAuth.getInstance().getCurrentUser() method.

Having said that, if the data of the users is stored in the realtime database, you can obtain it in the same way that you obtain data from other nodes. Please note, though, that the privacy settings of your app will determine if you can read other users' data or not.

It would help if you show your database structure in the question.

Edit After Viewing Database Structure :-

Alright, from what I understand, this is quite a basic problem. What you need is a childEventListener to retrieve all the children ( in your case - users ) of the trace-5fa8c node.

The code for that is as follows :-

DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("trace-5fa8c");

databaseReference.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
userinfo user = dataSnapshot.getValue(userinfo.class);

Log.d(TAG, "showData: name: " + user.getName());
Log.d(TAG, "showData: Mobile: " + user.getMob());
Log.d(TAG, "showData: Vehicle: " + user.getVehicle());
Log.d(TAG, "showData: Address: " + user.getaddress());

//Do whatever further processing you need
}

@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) {

}
};

Also, even though this is not a part of your question, I'd like to add that with each onChildAdded(datasnapshot), you can get a userInfo pojo. So, in your showData() method, instead of creating a new Arraylist each time, maintain a single Arraylist<UserInfo> and keep adding the child pojo to it each time a child is added. This ArrayList object will be the dataset for your ListView object.



Related Topics



Leave a reply



Submit