从网络上下载图片出现了问题
代码如下 虽然都能显示图片 但是每次都会出现
NullPointerException import javax.microedition.lcdui.*;
import java.util.*;
import javax.microedition.io.*;
import java.io.*;
public class Test extends Canvas implements Runnable{
Image image;
public Test () {
new Thread(this).start();
tt.start();
}
public void paint(Graphics g)
{
g.drawImage(image,0,0,Graphics.HCENTER|Graphics.VCENTER); //image出现错误
}
public void run()
{
try{
HttpConnection h=(HttpConnection)Connector.open( "http://cgi.htsc.com.cn/cgi/gif.dll?GetHqData&1027&0&120&0&600536&TU%20540%20400%2040;ZS%20460%20165;CJl%20460%20115;ZB%20460%2075%20;MC%20160%200;MM%20160%200;MX%20160%200 ");
DataInputStream dis = null;
dis = h.openDataInputStream();
ByteArrayOutputStream dos = null;
// byte[] b=new byte[ii];// in.read (b,0,ii);
int ch = (int) h.getLength();
byte png[] = null;
if (ch != -1) {
png = new byte[ch];
dis.readFully(png);
} else {
System.out.println ( "dfsa ");
dos = new ByteArrayOutputStream();
int hh;
while ((hh = dis.read()) != -1) {
dos.write(hh);
}
png = dos.toByteArray();
}
image=Image.createImage(png, 0, png.length);
repaint();
}
catch(
IOException ioe)
{}
}
}
------解决方案--------------------public void paint(Graphics g)
{
if(image != null) {
g.drawImage(image,0,0,Graphics.HCENTER|Graphics.VCENTER);
}
}
------解决方案--------------------paint方法在线程启动去取数据之前就被调用到了。这个时候,image还是空呢。
去到数据后,只是刷新repaint()。
------解决方案--------------------确切的说paint方法会在你setCurrent()的时候自行调用,所以...