Help with basic threading / message handling (NullPointerException)


Last Updated:

  1. EightBitSpade

    EightBitSpade Member This Topic's Starter

    Joined:
    Sep 29, 2010
    Messages:
    5
    Likes Received:
    0
    Hello everyone! I'm relatively new to java programming and developing on android, but I realized that I would need to learn how to handle threads if I ever wanted to make interactive games on android. So I designed a simple app to see if I could figure it out. Unfortunately, it does not work.

    Here's the app I came up with: It should simply display one text view on the screen. A handler should be set up in the main thread that will respond to messages - if the message sent contains the value 1, then it should set the text of this text view to "Start." If it receives a 2, then it should change that text to "It worked!"

    That message should come from the other, secondary thread, which should perform like this: It contains one variable, an int named counter that starts off at 0. Then, if the counter is 0, the counter is set to 1, and the value of counter is sent to the main thread handler in the what field of a message called m (where the main thread handler should receive it and change the text view text to "Start."). Then, the thread should sleep for 5 seconds. When it resumes and runs a second time, it should change the value of counter to 2, and send that to the main thread handler, which would then change the text view text to "It worked!"

    Here is the code:
    Code (Text):
    1.  
    2.    package com.thread.test;
    3.  
    4.     import android.app.Activity;
    5.     import android.os.Bundle;
    6.     import android.os.Handler;
    7.     import android.os.Message;
    8.     import android.widget.TextView;
    9.  
    10.     public class threadTest extends Activity {
    11.        
    12.        //Fields
    13.        TextView myTextView = null;
    14.        
    15.        Thread refreshThread = null;
    16.        
    17.        //Handler
    18.        Handler updateHandler = new Handler()
    19.        {
    20.        
    21.           //Handle message routine
    22.           //This gets called on every message that is recieved
    23.          
    24.           //@Override
    25.           public void handleMessage(Message msg)
    26.           {
    27.              if (msg.what == 1)
    28.              {
    29.                 myTextView.setText("Start");
    30.              }
    31.              if (msg.what == 2)
    32.              {
    33.                 myTextView.setText("It Worked!");
    34.              }
    35.              super.handleMessage(msg);
    36.           }
    37.        };
    38.        
    39.         /** Called when the activity is first created. */
    40.         @Override
    41.         public void onCreate(Bundle savedInstanceState) {
    42.            //View referencing
    43.            this.myTextView = (TextView)findViewById(R.id.myTextView);
    44.            
    45.             super.onCreate(savedInstanceState);
    46.             setContentView(R.layout.main);
    47.            
    48.             //Thread creation
    49.             this.refreshThread = new Thread(new updateThread());
    50.             this.refreshThread.start();
    51.         }
    52.        
    53.         class updateThread implements Runnable{
    54.            private int counter = 0;
    55.            //@Override
    56.            public void run()
    57.            {
    58.               while(!Thread.currentThread().isInterrupted())
    59.               {
    60.                  Message m = new Message();
    61.                  if (this.counter == 1)
    62.                  {
    63.                     this.counter = 2;
    64.                     m.what = this.counter;
    65.                     threadTest.this.updateHandler.sendMessage(m);
    66.                  }
    67.                  if (this.counter == 0)
    68.                  {
    69.                     this.counter = 1;
    70.                     m.what = this.counter;
    71.                     threadTest.this.updateHandler.sendMessage(m);
    72.                  }
    73.      
    74.                  try{
    75.                     Thread.sleep(5000);
    76.                  } catch (InterruptedException e) {
    77.                     Thread.currentThread().interrupt();
    78.                  }
    79.               }
    80.            }
    81.         }//End class updateThread
    82.        
    83.     }
    84.  
    As soon as I try to run it, I get a force close error. I checked my logcat, and here is what I got:

    Code (Text):
    1.  
    2. 09-30 00:24:47.883: INFO/ActivityManager(71): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.thread.test/.threadTest }
    3.  
    4. 09-30 00:24:48.543: WARN/ActivityManager(71): Activity pause timeout for HistoryRecord{43f9cf00 com.android.launcher/com.android.launcher2.Launcher}
    5.  
    6. 09-30 00:24:48.783: INFO/ActivityManager(71): Start proc com.thread.test for activity com.thread.test/.threadTest: pid=250 uid=10039 gids={1015}
    7.  
    8. 09-30 00:24:50.453: DEBUG/dalvikvm(71): GREF has increased to 301
    9. 09-30 00:24:50.483: DEBUG/AndroidRuntime(250): Shutting down VM
    10. 09-30 00:24:50.483: WARN/dalvikvm(250): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
    11. 09-30 00:24:50.552: ERROR/AndroidRuntime(250): FATAL EXCEPTION: main
    12. 09-30 00:24:50.552: ERROR/AndroidRuntime(250): java.lang.NullPointerException
    13. 09-30 00:24:50.552: ERROR/AndroidRuntime(250):     at com.thread.test.threadTest$1.handleMessage(threadTest.java:33)
    14. 09-30 00:24:50.552: ERROR/AndroidRuntime(250):     at android.os.Handler.dispatchMessage(Handler.java:99)
    15. 09-30 00:24:50.552: ERROR/AndroidRuntime(250):     at android.os.Looper.loop(Looper.java:123)
    16. 09-30 00:24:50.552: ERROR/AndroidRuntime(250):     at android.app.ActivityThread.main(ActivityThread.java:4627)
    17. 09-30 00:24:50.552: ERROR/AndroidRuntime(250):     at java.lang.reflect.Method.invokeNative(Native Method)
    18. 09-30 00:24:50.552: ERROR/AndroidRuntime(250):     at java.lang.reflect.Method.invoke(Method.java:521)
    19. 09-30 00:24:50.552: ERROR/AndroidRuntime(250):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
    20. 09-30 00:24:50.552: ERROR/AndroidRuntime(250):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
    21. 09-30 00:24:50.552: ERROR/AndroidRuntime(250):     at dalvik.system.NativeStart.main(Native Method)
    22. 09-30 00:24:50.683: WARN/ActivityManager(71):   Force finishing activity com.thread.test/.threadTest
    23.  
    I've never seen any of this before, but here is my interpretation: It seems that the big problem is that there is an uncaught exception, and that exception is a java.lang.NullPointerException located somewhere in my handleMessage method.

    I did some homework by looking around on this forum first, and found out that a java.lang.NullPointerException occurs when you try to access the fields or methods of an object that you haven't instantiated yet. handleMessage only uses msg.what and myTextView, and of the two, it seems more likely that I have messed something up with msg.what.

    I'm trying to learn how all of this works, so if someone could just give me a few pointers or point me in the right direction or to a good resource, I would really appreciate it! :) Thank you for your time!
     

    Advertisement
  2. jonbonazza

    jonbonazza Well-Known Member

    Joined:
    Jul 13, 2010
    Messages:
    1,934
    Likes Received:
    458
    remove the super.handleMessage(msg); line.
     
  3. EightBitSpade

    EightBitSpade Member This Topic's Starter

    Joined:
    Sep 29, 2010
    Messages:
    5
    Likes Received:
    0
    I found out my problem, and thought I would post the solution up so that it might help someone else someday. The problem, which I found through using the debugging tools, was that the reference variable myTextView was remaining null. That came form putting the line

    this.myTextView = (TextView)findViewById(R.id.myTextView);

    Before this line in the onCreate method:

    setContentView(R.layout.main);

    As soon as I moved it after that line, everything worked perfectly. Thanks for your help! :)
     

Share This Page

Loading...