I'm making a simple game to learn how to use Android Studio. The objective of the game is to do some simple tasks as fast as possible. In my main game screen, I have a thread that makes an int count up every second, so the player knows how much time has gone by. When the player has done all the simple tasks, the game goes to the end screen. Now I want to display the time in the endscreen, so the player knows how fast they finished. I get an error when I run the game. This is the code to run the thread every second: Timer d = new Timer(true); thread1 thread1 = new thread1(this, myCanvas); t.scheduleAtFixedRate(thread1, 0, 1000);   This is the tick function that the thread does every second: public void tick1(){     timer++; }  This is the getter for the timer: public int getTimer(){     return timer; }  When the game ends and it goes to the endscreen, I use the getTimer() to have a textview that should display the timer: err = (TextView)findViewById(R.id.textView); err.setText(&quot;Tijd: &quot;+ timer+&quot;&quot;);  This is the error message I get when I try to run it: 2021-03-06 11:18:38.153 21729-21729/com.example.test_game E/AndroidRuntime: FATAL EXCEPTION: main     Process: com.example.test_game, PID: 21729     java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test_game/com.example.test_game.Eindscherm}: java.lang.NullPointerException: Attempt to invoke virtual method 'int com.example.test_game.MyCanvas.getTimer()' on a null object reference         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3792)         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3968)         at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)         at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)         at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2307)         at android.os.Handler.dispatchMessage(Handler.java:106)         at android.os.Looper.loop(Looper.java:246)         at android.app.ActivityThread.main(ActivityThread.java:8506)         at java.lang.reflect.Method.invoke(Native Method)         at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)      Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int com.example.test_game.MyCanvas.getTimer()' on a null object reference         at com.example.test_game.Eindscherm.onCreate(Eindscherm.java:24)         at android.app.Activity.performCreate(Activity.java:8198)         at android.app.Activity.performCreate(Activity.java:8182)         at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3765)         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3968)          at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)          at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)          at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2307)          at android.os.Handler.dispatchMessage(Handler.java:106)          at android.os.Looper.loop(Looper.java:246)          at android.app.ActivityThread.main(ActivityThread.java:8506)          at java.lang.reflect.Method.invoke(Native Method)          at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
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?
113159
I'm not sure why I'm getting this error, but shouldn't this code compile, since I'm already checking to see if queue is getting initialized?   public static void Main(String[] args) {     Byte maxSize;     Queue queue;      if(args.Length != 0)     {         if(Byte.TryParse(args[0], out maxSize))             queue = new Queue(){MaxSize = maxSize};         else             Environment.Exit(0);     }     else     {         Environment.Exit(0);     }      for(Byte j = 0; j &lt; queue.MaxSize; j++)         queue.Insert(j);     for(Byte j = 0; j &lt; queue.MaxSize; j++)         Console.WriteLine(queue.Remove()); }   So if queue is not initialized, then the for loops aren't reachable right? Since the program already terminates with Environment.Exit(0)?  Hope ya'll can give me some pointers :)  Thanks.
87780
I have a legacy WinForms Mdi App in VB.Net 2.0 which I am adding functionality to. One of the additions is a warning which needs to be raised when the current time nears a specified value (a deadline). My intention is to check the time once an hour until there is less than an hour until the deadline, then display warnings at specified intervals until the time's up.  The user needs to be able to continue to use the app up to and even after the deadline, but they need to periodically be made aware of the deadline's proximity.   The app does not use System.Threading yet and my knowledge of it is limited at this time. I do know that there are 3 different Timer() methods available:    System.Threading.Timer(), Windows.Forms.Timer() and  System.Timers.Timer()   My question is, which is the best way to go with this? I attempted to use the threaded timer, but since WinForms are not thread safe I got a run time error trying to access another class. Is it worth making the class/form thread safe? Am I completely off track?  Thanks.
915
How do you write (and run) a correct micro-benchmark in Java?  I'm looking for some code samples and comments illustrating various things to think about.  Example: Should the benchmark measure time/iteration or iterations/time, and why?  Related:
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?
12512
Here is my problem: I've got a dialog with some parameters that the user can change (via a spinner for example). Each time one of these parameters is changed, I launch a thread to update a 3D view according to the new parameter value.  If the user changes another value (or the same value again by clicking many times on the spinner arrow) while the first thread is working, I would like to abort the first thread (and the update of the 3D view) and launch a new one with the latest parameter value.  How can I do something like that?  PS: There is no loop in the run() method of my thread, so checking for a flag is not an option: the thread updating the 3D view basically only calls a single method that is very long to execute. I can't add any flag in this method asking to abort either as I do not have access to its code.
45337
I'm making a Java application with an application-logic-thread and a database-access-thread. Both of them persist for the entire lifetime of the application and both need to be running at the same time (one talks to the server, one talks to the user; when the app is fully started, I need both of them to work).  However, on startup, I need to make sure that initially the app thread waits until the db thread is ready (currently determined by polling a custom method dbthread.isReady()). I wouldn't mind if app thread blocks until the db thread was ready.  Thread.join() doesn't look like a solution - the db thread only exits at app shutdown.  while (!dbthread.isReady()) {} kind of works, but the empty loop consumes a lot of processor cycles.  Any other ideas? Thanks.
75825
I have created a program which searches for files in a source folder. If it finds any file, it processes that file and moves it to a destination folder, then looks for a new file in the source folder. It has to keep on checking the source folder for a file.  I have used a thread to look for files in the source folder. The problem I am facing is whenever any exception is thrown during file processing, the thread gets stopped. I want the thread to be running even if an exception is thrown. It has to move the file that caused the error to some other folder and look for a new file in the source folder. How can I make the thread keep on running?  Eg:  public void run() {     try {         searchfile();     }     catch(Exception e) {         e.printStackTrace();     } }  public void searchfile(){   ... }     Update :   I should be more clear in my question. Actually there are 4 source folders and 4 destination folders. I have to perform the same operation in each source &amp; destination pair. So i have created 4 threads in one class and do the operation in separate class.  class MainClass {    public static void main(String[] args){       for(int i=0;i&lt;4;i++){          SearchClass search = new SearchClass();          Thread thread = new Thread(search);          thread.start();      }    }    }  class SearchClass {    public void run() {    try {       searchfile();    } catch(Exception e) {       e.printStackTrace();    } }  public void searchfile(){ ... } }   All the thread wont stop running eventhough it caught any exception in middle. How can i do that?
29493
I'm in the process of writing a piece of code that connects to a server spawns a bunch of threads using that connection and does a bunch of "stuff".  There are certain instances where the connection fails and I need to stop everything and start from scratch with a new object.  I wanted to clean up after the object but calling thread.stop on the threads, but this method is seemingly deprecated.  What is the recommended alternative to doing this? Should I write my own cleanup and exit method for each of the threads? Set the thread to null? or something else?
117617
I need to plot the decay of my phone's battery against time over night. My starting time is 23:17:47 and my ending one is 07:05:49. I don't have any issue in changing the time format in the current one, selecting an XY chart and plotting time on the X axis.   The problem arises because Excel doesn't start the X axis at 23:17:47, but instead at 00:00:00, so my first value is drawn from the end of the graph and the goes back at the beginning when time values are over 00:00:00.   In other words, how do I set up the min time value to 23:17:47 and the max to 07:05:49 in excel?
16225
Why does it (apparently) make a difference whether I pass null as an argument directly, or pass an Object that I assigned the value null?  Object testVal = null; test.foo(testVal);    // dispatched to foo(Object) // test.foo(null);    // compilation problem -&gt; "The method foo(String) is ambiguous"     public void foo(String arg) { // More-specific     System.out.println("foo(String)"); }  public void foo(Object arg) { // Generic     System.out.println("foo(Object)"); }   In other words, why is the (commented-out) second call to foo(...) not dispatched to foo(Object)?  Update: I use Java 1.6. I could compile Hemal's code without problems, but mine still doesn't compile. The only difference I see is that Hemal's methods are static while mine are not. But I really don't see why this should make a difference...?  Update 2: Solved. I had another method foo(Runnable) in my class, so the dispatcher couldn't unambiguously select the single most specific method. (See my comment in Hemal's second answer.) Thanks everyone for your help.
20429
I installed eclipse via Ubuntu Software. When I start it, it take some seconds and then comes an error window showing the path of the error.  The following is the .log file:  !SESSION Wed May 02 12:53:28 BRT 2018 ------------------------------------------ !ENTRY org.eclipse.equinox.launcher 4 0 2018-05-02 12:53:28.587 !MESSAGE Exception launching the Eclipse Platform: !STACK java.lang.ClassNotFoundException: org.eclipse.core.runtime.adaptor.EclipseStarter     at java.base/java.net.URLClassLoader.findClass(URLClassLoader.java:466)     at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:566)     at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499)     at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:626)     at org.eclipse.equinox.launcher.Main.basicRun(Main.java:584)     at org.eclipse.equinox.launcher.Main.run(Main.java:1438)     at org.eclipse.equinox.launcher.Main.main(Main.java:1414)   What is the problem and how can I fix it?
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
66447
I have an object with a method named StartDownload(), that starts three threads.  How do I get a notification when each thread has finished executing?  Is there a way to know if one (or all) of the thread is finished or is still executing?
28335
I'm trying to make a simple idle-walk transition in Animator using Unity. I've set a script that changes the Speed value from the Animator, and it works perfectly when I move the character forward when the game is on.  The transitions work well between both animations, except that they don't start automatically after the speed has changed to greater than zero.  I've found out that it waits until the animation loop gets to it's end, which makes the game feel dull and not fluid at all.    I don't think there's an issue with the code, but I'm attaching it anyway:  #pragma strict var anim : Animator;  function Start () {     anim = GetComponent("Animator"); }  function Update () {     var move : float = Input.GetAxis ("Vertical");     anim.SetFloat("Speed",move);     transform.Rotate(0,Input.GetAxis("Horizontal"),0);     transform.Translate(0,0,(Input.GetAxis("Vertical")*Time.deltaTime*move)); }
112025
I am trying to spawn one gameobject from a list of gameobjects each time I touch the trigger with the controller.  But when I do this, all the game objects from the list spawn together at the same time. I couldn't figure out how to solve this problem and make them spawn one at a time instead, where the next touch spawns the next object in the list, and so on.    using System.Collections; using System.Collections.Generic; using UnityEngine;  public class Trigger : MonoBehaviour {      public Transform spawnPoint;     //public GameObject Prefab;     public List&lt;GameObject&gt; items = new List&lt;GameObject&gt;();      void OnTriggerEnter(Collider other)     {         //GameObject Prefab = new GameObject("prefab");          for (int i = 0; i &lt; items.Count; i++)         {             Instantiate(items[i], spawnPoint.position, spawnPoint.rotation);             Debug.Log("Hello World" +i);         }      }  }
98616
I can hookup to AppDomain.CurrentDomain.UnhandledException to log exceptions from background threads, but how do I prevent them terminating the runtime?