0

I tried to browse some pictures using the emulator (WTK2.5) using this code sample, but I got this exception message (on the showdir() function):

 java.lang.NullPointerException
 at javax.microedition.lcdui.Form.append(Form.java:641)
 at GUI.FileBrowser.showCurrDir(+151)
 at GUI.FileBrowser.<init>(FileBrowser.java:115)
 at GUI.Menu.run(Menu.java:109)

and here is my code which I put in into the Netbeans IDE: `

 /* special string that denotes upper directory accessible by this browser.
 * this virtual directory contains all roots.
 */

 public class FileBrowser extends Form implements CommandListener, Runnable         {
 private static final String[] attrList = {"Read", "Write", "Hidden"};
 private static final String[] typeList = {"Regular File", "Directory"};
 private static final String[] monthList = {"Jan", "Feb", "Mar", "Apr"};
 Displayable d;
 /* special string denotes upper directory */
 private static final String UP_DIRECTORY = "..";
 private static final String MEGA_ROOT = "/";

 /* separator string as defined by FC specification */
 private static final String SEP_STR = "/";

 /* separator character as defined by FC specification */
 private static final char SEP = '/';
 private String currDirName;
 private Command view;
 private Command creat;


 private Command delete;
 private Command creatOK;
 private Command prop;
 private Command back;
 private Command exit;
 private TextField nameInput; // Input field for new file name
 private ChoiceGroup typeInput; // Input field for file type (regular/dir)
 private Image dirIcon;
 private Image fileIcon;
 private Image[] iconList;
 private TextField viewer2;
 String login;
 String image;
 HttpConnection hc;
 DataInputStream dis;
 StringBuffer sb = new StringBuffer();
 int ch;

 public FileBrowser() {
    super("Choisir Image");
    view = new Command("View", Command.ITEM, 1);
    creat = new Command("New", Command.ITEM, 2);
    delete = new Command("Delete", Command.ITEM, 3);
    creatOK = new Command("OK", Command.OK, 1);
    prop = new Command("Properties", Command.ITEM, 2);
    back = new Command("Back", Command.BACK, 2);
    exit = new Command("Exit", Command.EXIT, 3);
    currDirName = MEGA_ROOT;
    try {
        dirIcon = Image.createImage("/dir.png");
    } catch (IOException e) {
        dirIcon = null;
    }

    try {
        fileIcon = Image.createImage("/file.png");
    } catch (IOException e) {
        fileIcon = null;
    }

    iconList = new Image[]{fileIcon, dirIcon};

    try {
        showCurrDir();
    } catch (SecurityException e) {


        addCommand(exit);
        setCommandListener(this);

    } catch (Exception e) {
        e.printStackTrace();
    }
   }
    public void commandAction(Command c, Displayable d) {
    if (c == view) {
        Thread thread = new Thread();
        thread.start();

    } else if (c == prop) {
        List curr = (List) d;
        String currFile = curr.getString(curr.getSelectedIndex());
        showProperties(currFile);
    } else if (c == creat) {
        createFile();
    } else if (c == creatOK) {
        String newName = nameInput.getString();
        image = nameInput.getString().trim();
        if ((newName == null) || newName.equals("")) {
        } else 
            executeCreateFile(newName, typeInput.getSelectedIndex() != 0);
            removeCommand(creatOK);
            removeCommand(back);
        }
    } else if (c == back) {
        showCurrDir();
    } else if (c == exit) {
        this.deleteAll();
    } else if (c == delete) {
        List curr = (List) d;
        String currFile = curr.getString(curr.getSelectedIndex());
        executeDelete(currFile);
    }
  }
  void delete(String currFile) {
    if (!currFile.equals(UP_DIRECTORY)) {
        if (currFile.endsWith(SEP_STR)) {
            checkDeleteFolder(currFile);
        } else {
            deleteFile(currFile);
            showCurrDir();
        }
    } else {

    }
 }

 private void executeDelete(String currFile) {
    Thread thread = new Thread();
    thread.start();
 }
 private void checkDeleteFolder(String folderName) {
    try {

        Enumeration content = fcdir.list("*", true);
        if (!content.hasMoreElements()) {
            fcdir.delete();
            showCurrDir();
        } else {

        }
    } catch (IOException ioe) {
        System.out.println(currDirName + folderName);

        ioe.printStackTrace();
    }
 }
 private void executeCreateFile(final String name, final boolean val) {
    Thread thread = new Thread();
    thread.start();
 }


 /**
 * Show file list in the current directory .
 */
 void showCurrDir() {
    Enumeration e;
    FileConnection currDir = null;
    List browser;

    try {
        if (MEGA_ROOT.equals(currDirName)) {
            e = FileSystemRegistry.listRoots();
            browser = new List(currDirName, List.IMPLICIT);
        } else {

            e = currDir.list();
            browser = new List(currDirName, List.IMPLICIT);
            append(UP_DIRECTORY);
            append(dirIcon);
        }

        while (e.hasMoreElements()) {
            String fileName = (String) e.nextElement();

            if (fileName.charAt(fileName.length() - 1) == SEP) {
                // This is directory
                //browser.append(fileName, dirIcon);
                append(fileName);
                append(dirIcon);

            } else {
                // this is regular file
                //browser.append(fileName, fileIcon);
                append(fileName);
                append(fileIcon);
            }
        }

       // browser.setSelectCommand(view);
        //Do not allow creating files/directories beside root
        if (!MEGA_ROOT.equals(currDirName)) {
            addCommand(delete);
            addCommand(prop);
            addCommand(creat);
            addCommand(delete);
        }

        //browser.addCommand(exit);
        addCommand(exit);

        //browser.setCommandListener(this);
        this.setCommandListener(this);

        if (currDir != null) {
            currDir.close();
        }

        // utils.StaticMidlet.disp.setCurrent(this);
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
  }

 void traverseDirectory(String fileName) {
    /* In case of directory just change the current directory
     * and show it
     */
    if (currDirName.equals(MEGA_ROOT)) {
        if (fileName.equals(UP_DIRECTORY)) {
            // can not go up from MEGA_ROOT
            return;
        }

        currDirName = fileName;
    } else if (fileName.equals(UP_DIRECTORY)) {
        // Go up one directory
        int i = currDirName.lastIndexOf(SEP, currDirName.length() - 2);

        if (i != -1) {
            currDirName = currDirName.substring(0, i + 1);
        } else {
            currDirName = MEGA_ROOT;
        }
    } else {
        currDirName = currDirName + fileName;
    }

    showCurrDir();
 }

 void showFile(String fileName) {
    try {


        if (!fc.exists()) {
            throw new IOException("File does not exists");
        }

        InputStream fis = fc.openInputStream();
        byte[] b = new byte[1024];

        int length = fis.read(b, 0, 1024);

        fis.close();
        fc.close();


        append(viewer2);
        addCommand(back);
        addCommand(exit);

        this.setCommandListener(this);

        if (length > 0) {
            viewer2.setString(new String(b, 0, length));
        }

        utils.StaticMidlet.disp.setCurrent(this);
    } catch (Exception e) {

        alert.setTimeout(Alert.FOREVER);
        utils.StaticMidlet.disp.setCurrent(alert);
    }
 }

 void deleteFile(String fileName) {
    try {

        fc.delete();
    } catch (Exception e) {

        alert.setTimeout(Alert.FOREVER);
        utils.StaticMidlet.disp.setCurrent(alert);
    }
 }

 void showProperties(String fileName) {
    try {
        if (fileName.equals(UP_DIRECTORY)) {
            return;
        }



        if (!fc.exists()) {
            throw new IOException("File does not exists");
        }

        //Form props = new Form("Properties: " + fileName);
        ChoiceGroup attrs = new ChoiceGroup("Attributes:", Choice.MULTIPLE,     attrList, null);

        addCommand(back);
        addCommand(exit);
        setCommandListener(this);
        append(new StringItem("Location:", currDirName));


        addCommand(back);
        addCommand(exit);
        this.setCommandListener(this);

        fc.close();

        utils.StaticMidlet.disp.setCurrent(this);
    } catch (Exception e) {

        alert.setTimeout(Alert.FOREVER);
        utils.StaticMidlet.disp.setCurrent(alert);
    }
}

void createFile() {
    //Form creator = new Form("New File");
    nameInput = new TextField("Enter Name", null, 256, TextField.ANY);

    append(nameInput);
    append(typeInput);
    addCommand(creatOK);
    addCommand(back);
    addCommand(exit);
    this.setCommandListener(this);

 }

 void createFile(String newName, boolean isDirectory) {
    try {


        if (isDirectory) {
            fc.mkdir();
        } else {
            fc.create();
        }

        showCurrDir();
    } catch (Exception e) {
        String s = "Can not create file '" + newName + "'";

        if ((e.getMessage() != null) && (e.getMessage().length() > 0)) {
            s += ("\n" + e);
        }

        Alert alert = new Alert("Error!", s, null, AlertType.ERROR);
        alert.setTimeout(Alert.FOREVER);
        utils.StaticMidlet.disp.setCurrent(alert);
        // Restore the commands that were removed in commandAction()
        addCommand(creatOK);
        addCommand(back);
        this.setCommandListener(this);
    }
 }

 private String myDate(long time) {
    Calendar cal = Calendar.getInstance();

    cal.setTime(new Date(time));

    StringBuffer sb = new StringBuffer();

    sb.append(cal.get(Calendar.HOUR_OF_DAY));
    sb.append(':');
    sb.append(cal.get(Calendar.MINUTE));
    sb.append(':');
    sb.append(cal.get(Calendar.SECOND));
    sb.append(',');
    sb.append(' ');
    sb.append(cal.get(Calendar.DAY_OF_MONTH));
    sb.append(' ');
    sb.append(monthList[cal.get(Calendar.MONTH)]);
    sb.append(' ');
    sb.append(cal.get(Calendar.YEAR));

    return sb.toString();
  }

  public void inserer(String image) {
    try {

        dis = new DataInputStream(hc.openDataInputStream());
        while ((ch = dis.read()) != -1) {
            sb.append((char) ch);
        }
        if ("OK".equals(sb.toString().trim())) {

        } else {

        }
        sb = new StringBuffer();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
 }

 public void run() {
    List curr = (List) d;
    final String currFile = curr.getString(curr.getSelectedIndex());
    if (currFile.endsWith(SEP_STR) || currFile.equals(UP_DIRECTORY)) {
        traverseDirectory(currFile);
    } else {
        // Show file contents
        showFile(currFile);
    }
    final String name = "";
    final boolean val = false;
    createFile(name, val);
    final String file = currFile;
    delete(file);
  }
}  `  

