我尝试使用此代码示例使用模拟器(WTK2.5)浏览一些图片,但我收到此异常消息(在showdir()函数上):
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)
这是我在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);
}
} `
此代码仅显示文件内容(例如:file1.txt),我想显示图片。
答案 0 :(得分:0)
<强>摘要强>
我完全不了解Java,但是您的异常消息
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)
表示在NullPointerException
中呼叫append
时您有showCurrDir
。
我强烈建议您阅读类似“What is a Null Pointer Exception, and how do I fix it?”的内容,如果您不知道如何通过查看堆栈跟踪来解决您的问题......
我对您的问题的分析
您使用四个唯一对象调用append
六次:
append(UP_DIRECTORY);
append(dirIcon);
append(fileIcon);
append(fileName);
意味着一个是空的。
我们知道UP_DIRECTORY
不是null,因为它是一个初始化的字段:
private static final String UP_DIRECTORY = "..";
这会留下dirIcon
,fileIcon
和fileName
。
在构造函数中,您通过尝试使用dirIcon
加载它们来初始化fileIcon
和Image.createImage
,但是如果找不到文件,则通过将异常设置为null来吞咽异常,即< / p>
try {
dirIcon = Image.createImage("/dir.png");
} catch (IOException e) {
dirIcon = null;
}
try {
fileIcon = Image.createImage("/file.png");
} catch (IOException e) {
fileIcon = null;
}
因此dirIcon
或fileIcon
中的一个可能为空。
fileName
来自以下块:
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
}
所以大概fileName
不是空的(正如我所说的,我不太了解Java,所以我可能错了 - 我想没有理由阻止null
偷偷进入{{ 1}}?)。
此处有另一个问题,因为您永远不会将e
设置为任何内容的实例,它将是currDir
,导致另一个null
if { {1}}是假的。由于问题出在构造函数中(在调用NullPointerException
之前),它们 相等,所以这不会导致问题。
解决方案
MEGA_ROOT.equals(currDirName)
的结果似乎是traverseDirectory
的使用似乎是安全的,例如(1)或(2),所以我认为我们可以排除hasMoreElements
为FileSystemRegistry.listRoots()
。
我会在你加载图片文件的部分添加一个断点,看看它们是否真的存在 - 如果没有,这就是你fileName
的原因。