各位java大神请指点一下,急急急!谢谢!
我运行到下面一段代码的时候出现错误
Running with locale: Chinese (Simplified)_People's Republic of China.936
Running in the identified_third_party security domain
java.lang.NullPointerException
at com.han.Qunliao.commandAction(+39)
at javax.microedition.lcdui.Display$DisplayAccessor.commandAction(+282)
at javax.microedition.lcdui.Display$DisplayManagerImpl.commandAction(+10)
at com.sun.midp.lcdui.DefaultEventHandler.commandEvent(+68)
at com.sun.midp.lcdui.AutomatedEventHandler.commandEvent(+47)
at com.sun.midp.lcdui.DefaultEventHandler$QueuedEventHandler.handleVmEvent(+186)
at com.sun.midp.lcdui.DefaultEventHandler$QueuedEventHandler.run(+57)
代码如下
package com.han;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.SocketConnection;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDletStateChangeException;
public class Qunliao extends Form implements CommandListener,Runnable{
private static Qunliao instance;
private SocketConnection sc=null;
private DataOutputStream dos=null;
private DataInputStream dis=null;
private TextField txtName= new TextField("用 户 名:", "", 20, TextField.ANY);
private TextField txtMsg= new TextField("聊天信息:", "", 255, TextField.ANY);
private Command cmdSend = new Command("发送", Command.OK, 1);
private boolean isRUN=true;
public Qunliao() {
// display=Display.getDisplay(this);
super("群聊");
instance = this;
addCommand(cmdSend);
setCommandListener(this);
append(txtName);
append(txtMsg);
append("群聊区域:"+"\n");
MyConnection mc = new MyConnection();
Thread t1= new Thread(mc);
// t1.start();
}
public void commandAction(Command c, Displayable d) {
// TODO Auto-generated method stub
try
{
dos.writeUTF(txtName.getString()+"说:"+txtMsg.getString());
}catch(Exception ex)
{
ex.printStackTrace();
}
}
class MyConnection implements Runnable
{
public MyConnection(){}
public void run() {
// TODO Auto-generated method stub
try
{
sc=(SocketConnection)Connector.open("socket://127.0.0.1:9999");
dis=sc.openDataInputStream();
dos=sc.openDataOutputStream();
new Thread(this).start();
}catch(Exception ex)
{
ex.printStackTrace();
}
}
}
public void run() {
// TODO Auto-generated method stub
while(isRUN)
{
try
{
String msg=dis.readUTF();
append(msg+"\n");
}catch(Exception ex)
{
ex.printStackTrace();
}
}
}
public static Qunliao getInstance()
{
if (instance == null) {
instance = new Qunliao();
}
return instance;
}
}
[解决办法]
java.lang.NullPointerException
at com.han.Qunliao.commandAction(+39)
空指针,估计是dos为null吧。
从代码来看,并不能保证run()函数会在commandAction()之前被调用,所以dos可能初始化到值。
[解决办法]
我刚学这个不会改,你可不可以帮我改下,非常感谢!
[解决办法]
2楼正解,dos为null