function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Chelsea LukowskiChelsea Lukowski 

How to get a random number of records

I need to get 10% this quater Sales_c records for audit purposes. I have a visualforce page and apex class setup but I am getting "Attempt to de-reference a null object" and I cannot figure it out. 

Apex Class:
public class RandomizerMasterTriggerHandler {
    
    
    public List<Sales__c> RandomSales {get;set;}
    public List<Sales__c> sales {get;set;}
    
    public RandomizerMasterTriggerHandler(){
        
        //Number of random sales to be returned
        sales = [select Sales_Year__c, Total_Sale_Line_Item_Amount_del__c, Name, Id, Partner_Account__c, Sale_Status__c from Sales__c where CreatedDate = LAST_QUARTER];
        decimal percentOfSales = .10;
        Double numberOfsales = sales.size() * percentOfSales;
        system.debug('Sales List - ' + sales.size());
        system.debug('Number of Sales - ' + numberofSales);
                     
        //Make sure there are enough records
        if(sales.size() >= numberOfsales){
            System.debug('Sales List size ' + sales.size());
            
            //create a list of strings to pass to our randomizer method
            List<string> salesIDs = new List<string>();
            Map<ID,Sales__c> salesMap = new Map<ID,Sales__c>();
            for(Sales__c s : sales){
                salesIDs.add(s.Id);
                salesMap.put(s.Id,s);
            }
            system.debug('SalesIDs - ' + salesIds);
            system.debug('SalesIDs - ' + salesIds.size());
            system.debug('SalesMap - ' + salesMap);
            system.debug('SalesMap - ' + salesMap.size());
            //create a set to hold the returned ids so that we can make sure there are no dupliates
            Set<Id> usedIds = new Set<Id>();
            string randomID;
            //Now lets get the random sales IDs
            for(Integer i=0; i<numberOfSales; i++){
				randomId = randomizer.getRandomString(salesIDs);
                system.debug('RandomId - ' + randomId);
                //check for duplicates
                while(usedIDs.contains(randomId)){
                    randomId = randomizer.getRandomString(salesIDs);
                }
                usedIDs.add(randomId);
                System.debug('usedIDs - ' + usedIds);
                RandomSales.add(salesMap.get(randomId));
                system.debug('Random Sales - ' + RandomSales);
            }
        }
    }
}
VisualForce page:
<apex:page controller="RandomizerMasterTriggerHandler" cache="true">
    
    <table>
        <tr>
            <th>Sales Number</th><th>Sales ID</th>
        </tr>
        <apex:repeat value="{!RandomSales}" var="s">
            <tr>
                <td><a target="_blank" href="/{!s.Id}">{!s.Name}</a></td>
                <td><a target="_blank" href="/{!s.Id}">{!s.Id}</a></td>
            </tr>
        </apex:repeat>
    </table>
    
</apex:page>

Apex class method for random number:
public class Randomizer {

     //returns a random Integer
     public static Integer getRandomNumber(Integer size){
          Double d = math.random() * size;
          return d.intValue();
     }

     //returns either true or false randomly
     public static Boolean getRandomBoolean(){
          if(math.mod(getRandomNumber(10),2) == 0){
               return true;
          }
          else{
               return false;
          }
     }

     //Get's a random value from a list of strings
     public static String getRandomString(List<String> strings){
          List<Double> ranks = new List<Double>();
          Map<Double,String> rankMap = new Map<Double,String>();

          for(String s : strings){
               Boolean isDup = true;
               Double rank;

               While(isDup){
                    Double x = getRandomNumber(100000);
                    if(!rankMap.containsKey(x)){
                         rank = x;
                         isDup = false;
                    }
               }

               ranks.add(rank);
               rankMap.put(rank,s);
          }

          ranks.sort();
          return rankMap.get(ranks.get(0));
     }

     //Returns a random picklist value 
     public static string getRandomPickListValue(Sobject s_object, String field_name, Boolean allow_blank){
          List<String> Strings = new List<String>();
          if(allow_blank){
               String b = '';
               Strings.add(b);
          }
            Schema.sObjectType sobject_type = s_object.getSObjectType();
            Schema.DescribeSObjectResult sobject_describe = sobject_type.getDescribe();
            Map<String, Schema.SObjectField> field_map = sobject_describe.fields.getMap();
            List<Schema.PicklistEntry> pick_list_values = field_map.get(field_name).getDescribe().getPickListValues();
            for (Schema.PicklistEntry a : pick_list_values) {
                Strings.add(a.getValue());
            }
            return getRandomString(Strings);
     }

