+ Start a Discussion
Puja ChoudharyPuja Choudhary 

Attempt to de-reference a null object for soql query

hi,
I have a favourite button which fetches the items which has been ordered more than twice.
This is my controller

    Public List<Menu__c> favmenu {get;set;}
     favmenu = [select id, name,Category__c,Description__c,Image__c,ImageURL__c,Dish_Name__c,Price__c,
                 Special_Dish__c,Status__c,SubCategory__c,veg_non_veg__c,remarks__c from Menu__c where id IN : menuIdList]; 
           
           if(favmenu.size()>0)
               nofavourites = 'Choose from your favourites';
           else
                nofavourites='No favourites yet';

When i m testing for favmenu.size()>0 ..... it is working fine....but for the else part, when the soql query is not fetching any item, it is showing the error
Attempt to de-reference a null object 
An unexpected error has occurred. Your development organization has been notified.
Best Answer chosen by Puja Choudhary
HemantJain0206HemantJain0206
Hi,

Try initializing the list before the Soql query. Like this:
Public List<Menu__c> favmenu {get;set;}
favmenu  = new List<Menu__c>(); //Add this line
     favmenu = [select id, name,Category__c,Description__c,Image__c,ImageURL__c,Dish_Name__c,Price__c,
                 Special_Dish__c,Status__c,SubCategory__c,veg_non_veg__c,remarks__c from Menu__c where id IN : menuIdList];

 

All Answers

Nayana KNayana K
Can you please post the next part of code? I don't think these lines can cause issues.
Puja ChoudharyPuja Choudhary
Hi,
This is the full controller code
I am just trying to print the novafourites string.
public with sharing class ctr_foodmenucontroller {
    Public List<Menu__c> menu { get; set;}
    Public List<Toppings__c> toppings { get; set;}
    Public String mob { get; set;}
    Public Contact c { get; set;}
    Public String Lang { get; set;}
    Public String cid { get; set;}
    Public String cmessage { get; set;}
    Public String nofavourites { get; set;}
    Public String tout { get; set;}
    Public String tablen{get;set;}
    Public String custname { get; set;}
    Public String d { get; set;}
    public DateTime dd{get;set;}
    Public Room__c room {get;set;}
    Public id existingorderid { get; set;}    
    Public String Closelaterorderid{get; set;}
    Public Boolean closelater{get; set;}
    Public List<Order__c> order { get; set;}
    Public List<OLI__c> repeatorder { get; set;}
    Public List<AggregateResult> favourites { get; set;}
    public String selectedroomId { get; set; }
    Public Toppings__c t { get; set;}
    Public List<Menu__c> favmenu {get;set;}
    public String dynamiclist{get; set;}
    Public ctr_foodmenucontroller(){
    
       existingorderid = null;
       room = new Room__c();
       tout = System.currentPageReference().getParameters().get('tout');
       tablen = ApexPages.currentPage().getParameters().get('tablen'); 
       dd=Date.Today();
       //this.dynamiclist='defaultValue';
 

      //tout =false;
      //tablen ='';
      
      lang = ApexPages.currentPage().getParameters().get('lang');
      mob = ApexPages.currentPage().getParameters().get('mob');
      cid = ApexPages.currentPage().getParameters().get('cid');
       String taway= System.currentPageReference().getParameters().get('tout');
       String tnumber = ApexPages.currentPage().getParameters().get('tablen');
      cmessage = Label.Order_Submissions;
      
     
      if(cid!=null & cid!=''){
        c = [select id,name,Last_Login_Reff_Id__c,Mobilephone from contact where id=:cid limit 1];
       // order = [select id, Name,status__c from Order__c where Customer__c=:c.id and Session_id__c=:c.Last_Login_Reff_Id__c limit 1];
        order = [select id, Name,status__c from Order__c where Customer__c=:c.id and Tables__c=:tablen and Status__c='In Progress'  limit 1];
        
        repeatorder = [SELECT Id, Name, Menu__c,Order__c FROM OLI__c where Order__c in(SELECT id FROM Order__c where Customer__c=:c.id)];
           favourites = [select Menu__r.id menuid from OLI__c  where Order__c in(SELECT id FROM Order__c where Customer__c=:c.id and Status__c='Completed') group By Order__r.Customer__r.name,Menu__r.Dish_Name__c,Menu__r.id having count(id)>1 ];
          
          List<String> menuIdList = new List<String>();
         for(AggregateResult ar : favourites){
                 
                 menuIdList.add(String.Valueof(ar.get('menuid')));
                
            }

            if(menuIdList!=null && !menuIdList.isEmpty())    
                favmenu = [select id, name,Category__c,Description__c,Image__c,ImageURL__c,Dish_Name__c,Price__c,
                 Special_Dish__c,Status__c,SubCategory__c,veg_non_veg__c,remarks__c from Menu__c where id IN : menuIdList]; 
           
           if(favmenu.size()>0)
               nofavourites = 'Choose from your favourites';
           else
                nofavourites='No favourites yet';
               
           custname = c.name;
            
        if(order.size()>0)
                existingorderid = order[0].id;
            else
                existingorderid = null;
            
        }
        else{
            pagereference ref = new pagereference('/apex/dm_firstpage');
            ref.setredirect(true);
        } 
        
        
        
        
        menu = [SELECT Category__c,CreatedById, CreatedDate,Total_Price__c, IsDeleted, Description__c, Image__c, ImageURL__c,Chef_recommended__c, LastActivityDate, LastModifiedById, LastModifiedDate, Name, Dish_Name__c, OwnerId,Price__c, Id, Remarks__c, Special_Dish__c,Spicy__c, Status__c,Kids_Menu__c, SubCategory__c, SystemModstamp, veg_non_veg__c,Information__c, (SELECT Menu__c,Price__c,Topping__c,Name FROM Toppings__r) FROM Menu__c];
        
       
      }
      
     
     public List<SelectOption> getListOfRooms()
    {
           List<Room__c> RoomList = [select id,Name from Room__c] ;
           System.debug('Rooms'+RoomList.size());
           List<SelectOption> RoomOptionList = new List<SelectOption>();
           RoomOptionList .add(new SelectOption( ' ' ,'---Select---'));
           for(Room__c r : RoomList )
           {
                      RoomOptionList .add(new SelectOption(r.id , r.Name));
           }
          return RoomOptionList ;
    }
    
    
  /* public List<SelectOption> getdynamiclist() {
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('1','1'));
        options.add(new SelectOption('2','2'));
        options.add(new SelectOption('3','3'));
        options.add(new SelectOption('4','4'));
        options.add(new SelectOption('5','5'));
        return options;
    }*/
    
    
    String s = '1';
 
    public String getString() {
        return s;
    }
            
    public void setString(String s) {
        this.s = s;
    }
     
     public PageReference sort(){
     
                menu = [SELECT Category__c,CreatedById,Total_Price__c,Chef_recommended__c, CreatedDate, IsDeleted, Description__c, Image__c, ImageURL__c, LastActivityDate, LastModifiedById, LastModifiedDate, Name, Dish_Name__c, OwnerId,Price__c, Id, Remarks__c,Kids_Menu__c, Special_Dish__c,Spicy__c, Status__c, SubCategory__c, SystemModstamp, veg_non_veg__c,Information__c, (SELECT Menu__c,Price__c,Topping__c,Name FROM Toppings__r) FROM Menu__c  ORDER BY Price__c ASC];
                return null;
    }
     
     
     
    
    public PageReference redirect(){
         pagereference ref = new pagereference('/apex/dm_firstpage');
         ref.setredirect(true);
         return null;
    }
}

 
HemantJain0206HemantJain0206
Hi,