This code display only the file content (eg: file1.txt), I want to display pictures.

John Conde
  • 217,595
  • 99
  • 455
  • 496
  • That is a *lot* of code to look at. Could you only show the relevant parts which are needed to [reproduce](http://stackoverflow.com/help/mcve) your example? – Wai Ha Lee Apr 27 '15 at 11:59
  • thank you for your answer so like i said i would like to browse pictures with j2me using wtk 2.5 and i get an exception in the showcurrdir function – Ghaya Zarrouk Apr 27 '15 at 12:41

1 Answers1

0

Summary

I don't know much Java at all, but your exception message,

java.lang.NullPointerException
at javax.microedition.lcdui.Form.append(Form.java:641)
at GUI.FileBrowser.showCurrDir(+151)
at GUI.FileBrowser.<init>(FileBrowser.java:115)
at GUI.Menu.run(Menu.java:109)

states that you have a NullPointerException when calling append in showCurrDir.

I strongly suggest you read something like "What is a Null Pointer Exception, and how do I fix it?" if you don't know how to solve your problem from looking at the stack trace...


My analysis of your problem

You are calling append six times with four unique objects:

append(UP_DIRECTORY);
append(dirIcon);
append(fileIcon);
append(fileName);

meaning that one of them is null.

We know that UP_DIRECTORY is not null since it is a field which gets initialised:

private static final String UP_DIRECTORY = "..";

This leaves dirIcon, fileIcon, and fileName.

In the constructor you are initialising dirIcon and fileIcon by trying to load them using Image.createImage, but swallowing exceptions by setting them to null if the files could not be found, i.e.

try {
    dirIcon = Image.createImage("/dir.png");
} catch (IOException e) {
    dirIcon = null;
}

try {
    fileIcon = Image.createImage("/file.png");
} catch (IOException e) {
    fileIcon = null;
}

so one of dirIcon or fileIcon could be null.

fileName comes from the following block:

Enumeration e;
FileConnection currDir = null;

if (MEGA_ROOT.equals(currDirName)) {
    e = FileSystemRegistry.listRoots();
} else {
    e = currDir.list();
}

while (e.hasMoreElements()) {
    String fileName = (String) e.nextElement();
    // elided
}

so presumably fileName is not null (as I said, I don't know much Java so I could well be wrong - I suppose there's no reason to stop a null from sneaking into e?).

There is another problem here because you are never setting currDir to an instance of anything, and it will be null, causing another NullPointerException if MEGA_ROOT.equals(currDirName) is false. Since the problem is in the constructor (before traverseDirectory is called), they are equal, so this does not contribute to the problem.


A solution

It seems that your usage of hasMoreElements seems to be safe with the result of FileSystemRegistry.listRoots(), e.g. (1) or (2), so I think we can rule out fileName being null.

I would add a breakpoint in the parts where you are loading the image files to see if they are actually there - if not, this is the cause of your NullPointerException.

Community
  • 1
  • 1
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92