I created a client/server program where the server sends a packet to the client which has a randomly picked string from an array. But when ever I run the server and then the client which send data about it's byte array the server after receiving the packet throws an exception which looks like this:  Exception in thread "SDServerThread" java.lang.NullPointerException         at SDServerThread.run(SDServerThread.java:56)   This exception points to this line of code:  buf = GetText.getBytes();   The buf is a byte array list:  byte[] buf = new byte[256];   GetText is a string which calls a method to pick a random string.:  String GetText = getText();   The code starting from byte[] buf = new byte[256]; to buf = GetText.getBytes(); looks like this:  byte[] buf = new byte[256];          DatagramPacket packet = null; packet = new DatagramPacket(buf, buf.length); socket.receive(packet); System.out.println("packet received"); textArea.append("packet received\n");  String GetText = getText(); buf = GetText.getBytes();   I haven't tried a lot because i can't find any fixes relating to my kind of problem.  Thanks in advance for the help.
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?
51760
I have been investigating a potential heap size problem in our production code, and I wanted to recreate some simple elements through the developer console.  To cause a heap size exception, I would select every standard field from account for 50,000 accounts into a list.  System.debug('Heap size before query = ' + Limits.getHeapSize() + ', out of maximum ' + Limits.getLimitHeapSize()); List&lt;Account&gt; accs = [select AccountNumber, AccountSource, AnnualRevenue, BillingCity, BillingCountry, BillingPostalCode, BillingState, BillingStreet,                              CreatedById, CreatedDate, CurrencyIsoCode, Description, Fax, FirstName, Id, Industry, IsCustomerPortal,                              IsDeleted, IsPersonAccount, Jigsaw, JigsawCompanyId, LastActivityDate, LastModifiedById, LastModifiedDate, LastName,                              MasterRecordId, Name, NumberOfEmployees, OwnerId, Ownership, ParentId, PersonBirthdate, PersonContactId, PersonEmail,                              PersonEmailBouncedDate, PersonEmailBouncedReason, PersonHomePhone, PersonLastCURequestDate, PersonLastCUUpdateDate, PersonLeadSource,                              PersonMailingCity, PersonMailingCountry, PersonMailingPostalCode, PersonMailingState, PersonMailingStreet, PersonMobilePhone, PersonOtherCity,                              PersonOtherCountry, PersonOtherPostalCode, PersonOtherState, PersonOtherStreet, PersonTitle, Phone, Rating, RecordTypeId, Salutation, ShippingCity,                              ShippingCountry, ShippingPostalCode, ShippingState, ShippingStreet, Sic, SicDesc, Site, SystemModstamp, TickerSymbol, Type, Website                       from account                       limit 50000]; System.debug('Heap size after query = ' + Limits.getHeapSize() + ', out of maximum ' + Limits.getLimitHeapSize());   This is a full copy sandbox and there are over 50,000 accounts. My expectation was that this would fail with a heap size limit exception.  Instead I get the output:  USER_DEBUG [1]|DEBUG|Heap size before query = 1069, out of maximum 6000000 USER_DEBUG [12]|DEBUG|Heap size after query = 33931975, out of maximum 6000000   Notice the heap size used is 34MB and the limit 6MB but no exception occurs. I have done some more experiments and I can iterate over the list and carry on executing code with the heap size above this level.  Here are the limit usage stats which seem to show 0 heap usage.    I can't find anywhere that this is expected behaviour for the developer console. My understanding was that the limits apply in all contexts.  Can anyone shed any light on this?
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();
78597
I keep getting the System.NullPointerException: Attempt to de-reference a null object on my trigger at line 21. I've attempted to add != null to that line and I get an error too. Please see the code below.  trigger UpdateDMAAccount on Account (before insert, before update) { //get set of Postal Codes from leads to be inserted or updated Set&lt;String&gt; BillingpostalCodes = new Set&lt;String&gt;(); for(Account l : trigger.new){ if(l.BillingPostalCode != null){     BillingpostalCodes.add(l.BillingPostalCode);  } } if(BillingpostalCodes.size() &gt; 0){ //create Map of custom object records with Name (PostalCode) as key Map&lt;String,DMA_Value__c&gt; validBillingPostalCode = new Map&lt;String,DMA_Value__c&gt;(); for(DMA_Value__c obj : [SELECT Id, Name, DMA_Value__c FROM DMA_Value__c WHERE Name IN :BillingpostalCodes]){     validBillingPostalCode.put(obj.Name,obj); } for(Account l : trigger.new){     if((Trigger.isInsert || trigger.oldMap.get(l.Id).BillingPostalCode != l.BillingPostalCode) &amp;&amp; validBillingPostalCode.containsKey(l.BillingPostalCode)){          l.DMA__c = validBillingPostalCode.get(l.BillingPostalCode).DMA_Value__c;     }     else if(trigger.oldMap.get(l.Id).BillingPostalCode != NULL || l.BillingPostalCode &amp;&amp; !validBillingPostalCode.containsKey(l.BillingPostalCode)){         //blank value if new PostalCode does not match a record in the Map         l.DMA__c = Null;     }   }  } }
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)
120685
It seems to me that a lot of my debugging time is spent chasing down null-reference exceptions in complex statements. For instance:  For Each game As IHomeGame in _GamesToOpen.GetIterator()   Why, when I get a NullReferenceException, can I get the line number in the stack trace, but not the name of the object that equals null. In other words, why:  Object reference not set to an instance of an object.   instead of  _GamesToOpen is not set to an instance of an object.   or  Anonymous object returned by _GamesToOpen.GetIterator() is null.   or  game was set to null.   Is this strictly a design choice, meant to protect the anonymity of the code or is there a compelling reason in compiler design not to include this information in the debug-time exception?
89543
I have a small server program that accepts connections on a TCP or local UNIX socket, reads a simple command and (depending on the command) sends a reply. The problem is that the client may have no interest in the answer and sometimes exits early.  So writing to that socket will cause a SIGPIPE and make my server crash. What's the best practice to prevent the crash here? Is there a way to check if the other side of the line is still reading? (select() doesn't seem to work here as it always says the socket is writable). Or should I just catch the SIGPIPE with a handler and ignore it?
90469
It seems like when I call getMessage on a thrown AuraHandledException, I see "Script-thrown Exception" instead of the message that I have set. Any idea why this may be happening?  Controller:       @AuraEnabled     public static Conversation__c makeConversation(String tonum, String objid)     {         if (tonum.length() != 10)             throw new AuraHandledException('ToNumber length invalid.');     }   TestController:  @isTest     static void testMakeConversationInvalidTo()     {         Boolean testPass = false;         String fromNumber = '1234567890';         String toNumber = '1';          List&lt;ConversationController.ConversationWrapper&gt; test =    ConversationController.getConversations();         System.assertEquals(0, test.size());         try {             ConversationController.makeConversation(toNumber, '0');         } catch (AuraHandledException e) {             System.debug(e.getMessage());             System.debug(e.getTypeName());             System.assert(e.getMessage().contains('ToNumber length invalid'));             testPass = true;         }     }   Return:  16:26:28:477 USER_DEBUG [320]|DEBUG|Script-thrown exception 16:26:28:477 USER_DEBUG [321]|DEBUG|System.AuraHandledException
120476
I'm looking into a mechanism for serialize data to be passed over a socket or shared-memory in a language-independent mechanism.  I'm reluctant to use XML since this data is going to be very structured, and encoding/decoding speed is vital.  Having a good C API that's liberally licensed is important, but ideally there should be support for a ton of other languages.  I've looked at  and .  Am I on the right track?  Is there something better?  Should I just implement my own packed structure and not look for some standard?
25016
I am getting the following error trying to read from a socket. I'm doing a readInt() on that InputStream, and I am getting this error. Perusing the documentation this suggests that the client part of the connection closed the connection. In this scenario, I am the server.  I have access to the client log files and it is not closing the connection, and in fact its log files suggest I am closing the connection. So does anybody have an idea why this is happening? What else to check for? Does this arise when there are local resources that are perhaps reaching thresholds?    I do note that I have the following line:  socket.setSoTimeout(10000);   just prior to the readInt(). There is a reason for this (long story), but just curious, are there circumstances under which this might lead to the indicated error? I have the server running in my IDE, and I happened to leave my IDE stuck on a breakpoint, and I then noticed the exact same errors begin appearing in my own logs in my IDE.  Anyway, just mentioning it, hopefully not a red herring. :-(
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)
95490
Why am I getting an out of memory exception?  So this dies in C# on the first time through:  splitBitmaps.Add(neededImage.Clone(rectDimensions, neededImage.PixelFormat));   Where splitBitmaps is a List&lt;BitMap&gt; BUT this works in VB for at least 4 iterations:  arlSplitBitmaps.Add(Image.Clone(rectDimensions, Image.PixelFormat))  Where arlSplitBitmaps is a simple array list.  (And yes I've tried arraylist in c#)  This is the fullsection:  for (Int32 splitIndex = 0; splitIndex &lt;= numberOfResultingImages - 1; splitIndex++) {    Rectangle rectDimensions;    if (splitIndex &lt; numberOfResultingImages - 1)    {     rectDimensions = new Rectangle(splitImageWidth * splitIndex, 0,        splitImageWidth, splitImageHeight);    }    else    {     rectDimensions = new Rectangle(splitImageWidth * splitIndex, 0,       sourceImageWidth - (splitImageWidth * splitIndex), splitImageHeight);    }     splitBitmaps.Add(neededImage.Clone(rectDimensions, neededImage.PixelFormat));    }   neededImage is a Bitmap by the way.   I can't find any useful answers on the intarweb, especially not why it works just fine in VB.  Update:  I actually found a reason (sort of) for this working but forgot to post it.  It has to do with converting the image to a bitmap instead of just trying to clone the raw image if I remember.
113031
I have a dll that must be useable from C etc, so I cant use string objects etc as a normal would, but I'm not sure on how to do this safely..  const char *GetString() {     std::stringstream ss;     ss &lt;&lt; "The random number is: " &lt;&lt; rand();     return ss.str().c_str(); }   could the c string be destroyed when ss falls off the stack? I'm  assuming so...  Another option may be to create a new string on the heap, but what is going to deallocate that?  const char *GetString() {     std::stringstream ss;     ss &lt;&lt; "The random number is: " &lt;&lt; rand();     char *out = new char[ss.str().size()];     strcpy(ss.str().c_str(), out);     return out;//is out ever deleted? }   The same goes for pointers to other things as well as strings.
16626
I'm trying to read binary data using C#. I have all the information about the layout of the data in the files I want to read. I'm able to read the data "chunk by chunk", i.e. getting the first 40 bytes of data converting it to a string, get the next 40 bytes.  Since there are at least three slightly different version of the data, I would like to read the data directly into a struct. It just feels so much more right than by reading it "line by line".  I have tried the following approach but to no avail:  StructType aStruct; int count = Marshal.SizeOf(typeof(StructType)); byte[] readBuffer = new byte[count]; BinaryReader reader = new BinaryReader(stream); readBuffer = reader.ReadBytes(count); GCHandle handle = GCHandle.Alloc(readBuffer, GCHandleType.Pinned); aStruct = (StructType) Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(StructType)); handle.Free();   The stream is an opened FileStream from which I have began to read from. I get an AccessViolationException when using Marshal.PtrToStructure.  The stream contains more information than I'm trying to read since I'm not interested in data at the end of the file.  The struct is defined like:  [StructLayout(LayoutKind.Explicit)] struct StructType {     [FieldOffset(0)]     public string FileDate;     [FieldOffset(8)]     public string FileTime;     [FieldOffset(16)]     public int Id1;     [FieldOffset(20)]     public string Id2; }   The examples code is changed from original to make this question shorter.  How would I read binary data from a file into a struct?
90464
We noticed that lots of bugs in our software developed in C# (or Java) cause a NullReferenceException.  Is there a reason why "null" has even been included in the language?  After all, if there were no "null", I would have no bug, right?  In other words, what feature in the language couldn't work without null?
112802
i've got some binary data which i want to save as an image. When i try to save the image, it throws an exception if the memory stream used to create the image, was closed before the save. The reason i do this is because i'm dynamically creating images and as such .. i need to use a memory stream.  this is the code:  [TestMethod] public void TestMethod1() {     // Grab the binary data.     byte[] data = File.ReadAllBytes("Chick.jpg");      // Read in the data but do not close, before using the stream.     Stream originalBinaryDataStream = new MemoryStream(data);     Bitmap image = new Bitmap(originalBinaryDataStream);     image.Save(@"c:\test.jpg");     originalBinaryDataStream.Dispose();      // Now lets use a nice dispose, etc...     Bitmap2 image2;     using (Stream originalBinaryDataStream2 = new MemoryStream(data))     {         image2 = new Bitmap(originalBinaryDataStream2);     }      image2.Save(@"C:\temp\pewpew.jpg"); // This throws the GDI+ exception. }   Does anyone have any suggestions to how i could save an image with the stream closed? I cannot rely on the developers to remember to close the stream after the image is saved. In fact, the developer would have NO IDEA that the image was generated using a memory stream (because it happens in some other code, elsewhere).  I'm really confused :(
72722
getRealPath() is returning the actual path in the local system, but returns null when deployed with a .war file.  &lt;%@ page import="java.io.*" %&gt; &lt;%@ page contentType="text/html;charset=ISO-8859-1" %&gt;  &lt;% int iLf = 10; char cLf = (char)iLf; String a= application.getResource("/"); //String myfile = application.getRealPath("/")+ "generate.xml"; //String myfile = request.getContextPath()+"generate.xml"; //String myfile = request.getRealPath("/")+"generate.xml";  out.println(myfile);     File outputFile = new File(myfile); outputFile.createNewFile(); FileWriter outfile = new FileWriter(outputFile); outfile.write(" &lt;?xml version='1.0' encoding='UTF-8'?&gt; "+cLf); outfile.write(" &lt;playlist version='1' xmlns = 'http://xspf.org/ns/0/' &gt; " +cLf); outfile.write(" &lt;title&gt;My Band Rocks Your Socks&lt;/title&gt; "+cLf);  outfile.write("&lt;trackList&gt;"+cLf);  %&gt;  &lt;%! String[] sports; %&gt;  &lt;%     sports = request.getParameterValues("sports");      out.println("&lt;html&gt;&lt;body&gt;&lt;h1&gt;hello&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;");      if (sports != null)     {           for (int i = 0; i &lt; sports.length; i++)          {                // outfile.writeln (sports[i]);                String total=sports[i];               String[] sa=total.split("[,]");               // String[] sub=new String();               outfile.write("&lt;track&gt;"+cLf);               for (int j=0;j&lt;sa.length;j++)               {                 // outfile.writeln(sa[j]);                 // outfile.writeln("sa["+j+"]="+sa[j]);                 if( j == 0)                 {                      outfile.write("&lt;location&gt;" + sa[0] +"&lt;/location&gt;"+cLf);                  }                 else if (j == 1)                      {                         outfile.write("&lt;image&gt;" + sa[1] +"&lt;/image&gt;"+cLf);                       }                      else if( j==2)                           {                             outfile.write("&lt;title&gt;" + sa[2] +"&lt;/title&gt;"+cLf);                           }                 }// end of inner for loop()                       outfile.write("&lt;/track&gt;"+cLf);          //outfile.writeln();       }// end of outer for()     }      //else outfile.writeln ("&lt;b&gt;none&lt;b&gt;");    outfile.write(" &lt;/trackList&gt; "+cLf);   outfile.write(" &lt;/playlist&gt; "+cLf);   outfile.close();    %&gt; &lt;object type="application/x-shockwave-flash" width="400" height="170"           data="xspf_player.swf?playlist_url=generate.xml"&gt;           &lt;param name="movie" value="xspf_player.swf?playlist_url=generate.xml" /&gt;  &lt;/object&gt;   Can anyone provide me with an alternative for this? It would be very helpful if you showed some sample code too.