I have an application which crashed 2 times randomly with a weird logcat message.  Here is it (both crashes are identical):  05-17 15:45:56.792 31082-31082/? E/AndroidRuntime: FATAL EXCEPTION: main                                                Process: net.mycustom.application, PID: 31082                                                java.lang.NullPointerException: Attempt to invoke virtual method 'net.mycustom.application.tools.i net.mycustom.application.MyService.a(java.lang.Integer)' on a null object reference                                                    at net.mycustom.application.tools.a.b.onCreateDialog(Unknown Source:83)                                                    at android.app.DialogFragment.onGetLayoutInflater(DialogFragment.java:411)                                                    at android.app.Fragment.performGetLayoutInflater(Fragment.java:1339)                                                    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1298)                                                    at android.app.FragmentManagerImpl.addAddedFragments(FragmentManager.java:2426)                                                    at android.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2205)                                                    at android.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2161)                                                    at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2062)                                                    at android.app.FragmentManagerImpl$1.run(FragmentManager.java:738)                                                    at android.os.Handler.handleCallback(Handler.java:873)                                                    at android.os.Handler.dispatchMessage(Handler.java:99)                                                    at android.os.Looper.loop(Looper.java:280)                                                    at android.app.ActivityThread.main(ActivityThread.java:6706)                                                    at java.lang.reflect.Method.invoke(Native Method)                                                    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)   I have files in net/mycustom/application/tools (but there is nothing like "i").  Also I have a service here: net/mycustom/application/MyService.java (there is nothing like "a" in this service.)  How can I hunt down this issue? (Unknown source?)
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?
108141
I'm relatively new to Threading in Java and I've noticed that everytime I use Thread.sleep() I have to catch InterrupetdException.  What kind of behaviour causes this, and in simple applications where I have a monitor thread can I just Ignore the exception?
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?
60003
I've got a few methods that should call System.exit() on certain inputs. Unfortunately, testing these cases causes JUnit to terminate! Putting the method calls in a new Thread doesn't seem to help, since System.exit() terminates the JVM, not just the current thread. Are there any common patterns for dealing with this? For example, can I subsitute a stub for System.exit()?   [EDIT] The class in question is actually a command-line tool which I'm attempting to test inside JUnit. Maybe JUnit is simply not the right tool for the job? Suggestions for complementary regression testing tools are welcome (preferably something that integrates well with JUnit and EclEmma).
57448
So, I've been spending considerable more time on SO recently than I normally have, and one thing that I've noticed is quite a few people saying stuff like "There's a Null Pointer Error in this block of code, please help me fix it", with a huge amount of code posted, and no real clue as to where the NPE is. So my question is, what can we do to accomplish 2 goals?   Help the person asking the question become a better programmer. Help them to solve their problems.
118194
I've seen the following code many times:  try {     ... // some code } catch (Exception ex) {     ... // Do something     throw new CustomException(ex);      // or     // throw;      // or     // throw ex; }   Can you please explain the purpose of re-throwing an exception? Is it following a pattern/best practice in exception handling? (I've read somewhere that it's called "Caller Inform" pattern?)
98616
I can hookup to AppDomain.CurrentDomain.UnhandledException to log exceptions from background threads, but how do I prevent them terminating the runtime?
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();
123913
App version: 1.0.52  When you edit a question and rotate the screen while the "Getting preview" or "Posting edit" dialog is showing the app will crash.  12-25 21:38:07.033 E/AndroidRuntime(4768): FATAL EXCEPTION: main 12-25 21:38:07.033 E/AndroidRuntime(4768): Process: com.stackexchange.marvin, PID: 4768 12-25 21:38:07.033 E/AndroidRuntime(4768): java.lang.IllegalArgumentException: View=com.android.internal.policy.impl.PhoneWindow$DecorView{42440ba0 V.E..... R......D 0,0-684,192} not attached to window manager 12-25 21:38:07.033 E/AndroidRuntime(4768): at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:370) 12-25 21:38:07.033 E/AndroidRuntime(4768): at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:299) 12-25 21:38:07.033 E/AndroidRuntime(4768): at android.view.WindowManagerImpl.removeViewImmediate(WindowManagerImpl.java:84) 12-25 21:38:07.033 E/AndroidRuntime(4768): at android.app.Dialog.dismissDialog(Dialog.java:329) 12-25 21:38:07.033 E/AndroidRuntime(4768): at android.app.Dialog.dismiss(Dialog.java:312) 12-25 21:38:07.033 E/AndroidRuntime(4768): at com.stackexchange.marvin.core.OperationThatCanFail$1.onPostExecute(OperationThatCanFail.java:81) 12-25 21:38:07.033 E/AndroidRuntime(4768): at com.stackexchange.marvin.core.OperationThatCanFail$1.onPostExecute(OperationThatCanFail.java:67) 12-25 21:38:07.033 E/AndroidRuntime(4768): at android.os.AsyncTask.finish(AsyncTask.java:632) 12-25 21:38:07.033 E/AndroidRuntime(4768): at android.os.AsyncTask.access$600(AsyncTask.java:177) 12-25 21:38:07.033 E/AndroidRuntime(4768): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645) 12-25 21:38:07.033 E/AndroidRuntime(4768): at android.os.Handler.dispatchMessage(Handler.java:102) 12-25 21:38:07.033 E/AndroidRuntime(4768): at android.os.Looper.loop(Looper.java:136) 12-25 21:38:07.033 E/AndroidRuntime(4768): at android.app.ActivityThread.main(ActivityThread.java:5097) 12-25 21:38:07.033 E/AndroidRuntime(4768): at java.lang.reflect.Method.invokeNative(Native Method) 12-25 21:38:07.033 E/AndroidRuntime(4768): at java.lang.reflect.Method.invoke(Method.java:515) 12-25 21:38:07.033 E/AndroidRuntime(4768): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) 12-25 21:38:07.033 E/AndroidRuntime(4768): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) 12-25 21:38:07.033 E/AndroidRuntime(4768): at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132) 12-25 21:38:07.033 E/AndroidRuntime(4768): at dalvik.system.NativeStart.main(Native Method) 12-25 21:38:07.035 W/ActivityManager(27384):   Force finishing activity com.stackexchange.marvin/.ui.AskOrEditQuestionActivity
84853
Comment on Duplicate Reference: Why would this be marked duplicate when it was asked years prior to the question referenced as a duplicate?  I also believe the question, detail, and response is much better than the referenced question.  I've been a C++ programmer for quite a while but I'm new to Java and new to Eclipse.  I want to use the  to visualize some data I'm working with.  This code is organized like this:  ./com ./com/touchgraph ./com/touchgraph/graphlayout ./com/touchgraph/graphlayout/Edge.java ./com/touchgraph/graphlayout/GLPanel.java ./com/touchgraph/graphlayout/graphelements ./com/touchgraph/graphlayout/graphelements/GESUtils.java ./com/touchgraph/graphlayout/graphelements/GraphEltSet.java ./com/touchgraph/graphlayout/graphelements/ImmutableGraphEltSet.java ./com/touchgraph/graphlayout/graphelements/Locality.java ./com/touchgraph/graphlayout/graphelements/TGForEachEdge.java ./com/touchgraph/graphlayout/graphelements/TGForEachNode.java ./com/touchgraph/graphlayout/graphelements/TGForEachNodePair.java ./com/touchgraph/graphlayout/graphelements/TGNodeQueue.java ./com/touchgraph/graphlayout/graphelements/VisibleLocality.java ./com/touchgraph/graphlayout/GraphLayoutApplet.java ./com/touchgraph/graphlayout/GraphListener.java ./com/touchgraph/graphlayout/interaction ./com/touchgraph/graphlayout/interaction/DragAddUI.java ./com/touchgraph/graphlayout/interaction/DragMultiselectUI.java ./com/touchgraph/graphlayout/interaction/DragNodeUI.java ./com/touchgraph/graphlayout/interaction/GLEditUI.java ./com/touchgraph/graphlayout/interaction/GLNavigateUI.java ./com/touchgraph/graphlayout/interaction/HVRotateDragUI.java ./com/touchgraph/graphlayout/interaction/HVScroll.java ./com/touchgraph/graphlayout/interaction/HyperScroll.java ./com/touchgraph/graphlayout/interaction/LocalityScroll.java ./com/touchgraph/graphlayout/interaction/RotateScroll.java ./com/touchgraph/graphlayout/interaction/TGAbstractClickUI.java ./com/touchgraph/graphlayout/interaction/TGAbstractDragUI.java ./com/touchgraph/graphlayout/interaction/TGAbstractMouseMotionUI.java ./com/touchgraph/graphlayout/interaction/TGAbstractMousePausedUI.java ./com/touchgraph/graphlayout/interaction/TGSelfDeactivatingUI.java ./com/touchgraph/graphlayout/interaction/TGUIManager.java ./com/touchgraph/graphlayout/interaction/TGUserInterface.java ./com/touchgraph/graphlayout/interaction/ZoomScroll.java ./com/touchgraph/graphlayout/LocalityUtils.java ./com/touchgraph/graphlayout/Node.java ./com/touchgraph/graphlayout/TGAbstractLens.java ./com/touchgraph/graphlayout/TGException.java ./com/touchgraph/graphlayout/TGLayout.java ./com/touchgraph/graphlayout/TGLensSet.java ./com/touchgraph/graphlayout/TGPaintListener.java ./com/touchgraph/graphlayout/TGPanel.java ./com/touchgraph/graphlayout/TGPoint2D.java ./com/touchgraph/graphlayout/TGScrollPane.java ./TG-APACHE-LICENSE.txt ./TGGL ReleaseNotes.txt ./TGGraphLayout.html ./TGGraphLayout.jar   How do I add this project in Eclipse and get it compiling and running quickly?
77222
I have a really simple Java class that effectively decorates a Map with input validation, with the obvious void set() and String get() methods.  I'd like to be able to effectively call those methods and handle return values and exceptions from outside the JVM, but still on the same machine Update: the caller I have in mind is not another JVM; thanks @Dave Ray  My implementation considerations are typical    performance ease of implementation and maintenance (simplicity?) reliability flexibility (i.e. can I call from a remote machine, etc.)   Is there a 'right way?' If not, what are my options, and what are the pro/cons for each?  (Stuff people have actually done and can provide real-life feedback on would be great!)
105631
Please consider the below scenario:   I have an Application__c object. I have a trigger on that (for simplicity, coded directly in trigger) which does one thing if the record name is Error then throws exception.     trigger ApplicationTrigger on Application__c (before insert, after update){          if(trigger.new[0].Name == 'Error'){             Application__c application;             System.debug(application.Name);         } }    Now I am running below code:     Now notice the catch statement is not executing, means system was not able to catch the exception. It came as the Fatal Error.   This is kind of a big issue where if there is null pointer or any other exception in trigger and exception handling code will not be able to do anything. Not even logging since it never reaches to catch block.   Let me know if you guys ever faced such situation and if yes what you did to make sure that it is properly caught.
103112
When and why would somebody do the following:  doSomething( (MyClass) null );   Have you ever done this? Could you please share your experience?
48842
I'm creating my first full framework using Selenium and TestNG and recently implemented the ability to have logging enabled which will track every action (before and after).  public class CustomLogs {     //Set Logging_Level to "Debug" to enable logging     public String Logging_Level = "OFF";      public void Log(String message) {         if (Logging_Level == "Debug")         {System.out.println(message);         } else {         }     } }   Then, in my page objects, EVERY action method has a log statement before and after EVERY action.  public class LoginPage extends BrowserConfig {      final WebDriver driver;     private static CustomLogs customlogs = new CustomLogs();      //Elements on Page     @FindBy(id = "userId")     private WebElement userNameField;      //Constructor     public LoginPage(WebDriver driver) {         this.driver = driver;     }      //Fill Username     public void FillUsername(String userNameEntry) {         userNameField.clear();         customlogs.Log("Entering Username: "+userNameEntry+"...");         userNameField.sendKeys(userNameEntry);         customlogs.Log("Username entered.");   It seems like this is very beneficial, not only for debugging, but also because you can now print out every single action step, so keeping records or showing others what steps were completed is very straightforward.  But I can also see how this is cluttering the page object code.  Is this a good idea?  And/or is there a better way to do this?
90240
I have the below code:  public class CallOutForGet {      HttpRequest request=new Httprequest(); http http=new http(); request.setEndPoint('https://th-apex-http-callout.herokuapp.com/animals'); request.setmethod('GET');  HttpResponse response=http.send(request);  if(response.getStatusCode()==200){      Map&lt;String,Object&gt; results= (Map&lt;String,Object&gt;)JSON.deserializeUntyped(response.getBody());      List&lt;object&gt; animals=(List&lt;object&gt;)results.get('animals');     System.debug('Received Animals************');     for(object anim:animals){         System.debug(anim);     } }  }   This error at line -  request.setEndPoint('https://th-apex-http-callout.herokuapp.com/animals');  says expecting right parenthesis.
18923
I am trying to write a test for a trigger that is firing a future apex callout :  The trigger calls the callBillingService method from this class:  public class BillingCalloutService {     //Implement business and callout logic methods here     @Future(callout=true)     public static void callBillingService(List&lt;Id&gt; recordIds) {         List&lt;Project__c&gt; projects = [Select Id, ProjectRef__c,Billable_Amount__c from Project__c Where Id = :recordIds];          List&lt;Project__c&gt; projectsToUpdate = new List&lt;Project__c&gt;();          String username = ServiceCredentials__c.getValues('BillingServiceCredential').Username__c;         String password = ServiceCredentials__c.getValues('BillingServiceCredential').Password__c;          String auth = username + ':' + password;         String encodedAuth = EncodingUtil.base64Encode(Blob.valueOf(auth));          for(Project__c p : projects) {              BillingServiceProxy.InvoicesPortSoap11 service = new BillingServiceProxy.InvoicesPortSoap11();             service.inputHttpHeaders_x = new Map&lt;String, String&gt;();             service.inputHttpHeaders_x.put('Authorization', 'Basic ' + encodedAuth);              BillingServiceProxy.project project = new BillingServiceProxy.project();             project.username = username;             project.password = password;             project.projectRef = p.ProjectRef__c;             project.billAmount = p.Billable_Amount__c;              if(service.billProject(project).equals('ok')){                 projectsToUpdate.add(new Project__c(ProjectRef__c = p.ProjectRef__c, Status__c = 'Billed'));             }         }         shouldIRun.stopTrigger();         upsert projectsToUpdate ProjectRef__c;     } }   Error     Methods defined as TestMethod do not support Web service callouts   Test Class  @IsTest private class BillingCalloutServiceTest {      @IsTest     private static void testBillingCalloutService() {     Account a = new Account(Name = 'Acme');     insert a;     Opportunity o = new Opportunity(Name='Test', StageName='Submitted Project', AccountId=a.Id, Amount=1000, CloseDate=Date.Today());     insert o;     Project__c p = new Project__c(Status__c='Running',Start_Date__c=Date.Today(),End_Date__c=Date.Today(),Billable_Amount__c=10000,ProjectRef__c='projectX',Opportunity__c=o.Id);     insert p;      insert new ServiceCredentials__c(Name='BillingServiceCredential',Username__c='toto', Password__c='azerty');      Test.startTest();     Test.setMock(HttpCalloutMock.class, new BillingCalloutServiceMock());       p.Status__c = 'Billable';       update p;     Test.stopTest();     // runs callout and check results     p = [select Status__c from Project__c where id =: p.id];     System.assertEquals('Billed', p.Status__c);     }  }
6306
We have an error log object where we store the errors and I have a simple try catch like below... My issue is that the insert in the finally does not appear to be happening. Any advice? or is that a limitation in the try-catch error handling? list&lt;Error_Log__c&gt; error_logs = new list&lt;Error_Log__c&gt; () try {    if(status__c == '100') {       \\do something    } else {        throw new AuraHandledException('System Error');    }   } Catch (Exception e) {    Error_Log__c rec = new Error_Log__c(Name=&quot;Error Message: &quot;);    error_logs.add(rec);    throw new AuraHandledException('System Error'); } finally {   insert error_logs; }