Java ME, why does this code throw an exception?

Discussion in 'Java' started by Jeff, Jun 10, 2007.

  1. Jeff

    Jeff Guest

    Java ME

    The code below compiles but it crashes during execution. Look for "<---
    crash here" in the code, that tells where the crash occur. The error is a
    NullPointerException. The problem is that I don't know what causing the
    exception. When I don't know what's causing the error, it is difficult to
    fix it.

    Any suggestions what may cause this exception?

    public class HelloWorld extends MIDlet implements CommandListener {
    private String[] task;

    public void commandAction(Command c, Displayable d) {
    if (c == okCommand) {
    task[0] = "xxxxxx"; <--- crash here
    task[1] = "ddddddddd";
    task[2] = "eeeeeeeeee";
    try {
    Image iconGreen = Image.createImage("/icon-green.png");
    Image iconRed = Image.createImage("/icon-red.png");
    imageArray[0] = iconGreen;
    imageArray[1] = iconRed;
    imageArray[2] = iconGreen;
    } catch ( err) {
    taskList = new List("My Tasks", Choice.IMPLICIT, task,
    Jeff, Jun 10, 2007
    1. Advertisements

  2. I am not experienced with J2ME, but experience with
    J2SE suggests a number of things that might be done
    to trace the problem..
    try {
    // NEVER ignore exceptions in code that fails for
    // reasons not known!
    } catch (Exception e) {
    // should catch the NPE (and all other exceptions)

    Andrew Thompson

    Message posted via
    Andrew Thompson, Jun 10, 2007
    1. Advertisements

  3. hey there Jeff,
    once an array variable has been declared, memory may be allocated to
    it. It can be done with the "new" operator, that allocates memory for
    the String object.

    public class HelloWorld {

    private String[] task = new String[10]; <---- you need to initilize
    the array here with "new" operator

    public HelloWorld(){

    public void commandAction(String c) {

    if (c == "Test") {
    task[0] = "xxxxxx"; <----- now it does not trow an
    task[1] = "ddddddddd";
    task[2] = "eeeeeeeeee";

    public static void main(String args[]){
    new HelloWorld();

    Emre SIMTAY
    The Billboard Hot 100, Jun 10, 2007
  4. Initialize the task array properly. Something like task = new


    Blake Matheny, Jun 10, 2007
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.