     //returns a map of all picklists and multiselect picklists for a givien object
     //the keyset is the field name using proper case
     public static Map<String,List<String>> getPicVals(sObject s_object){
          Map<String,List<String>> valueMap = new Map<String,List<String>>();
          Schema.sObjectType sobject_type = s_object.getSObjectType();
          Schema.DescribeSObjectResult r = sobject_type.getDescribe();
          Map<String, Schema.SObjectField> field_map = r.fields.getMap();

          for(String s : field_map.keyset()){
               List<String> strings = new List<String>();
               Schema.DescribeFieldResult F = field_map.get(s).getDescribe();
               if(f.GetType() == Schema.DisplayType.Picklist || f.GetType() == Schema.DisplayType.MultiPicklist){
                    List<Schema.PicklistEntry> pick_list_values = field_map.get(s).getDescribe().getPickListValues();
                    for (Schema.PicklistEntry a : pick_list_values) {
                         strings.add(a.getValue());
                   }
                   valueMap.put(String.valueOf(field_map.get(s)),strings);
               }
          }
          return valueMap;
     }

     //Returns Lorem Ipsum placeholder text.
     public static String getPlaceholderText(Integer length){
          String firstSentence = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. ';
          List<String> sentenceList = new List<String>();
          sentenceList.add('Vivamus nec lacus eget massa cursus pulvinar. ');
          sentenceList.add('Morbi vel odio eget nunc auctor posuere eget eget ante. ');
          sentenceList.add('Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. ');
          sentenceList.add('Pellentesque lacus eros. ');
          sentenceList.add('Sed suscipit tristique varius. ');
          sentenceList.add('Mauris ultricies, nibh eu fermentum accumsan, justo quam pulvinar tellus, sed tempor quam eros sit amet ante. ');
          sentenceList.add('Duis mi libero, cursus nec facilisis ut, commodo eget nunc. ');
          sentenceList.add('Nulla eros augue, iaculis sed volutpat et, sagittis quis sem. ');
          sentenceList.add('Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nulla placerat accumsan vulputate. ');
          sentenceList.add('Fusce placerat tellus eget tellus faucibus a gravida sapien fermentum. ');

          String s = firstSentence;

          while (s.length() < length+1){
               s += getRandomString(sentenceList);
          }

          s = s.trim();

          while (s.length() >= length-1){
               s = s.substring(0,s.length()-1).trim();
          } 

          s = s.substring(0,s.length()-1).trim();
          s += '.';
          return s;
     }
}

