1

我正在使用下面的代码来显示来自 web 服务的 url 的图像。我没有收到任何错误,但也无法显示图像。

getWebData 是我的 Utils 类中的静态方法:

public static void getWebData(final String url, final WebDataCallback callback) throws IOException
{
    Thread t = new Thread(new Runnable()
    {
        public void run()
        {
            HttpConnection connection = null;
            InputStream inputStream = null;

            try
            {
                connection = (HttpConnection) Connector.open(url, Connector.READ, true);
                inputStream = connection.openInputStream();
                byte[] responseData = new byte[10000];
                int length = 0;
                StringBuffer rawResponse = new StringBuffer();
                while (-1 != (length = inputStream.read(responseData)))
                {
                    rawResponse.append(new String(responseData, 0, length));
                }
                int responseCode = connection.getResponseCode();
                if (responseCode != HttpConnection.HTTP_OK)
                {
                    throw new IOException("HTTP response code: "
                            + responseCode);
                }

                final String result = rawResponse.toString();
                UiApplication.getUiApplication().invokeLater(new Runnable()
                {
                    public void run()
                    {
                        callback.callback(result);
                    }
                });
            }
            catch (final Exception ex)
            {
                UiApplication.getUiApplication().invokeLater(new Runnable()
                {
                    public void run()
                    {
                        callback.callback("Exception (" + ex.getClass() + "): " + ex.getMessage());
                    }
                });
            }
            finally
            {
                try
                {
                    inputStream.close();
                    inputStream = null;
                    connection.close();
                    connection = null;
                }
                catch(Exception e){}
            }
        }
    });
    t.start();
}

下面是使用 getWebData 方法的 WebBitmapField。您需要做的就是将 URL 传递给构造函数,它会加载图像:

public class WebBitmapField extends BitmapField implements WebDataCallback
{
    private EncodedImage bitmap = null;

    public WebBitmapField(String url)
    {
        try
        {
            Util.getWebData(url, this);
        }
        catch (Exception e) {}
    }

    public Bitmap getBitmap()
    {
        if (bitmap == null) return null;
        return bitmap.getBitmap();
    }

    public void callback(final String data)
    {
        if (data.startsWith("Exception")) return;

        try
        {
            byte[] dataArray = data.getBytes();
            bitmap = EncodedImage.createEncodedImage(dataArray, 0,
                    dataArray.length);
            setImage(bitmap);
        }
        catch (final Exception e){}
    }
}
4

0 回答 0