Can someone explain me why can sometimes this exception happen?  Exception java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.Date.getTime()' on a null object reference  ChannelEPGF$myPagerAdapter.getItem (ChannelEPGF.java:82) (find the "//THIS IS THE 82. rows" text in my code)  here is my code:      import android.os.Bundle;     import android.support.v4.app.Fragment;     import android.support.v4.app.FragmentManager;     import android.support.v4.app.FragmentPagerAdapter;     import android.support.v4.view.ViewPager;     import android.view.LayoutInflater;     import android.view.View;     import android.view.ViewGroup;     import com.mp.myapp.DataTypes.ChannelEPG;     import java.util.Date;      public class ChannelEPGF extends Fragment implements ChannelEPG.fragmentCommunicator {     private Date selectedDate;     private String channelId;     private String channelTitle;     private ViewPager pager;     private boolean isTunable;      @Override     public void sendMessage(String name, Object msg) {             if (msg != null) {                     ChannelEPG item = (ChannelEPG) msg;                     channelId = item.GetId();                     channelTitle = item.GetTitle();                     isTunable = item.GetTunable();             } else {                     pager.getAdapter().notifyDataSetChanged();             }     }      @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {             View v = inflater.inflate(R.layout.activity_channel_epgf, container, false);              pager = (ViewPager) v.findViewById(R.id.viewPager);             if (pager != null) {                     pager.setAdapter(new myPagerAdapter(getChildFragmentManager()));                     pager.setCurrentItem(1);             }              return v;     }      private class myPagerAdapter extends FragmentPagerAdapter {              public myPagerAdapter(FragmentManager fm) {                     super(fm);             }              @Override             public Fragment getItem(int pos) {                     if (pos == 0) {                             selectedDate = new Date();                             selectedDate.setTime(selectedDate.getTime() - 24 * 3600 * 1000);                             return ActivityChannelEPG.newInstance(selectedDate, channelId, channelTitle, isTunable);                     } else if (pos == 1) {                             selectedDate = new Date();                             return ActivityChannelEPG.newInstance(selectedDate, channelId, channelTitle, isTunable);                     } else if (pos == 2) {                             selectedDate = new Date();                             selectedDate.setTime(selectedDate.getTime() + 24 * 3600 * 1000);                             return ActivityChannelEPG.newInstance(selectedDate, channelId, channelTitle, isTunable);                     } else {                             selectedDate.setTime(selectedDate.getTime() + 24 * 3600 * 1000); //THIS IS THE 82. rows                             return ActivityChannelEPG.newInstance(selectedDate, channelId, channelTitle, isTunable);                     }             }              @Override             public int getCount() {                     return 8;             }              public int getItemPosition(Object object) {                     return POSITION_NONE;             }     }   }
129
What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them?  What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
119160
This Trigger is on lead (Before Insert, Before Update) and it errors (System.NullPointerException: Attempt to de-reference a null object). I'm getting this error when i'm posting "Web to Lead". However i do have the right ORG iD and Record type id included on the xml file:   &lt;input type=hidden name="oid" value="xxxxxxxxxxxxx"&gt; &lt;input type=hidden name="recordType" id="recordType" value="zzzzzzzzzzzzzzzzzz"&gt;    trigger IAAILeadTrigger on Lead (before insert, before update){ //BEGIN: S-444340 T-561808 - Process only IAA Remarketing Recordtype data     Map&lt;ID,Schema.RecordTypeInfo&gt; rt_Map = Lead.sObjectType.getDescribe().getRecordTypeInfosById();      //Looks up the branches based on the Lead PostalCode     if(trigger.isBefore){          for(Lead ld : trigger.new){                      if (rt_map.get(ld.recordTypeID).getName().containsIgnoreCase('IAA Remarketing') )                if( trigger.isInsert ||                    (trigger.isUpdate &amp;&amp; ld.Branch__c == null) ||                   (trigger.isUpdate &amp;&amp; ld.PostalCode != trigger.oldMap.get(ld.id).PostalCode)               ){                   leads.add(ld);               }           }           }                 //Only check the leads that are in the lead list and NOT the full trigger.new list         if(!leads.isEmpty()){             LeadController.GetLeadBranches(leads);           }     }  }
73868
I need help. I am currently trying to test this code before uploading  public class CoreValuesExt { ApexPages.StandardController sc; public boolean readonly {get; set;} public Core_Values__c cv {get; set;} public integer countEdit = 1; public string buttonValue {get; set;} public integer recordScan;  public CoreValuesExt(ApexPages.StandardController sc) {     this.sc = sc;     cv = new Core_Values__c();     cv.Account__c = sc.getid();      readonly = true;     buttonValue = 'Edit';     recordScan = [SELECT COUNT() FROM Core_Values__c WHERE Account__c = :cv.Account__c];    if (recordScan != 0){    cv = [SELECT id, HSE__c, Professionalism_Integrity__c, Quality_Accuracy__c, Technology_Innovation__c, Timeliness__c, Value_for_money__c FROM Core_Values__c WHERE Account__c = :cv.Account__c];     }  }  public ApexPages.PageReference Save() {     return sc.Save(); }  public void ApplyAction() {     countEdit++;     Integer modolus = Math.mod(countEdit, 2);     String total = cv.HSE__c + cv.Professionalism_Integrity__c + cv.Quality_Accuracy__c + cv.Technology_Innovation__c + cv.Value_for_Money__c + cv.Timeliness__c;     if(modolus == 0)     {         readonly = false;         buttonValue = 'Save';     }     else     {         if(total != 'nullnullnullnullnullnull')            {         if (recordScan == 0){         insert cv;         readonly = true;         buttonValue = 'Edit';         }         else         {         update cv;         readonly = true;         buttonValue = 'Edit';         }         }     }    }   }  With this trigger.  trigger CoreValuesTrigger on Core_Values__c (before insert) {  Core_Values__c cvs = Trigger.new; CoreValuesExt.ApplyAction(cvs);  }   But when I try to save, I get a message saying:      Illegal assignment from List to   CoreValuesExt__Core_Values__c at line 3 column 1   "  How do I go through with this? I need help. Thanks
104149
When an exception is thrown in an Asp.Net web page, an error message is displayed with the complete stack trace.    Example below:       Stack Trace:     IndexOutOfRangeException: Index was outside the bounds of the array.    MyNameSpace.SPAPP.ViewDetailsCodeBehind.LoadView()  +5112   MyNameSpace.SPAPP.ViewDetailsCodeBehind.Page_Load(Object sender, EventArgs e) +67   System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +13   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +43   System.Web.UI.Control.OnLoad(EventArgs e) +98   ... ...   The problem is that the Line number displayed does not correspond to the line in my code that originated the exception. In the example above, the stack shows line number 5111, yet my code behind .cs file only has 250 lines!  The aspx page is stored in a SharePoint site and the Assembly with the code behind has been deployed to GAC. Also, I've compiled in Debug mode. Given the settings above, how can I find out what line in my code caused the Exception?    Clarification as pointed out by :     In Release mode the number in front of the exception is NOT the line of code. Instead it's an offset to the native compiled code, which doesn't have any meaning to humans. More about this here:       In debug mode the PDB file will automatically map the native code offset to your .cs line in code and the number displayed WILL be the corresponding line in code.
11494
App version 1.0.27  If you the notification pane and click on the loading icon while it's spinning, the app will cause the app to crash.  03-26 22:51:08.331 E/AndroidRuntime(5927): FATAL EXCEPTION: main 03-26 22:51:08.331 E/AndroidRuntime(5927): java.lang.ArrayIndexOutOfBoundsException: length=0; index=-1 03-26 22:51:08.331 E/AndroidRuntime(5927): at java.util.ArrayList.get(ArrayList.java:310) 03-26 22:51:08.331 E/AndroidRuntime(5927): at com.stackexchange.marvin.ui.BaseActivity$3.onItemClick(BaseActivity.java:266) 03-26 22:51:08.331 E/AndroidRuntime(5927): at android.widget.AdapterView.performItemClick(AdapterView.java:298) 03-26 22:51:08.331 E/AndroidRuntime(5927): at android.widget.AbsListView.performItemClick(AbsListView.java:1100) 03-26 22:51:08.331 E/AndroidRuntime(5927): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2788) 03-26 22:51:08.331 E/AndroidRuntime(5927): at android.widget.AbsListView$1.run(AbsListView.java:3463) 03-26 22:51:08.331 E/AndroidRuntime(5927): at android.os.Handler.handleCallback(Handler.java:730) 03-26 22:51:08.331 E/AndroidRuntime(5927): at android.os.Handler.dispatchMessage(Handler.java:92) 03-26 22:51:08.331 E/AndroidRuntime(5927): at android.os.Looper.loop(Looper.java:137) 03-26 22:51:08.331 E/AndroidRuntime(5927): at android.app.ActivityThread.main(ActivityThread.java:5103) 03-26 22:51:08.331 E/AndroidRuntime(5927): at java.lang.reflect.Method.invokeNative(Native Method) 03-26 22:51:08.331 E/AndroidRuntime(5927): at java.lang.reflect.Method.invoke(Method.java:525) 03-26 22:51:08.331 E/AndroidRuntime(5927): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 03-26 22:51:08.331 E/AndroidRuntime(5927): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 03-26 22:51:08.331 E/AndroidRuntime(5927): at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:126) 03-26 22:51:08.331 E/AndroidRuntime(5927): at dalvik.system.NativeStart.main(Native Method)   (Think I should calm down on finding bugs for a little while? :P)
68403
I have this controller but I am getting this error      System.QueryException: List has no rows for assignment to SObject   public class MyController {     private final Account account;      public MyController() {         account = [SELECT Id, Name, Site FROM Account                     WHERE Id = :ApexPages.currentPage().getParameters().get('id')];             }      public Account getAccount() {         return account;     }      public PageReference save() {         update account;         return null;     } }
93419
I am using Structure map like the MVC storefront by Rob Conery does and I have an AdminController and so to get to it I just type:  website/Admin/action   however if I miss spell the controller name I get the error below:  Exception Details: System.ArgumentNullException: Value cannot be null. Parameter name: key  There error occurs on this line:  Controller controller = ObjectFactory.GetInstance(controllerType) as Controller;   Does anyone have any ideas on how I can handle this error or not allow it to happen at all and maybe just goto a 404 page??  Cheers in advance
101830
There is a Java Void -- uppercase V-- . The only situation I have ever seen it used is to parameterize Callables    final Callable&lt;Void&gt; callable = new Callable&lt;Void&gt;() {             public Void call() {                 foobar();                 return null;             }         };   Are there any other uses for the Java Void reference type? Can it ever be assigned anything other than null? If yes, do you have examples?
8224
Since many users are facing the NullReferenceException: Object reference not set to an instance of an object error in Unity, I thought that it would be a good idea to gather from multiple source some explanation and ways to fix this error.  Symptoms I am getting the error below appearing in my console, what does it mean and how do I fix it?  NullReferenceException: Object reference not set to an instance of an object
92456
Alright, I have been doing the following (variable names have been changed):   FileInputStream fis = null; try {     fis = new FileInputStream(file);      ... process ...  } catch (IOException e) {     ... handle error ... } finally {     if (fis != null)         fis.close(); }    Recently, I started using FindBugs, which suggests that I am not properly closing streams.  I decide to see if there's anything that can be done with a finally{} block, and then I see, oh yeah, close() can throw IOException.  What are people supposed to do here?  The Java libraries throw too many checked exceptions.
92671
public class ExampleClass {       public static void publishCaseUpdateNotifications(List&lt;Case&gt; cases) {     List&lt;Case_Updated__e&gt; notifications = new List&lt;Case_Updated__e&gt;();     for (Case c: cases) {         notifications.add(new Case_Updated__e(             Case__c = (String)c.Id,             CreatedByName__c = UserInfo.getName(),             CaseNumber__c = c.CaseNumber         ));     }       List&lt;Database.SaveResult&gt; results = EventBus.publish(notifications);      for (Database.SaveResult result : results) {         if (!result.isSuccess()) {             for (Database.Error error : result.getErrors()) {                 System.debug('Error returned: ' +                     error.getStatusCode() +' - '+                     error.getMessage());             }         }       }      }    }   My Test Class: getting error   @isTest   public class ExampleTestClass {    @isTest   static void testClassforExample(){         Case testcase = new Case(Subject ='Test',);      list&lt;Case_Updated__e&gt; caseUpdate =      ExampleClass.publishCaseUpdateNotifications(testcase );       }      }   My Error is Method does not exist or incorrect signature: void publishCaseUpdateNotifications(Case) from the type ExampleTestClass   Please suggest me how to resolve this error.     trigger Cases on Case (after insert) { if(Trigger.isAfter) {     System.debug('I will be replaced shortly!'); }  }   Do we need test class for above trigger. Please suggest me too
74634
I am trying to start share-point workflow using CSOM(Client side object model) by following means of code. But i got the following error from the line mark in comment. Please help me to figure out this error.     Error :- Cannot invoke method or retrieve property from null   object. Object returned by the following call stack is null.   "GetWorkflowDeploymentService new   Microsoft.SharePoint.WorkflowServices.WorkflowServicesManager() "    public bool StartWorkFlow()  {     string workflowName = "UpdateDealStatus";     // connect to the workflow services via a CSOM client context    var workflowServicesManager = new WorkflowServicesManager(_sharepoint,                  _sharepoint.Web);    // connect to the deployment service    var workflowDeploymentService = workflowServicesManager.GetWorkflowDeploymentService();    // get all installed workflows   var publishedWorkflowDefinitions =    workflowDeploymentService.EnumerateDefinitions(true);             _sharepoint.Load(publishedWorkflowDefinitions);     try    {       _sharepoint.ExecuteQuery();//Error thrown from this line    }    catch (Exception ex)    {      }     // find the first workflow definition    var firstWorkflowDefinition = publishedWorkflowDefinitions.First();     // connect to the subscription service    var workflowSubscriptionService = workflowServicesManager.GetWorkflowSubscriptionService();     // get all workflow associations    var workflowAssociations = workflowSubscriptionService.EnumerateSubscriptionsByDefinition(firstWorkflowDefinition.Id);     _sharepoint.Load(workflowAssociations);    _sharepoint.ExecuteQuery();     foreach (var association in workflowAssociations)    {        Console.WriteLine("{0} - {1}",        association.Id, association.Name);    }     return true; }
58028
I want to do something like this :  myYear = record.GetValueOrNull&lt;int?&gt;("myYear"),   Notice the nullable type as the generic parameter.   Since the GetValueOrNull function could return null my first attempt was this:   public static T GetValueOrNull&lt;T&gt;(this DbDataRecord reader, string columnName)   where T : class {     object columnValue = reader[columnName];      if (!(columnValue is DBNull))     {         return (T)columnValue;     }     return null; }   But the error I'm getting now is:     The type 'int?' must be a reference type in order to use it as parameter 'T' in the generic type or method   Right! Nullable&lt;int&gt; is a struct! So I tried changing the class constraint to a struct constraint (and as a side effect can't return null any more):  public static T GetValueOrNull&lt;T&gt;(this DbDataRecord reader, string columnName)   where T : struct   Now the assignment:  myYear = record.GetValueOrNull&lt;int?&gt;("myYear");   Gives the following error:     The type 'int?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method   Is specifying a nullable type as a generic parameter at all possible?
18236
Steps to Reproduce   Tap faster on the code. or Tap once on a huge code.   but happens only when  setupForGeneric() is called, might be a bug related to   private void setupForCode()   { String str = getIntent().getStringExtra("com.stackexchange.marvin:code_block"); PrettyWebView localPrettyWebView = (PrettyWebView)findViewById(R.id.code); localPrettyWebView.setPostBody("&lt;pre&gt;&lt;code&gt;" + TextUtils.htmlEncode(str) + "&lt;/pre&gt;&lt;/code&gt;", false); localPrettyWebView.setBackgroundColor("#eeeeee"); }  private void setupForGeneric() { String str = getIntent().getStringExtra("com.stackexchange.marvin:web_url"); PrettyWebView localPrettyWebView = (PrettyWebView)findViewById(R.id.code); localPrettyWebView.getSettings().setBuiltInZoomControls(true); localPrettyWebView.getSettings().setLoadWithOverviewMode(true); localPrettyWebView.getSettings().setUseWideViewPort(true); localPrettyWebView.loadUrl(str); localPrettyWebView.setBackgroundColor("#eeeeee"); }   Log  09-05 03:54:30.312: E/AndroidRuntime(26264): FATAL EXCEPTION: WebViewCoreThread  09-05 03:09:39.522: E/Crittercism(18318): java.lang.NullPointerException: [v0.1.22]  09-05 03:09:39.522: E/Crittercism(18318):   at android.content.ComponentName.&lt;init&gt;(ComponentName.java:75) 09-05 03:09:39.522: E/Crittercism(18318):   at android.content.Intent.&lt;init&gt;(Intent.java:3156) 09-05 03:09:39.522: E/Crittercism(18318):   at com.stackexchange.marvin.ui.ViewPopupActivity.showCode(ViewPopupActivity.java:25) 09-05 03:09:39.522: E/Crittercism(18318):   at com.stackexchange.marvin.ui.question.QuestionFragment$1.onCodeClicked(QuestionFragment.java:67) 09-05 03:09:39.522: E/Crittercism(18318):   at com.stackexchange.marvin.ui.common.PrettyWebView$WebAppInterface.codeClicked(PrettyWebView.java:197) 09-05 03:09:39.522: E/Crittercism(18318):   at android.webkit.WebViewCore.nativeTouchUp(Native Method) 09-05 03:09:39.522: E/Crittercism(18318):   at android.webkit.WebViewCore.nativeTouchUp(Native Method) 09-05 03:09:39.522: E/Crittercism(18318):   at android.webkit.WebViewCore.access$4000(WebViewCore.java:59) 09-05 03:09:39.522: E/Crittercism(18318):   at android.webkit.WebViewCore$EventHub$1.handleMessage(WebViewCore.java:1449) 09-05 03:09:39.522: E/Crittercism(18318):   at android.os.Handler.dispatchMessage(Handler.java:99) 09-05 03:09:39.522: E/Crittercism(18318):   at android.os.Looper.loop(Looper.java:137) 09-05 03:09:39.522: E/Crittercism(18318):   at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:790) 09-05 03:09:39.522: E/Crittercism(18318):   at java.lang.Thread.run(Thread.java:856)
112290
This code throws a NullReferenceException when it calls ExecuteScalar:  selectedPassengerID = 0;  //SqlCommand command = GenericDataAccess.CreateCommand();   // 2nd test string connectionString = ""; SqlConnection conn;  connectionString = ConfigurationManager.     ConnectionStrings["ConnST-MHM"].ConnectionString; conn = new SqlConnection(connectionString); SqlCommand command = new SqlCommand(); command.CommandType = CommandType.StoredProcedure ; command.Connection = conn; command.CommandText = "SearchForPassenger";  SqlParameter param;  param = command.CreateParameter(); param.ParameterName = "@name"; param.Value = pName; // Session[""]; param.DbType = DbType.String; command.Parameters.Add(param);  param = command.CreateParameter(); param.ParameterName = "@flightDate"; param.Value = date;  param.DbType = DbType.String; command.Parameters.Add(param);  param = command.CreateParameter(); param.ParameterName = "@ticketNo"; param.Value = ticketNumber;  param.DbType = DbType.Int32; command.Parameters.Add(param);  int item;  command.Connection.Open(); item = (int)command.ExecuteScalar();
81630
Why does this test program result in a java.lang.IllegalMonitorStateException?  public class test {     static Integer foo = new Integer(1);     public static void main(String[] args) {         synchronized(foo) {             foo++;             foo.notifyAll();         }         System.err.println("Success");     } }   Result:  Exception in thread "main" java.lang.IllegalMonitorStateException         at java.lang.Object.notifyAll(Native Method)         at test.main(test.java:6)
18034
when i try to save the following code, i got the error below. Following same instructions given in this link, but still errors. Am i doing anything wrong here? please suggest.    @isTest private class WebSvcCalloutTest {     @isTest static void testEchoString() {         Account a = new Account(name='Tester',SAP_KUNNR__c='1172');         insert a;                       // This causes a fake response to be generated         Test.setMock(WebServiceMock.class, new WebServiceMockImpl());      } }   Error:  Save error: Method does not exist or incorrect signature: Test.setMock(Type, WebServiceMockImpl)    WebSvcCalloutTest.cls         @isTest global class WebServiceMockImpl implements WebServiceMock {    global void doInvoke(            Object stub,            Object request,            Map&lt;String, Object&gt; response,            String endpoint,            String soapAction,            String requestName,            String responseNS,            String responseName,            String responseType) {          sapComDocumentSapSoapFunctionsMcS.Z_GSSMWFM_HNDL_EVNTRQST00 sap1 = new sapComDocumentSapSoapFunctionsMcS.Z_GSSMWFM_HNDL_EVNTRQST00();                Map&lt;String,String&gt; mapSAP = new Map&lt;String,String&gt; {};         sapComDocumentSapSoapFunctionsMcS.ZgssmbstDatarcrd01 req = new sapComDocumentSapSoapFunctionsMcS.ZgssmbstDatarcrd01();               sapComDocumentSapSoapFunctionsMcS.ZGssmwfmHndlEvntrqst00Response_element ret =  sap1.ZGssmwfmHndlEvntrqst00('',req);         response.put('response_x', ret);     } }