Debug log:
39.0 APEX_CODE,DEBUG;APEX_PROFILING,NONE;CALLOUT,NONE;DB,NONE;SYSTEM,DEBUG;VALIDATION,NONE;VISUALFORCE,NONE;WAVE,INFO;WORKFLOW,NONE 10:10:34.0 (245538)|USER_INFO|[EXTERNAL]|005o0000001bpTU|chelsea.lukowski@titan-intl.com.jitterbit|Central Standard Time|GMT-05:00 10:10:34.0 (275394)|EXECUTION_STARTED 10:10:34.0 (279105)|CODE_UNIT_STARTED|[EXTERNAL]|066K00000002BGc|VF: /apex/RandomizerVisualforcePage 10:10:34.0 (47826025)|SYSTEM_MODE_ENTER|true 10:10:34.0 (52730566)|USER_DEBUG|[13]|DEBUG|Sales List - 22 10:10:34.0 (52744364)|USER_DEBUG|[14]|DEBUG|Number of Sales - 2.2 10:10:34.0 (52759612)|USER_DEBUG|[21]|DEBUG|Sales List size 22 10:10:34.0 (53290767)|USER_DEBUG|[30]|DEBUG|SalesIDs - (a2HK0000001LJQzMAO, a2HK0000001LJR9MAO, a2HK0000001LJR4MAO, a2HK0000001LJREMA4, a2HK0000001LJUIMA4, a2HK0000001LJV6MAO, a2HK0000001LJV7MAO, a2HK0000001LJUcMAO, a2HK0000001LJUmMAO, a2HK0000001LJVGMA4, ...) 10:10:34.0 (53301778)|USER_DEBUG|[31]|DEBUG|SalesIDs - 22 10:10:34.0 (53496404)|USER_DEBUG|[32]|DEBUG|SalesMap - {a2HK0000001LJIUMA4=Sales__c:{Sales_Year__c=2017, Total_Sale_Line_Item_Amount_del__c=3250.00, Name=S-00845, Id=a2HK0000001LJIUMA4, Partner_Account__c=001K000001JtseEIAR, Sale_Status__c=Submitted, RecordTypeId=012o0000000q44bAAA}, a2HK0000001LJQzMAO=Sales__c:{Sales_Year__c=2017, Total_Sale_Line_Item_Amount_del__c=0.00, Name=S-00846, Id=a2HK0000001LJQzMAO, Partner_Account__c=001K000001JtseEIAR, Sale_Status__c=Submitted, RecordTypeId=012o0000000q44bAAA}, a2HK0000001LJR4MAO=Sales__c:{Sales_Year__c=2017, Total_Sale_Line_Item_Amount_del__c=0.00, Name=S-00847, Id=a2HK0000001LJR4MAO, Partner_Account__c=001K000001JtseEIAR, Sale_Status__c=Open, RecordTypeId=012o0000000q44aAAA}, a2HK0000001LJR9MAO=Sales__c:{Sales_Year__c=2017, Total_Sale_Line_Item_Amount_del__c=0.00, Name=S-00848, Id=a2HK0000001LJR9MAO, Partner_Account__c=001K000001JtseEIAR, Sale_Status__c=Open, RecordTypeId=012o0000000q44aAAA}, a2HK0000001LJREMA4=Sales__c:{Sales_Year__c=2017, Total_Sale_Line_Item_Amount_del__c=0.00, Name=S-00849, Id=a2HK0000001LJREMA4, Partner_Account__c=001K000001JtseEIAR, Sale_Status__c=Open, RecordTypeId=012o0000000q44aAAA}, a2HK0000001LJRiMAO=Sales__c:{Sales_Year__c=2017, Total_Sale_Line_Item_Amount_del__c=1500.00, Name=S-00850, Id=a2HK0000001LJRiMAO, Partner_Account__c=001K000001JtsjiIAB, Sale_Status__c=Submitted, RecordTypeId=012o0000000q44aAAA}, a2HK0000001LJUIMA4=Sales__c:{Sales_Year__c=2017, Total_Sale_Line_Item_Amount_del__c=0.00, Name=S-00851, Id=a2HK0000001LJUIMA4, Partner_Account__c=001K000001JtsjiIAB, Sale_Status__c=Submitted, RecordTypeId=012o0000000q44aAAA}, a2HK0000001LJUNMA4=Sales__c:{Sales_Year__c=2017, Total_Sale_Line_Item_Amount_del__c=0.00, Name=S-00852, Id=a2HK0000001LJUNMA4, Partner_Account__c=001K000001JtsjiIAB, Sale_Status__c=Submitted, RecordTypeId=012o0000000q44aAAA}, a2HK0000001LJUSMA4=Sales__c:{Sales_Year__c=2017, Total_Sale_Line_Item_Amount_del__c=0.00, Name=S-00853, Id=a2HK0000001LJUSMA4, Partner_Account__c=001K000001JtseEIAR, Sale_Status__c=Open, RecordTypeId=012o0000000q44aAAA}, a2HK0000001LJUXMA4=Sales__c:{Sales_Year__c=2017, Total_Sale_Line_Item_Amount_del__c=0.00, Name=S-00854, Id=a2HK0000001LJUXMA4, Partner_Account__c=001K000001JtseEIAR, Sale_Status__c=Open, RecordTypeId=012o0000000q44aAAA}, ...} 10:10:34.0 (53512075)|USER_DEBUG|[33]|DEBUG|SalesMap - 22 10:10:34.0 (67031844)|USER_DEBUG|[40]|DEBUG|RandomId - a2HK0000001LJUrMAO 10:10:34.0 (67082996)|USER_DEBUG|[46]|DEBUG|usedIDs - {a2HK0000001LJUrMAO} 10:10:34.0 (67272025)|FATAL_ERROR|System.NullPointerException: Attempt to de-reference a null object Class.RandomizerMasterTriggerHandler.<init>: line 47, column 1
Balayesu ChilakalapudiBalayesu Chilakalapudi
Try using LIMIT in your soql query with the random number like this,
Double d = math.random() * size; 
Integer c= d.intValue();
sales = [select Sales_Year__c, Total_Sale_Line_Item_Amount_del__c, Name, Id, Partner_Account__c, Sale_Status__c from Sales__c where CreatedDate = LAST_QUARTER
LIMIT :c];