Try initializing the list before the Soql query. Like this:
Public List<Menu__c> favmenu {get;set;}
favmenu  = new List<Menu__c>(); //Add this line
     favmenu = [select id, name,Category__c,Description__c,Image__c,ImageURL__c,Dish_Name__c,Price__c,
                 Special_Dish__c,Status__c,SubCategory__c,veg_non_veg__c,remarks__c from Menu__c where id IN : menuIdList];

 
This was selected as the best answer
Nayana KNayana K
So, here is the issue:
 
if(menuIdList!=null && !menuIdList.isEmpty())    
                favmenu = [select id, name,Category__c,Description__c,Image__c,ImageURL__c,Dish_Name__c,Price__c,
                 Special_Dish__c,Status__c,SubCategory__c,veg_non_veg__c,remarks__c from Menu__c where id IN : menuIdList];

If this if condition doesn't satisfy, then favmenu will not be queried. Which means this will remain null.
In next when you try to check if(favmenu.size()>0) => it will be evaluating as if(null.size() > 0) which will give you attempt to deference null.


Just above the if, initialize the favmenu to new List() :
 
favmenu = new List<Menu__c>();

if(menuIdList!=null && !menuIdList.isEmpty()) favmenu = [select id, name,Category__c,Description__c,Image__c,ImageURL__c,Dish_Name__c,Price__c, Special_Dish__c,Status__c,SubCategory__c,veg_non_veg__c,remarks__c from Menu__c where id IN : menuIdList];


 
LBKLBK
Change the following line of code (line 66).
if(favmenu.size()>0)
to
if(favmenu!=null && favmenu.size()>0)
This will solve this issue.