how to get random rows(parse objects) from parse table using android parse sdk?

前端 未结 3 454
离开以前
离开以前 2021-01-25 00:56

I have 500 records on parse class or table and now i need to get 10 random records out of 500 records?

Please tell me how can I do this.

 ParseQuery

3条回答
  •  温柔的废话
    2021-01-25 01:26

    The best way is probably to write a CloudCode module that downloads 500 objects, then randomly selects 10 to send down to your Android app in the response. That's much better than downloading 500 objects to your device and choosing 10.

    It's been a while since I've written CloudCode, but you could do something like the following.

    in iOS app (you can do a little work to find the Android equivalent):

    [PFCloud callFunctionInBackground:@"get500obj" withParameters:@{} block:^(id result, NSError *error) {
       // do something with result
    }];
    

    in CloudCode (this should be treated as pseudocode as it's untested):

    Parse.Cloud.define('get500obj', function(request, response) {
        // for getting random element
        Array.prototype.randomElement = function () {
            return this[Math.floor(Math.random() * this.length)]
        }
    
        var query = new Parse.Query("your-object-class-name");
        query.find({
            success: function(results) {
                var final10 = [];
                for (var i = 0; i < 10; i++) {
                    var myRandomElement = results.randomElement()
                    if (final10.indexOf(myRandomElement) == -1) {
                        final10.push(myRandomElement);
                    } else {
                        i--;
                    }
                }
                response.success(final10);
            },
            error: function() {
                response.error(error);
            }
        });
    });
    

提交回复
热议问题