0

When I am try to run a thread then it is giving following error

startApp threw an Exception
java.lang.NullPointerException
java.lang.NullPointerException
      at threadlearn.Midlet.startApp(Midlet.java:28)

MIDlet.java

public class Midlet extends MIDlet {
    ThreadClass th;

    public void startApp() {
        th.startThread();
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }
}

class ThreadClass implements Runnable{ 
    Thread t;

    ThreadClass() {

        t = new Thread(this);
    }

    public void startThread() {
        t.start();
    }

    public void run() {
        System.out.println("We are in Thread");
    }          
}
vusan
  • 5,221
  • 4
  • 46
  • 81
Pawan Chaurasiya
  • 881
  • 2
  • 16
  • 30
  • 3
    `th` is not initialized, assign some value to it: `ThreadClass th = new ThreadClass();` – hoaz Mar 13 '14 at 12:44
  • For the next error: the error message tells you that the error happened in method Midlet.startApp in the file Midlet.java at line 28, and that something in null when it should not. Now it is a small step to find out that 'th' was probably null. – Meier Mar 13 '14 at 14:17

1 Answers1

0

As hoaz says, you need to initialize your object.

Also, your startThread() method is redundant. Why not just call start?

Anyway, it's considered bad practice to have threads start themselves. So I propose this rewrite of your code:

public class Midlet extends MIDlet {
 ThreadClass th = null;
 Thread myThread = null;

 public void startApp() {
  if (th==null) {
   th = new ThreadClass();
   myThread = new Thread(th);
  }
  myThread.start();
 }

 public void pauseApp() {
 }

 public void destroyApp(boolean unconditional) {
 }
}

class ThreadClass implements Runnable{ 

 ThreadClass() {
 }

 public void run() {
  System.out.println("We are in Thread");
 }          
}
mr_lou
  • 1,910
  • 2
  • 14
  • 26