загрузка фоновых изображений с помощью j2me и lwuit

У меня есть списки изображений, которые нужно загрузить из Интернета и заполнить список вместе с текстом описания рядом с каждым изображением.

Проблема, с которой я столкнулся сейчас, заключается в том, что приложение зависает при загрузке изображений, которые я понимаю».

Я создал поток для загрузки, класс ниже. Я использую метод start для запуска потока, но изображение будет нулевым, пока я не использую run.

public class GetImage extends Thread {

public String imgString;
private String url;
private Label label;
public Image img = null;

public GetImage(String url, Label label){
    this.url = url;
    this.label = new Label();
    this.label = label;
}

public Image getPic()
{

    return img;
}
public void run()
{
   this.getImage_(); 
   this.label.setIcon(img.scaledHeight(60));

}

public void getImage_()
{
    HttpConnection hc = null;
    DataInputStream dis = null;
    DataOutputStream dos = null;
    StringBuffer messageBuffer  = new StringBuffer();

     try{
        hc = (HttpConnection)Connector.open(this.url,Connector.READ);
        dis = new DataInputStream(hc.openDataInputStream());
        int ch;
        long len = hc.getLength();
        if(len != -1)
        {
            for(int i=0; i < len; i++)
                if((ch = dis.read())!=-1)
                    messageBuffer.append((char)ch);
        }
        else
        {
            while((ch = dis.read()) != -1)
                messageBuffer.append((char)ch);
        }

        this.img = Image.createImage(messageBuffer.toString().getBytes(),0,messageBuffer.toString().length());
        dis.close();
    }
    catch(IOException ae){
        messageBuffer.append("Error");
    }
    finally{
        try {
            if (hc != null) hc.close();
        }
        catch (IOException ignored) {}
        try {
            if (dis != null) dis.close();
        }
        catch (IOException ignored) {}
        try {
            if (dos != null) dos.close();
        }
        catch (IOException ignored) {}
    }

   //return this.img;
}

}

и listrenderer для отображения списка:

public class ListRenderer extends Label implements ListCellRenderer {

public ListRenderer()
{
    super();
}

public Component getListCellRendererComponent(List list, Object o, int i, boolean bln) {
     //cast the value object into a Content

    Contents entry = (Contents)o;
    //get the icon of the Content and set it for this label
    this.setIcon(entry.getIcon());
    //get the text of the Content and set it for this label
    this.setText(entry.getText());
    //set transparency
    getStyle().setBgTransparency((byte)128);
    //set background and foreground colors
    //depending on whether the item is selected or not
    if(bln)
    {
        getStyle().setBgColor(0xffcc33);
        getStyle().setFgColor(0x000000);
    }
    else
    {
       getStyle().setBgColor(0xffffff);

    }
    return this;
}

public Component getListFocusComponent(List list) {
    setText("");
    setIcon(null);
    getStyle().setBgColor(0xffcc33);
    getStyle().setBgTransparency(80);
    return this;
}

}

кто-нибудь может помочь?


person Sunday Okpokor    schedule 02.04.2012    source источник
comment
Единственное, о чем я могу думать, это о том, что вы можете создавать свой поток и вызывать run вместо start. Метод start заставит произойти асинхронную магию.   -  person Dylan    schedule 02.04.2012
comment
да, я использую start, но изображение будет нулевым, пока я не использую run.   -  person Sunday Okpokor    schedule 02.04.2012
comment
ошибки, которые вы получаете, связаны с неправильной синхронизацией. Перепроверьте руководство, предложенное в ответ на ваш предыдущий вопрос - все эти загадочные synchronized, wait, notify существуют по какой-то причине   -  person gnat    schedule 02.04.2012


Ответы (1)


Комментарии, которые вы получили, вероятно, правильны. В этом сообщении в блоге показано что-то похожее на то, что вы пытаясь достичь. Он находится в Codename One, но большая часть кода должна быть применима и к LWUIT.

person Shai Almog    schedule 05.04.2012
comment
Спасибо, ребята, ваши комментарии были очень полезны. Наконец, я использовал метод callSeriallyAndWait(), предоставленный lwuit EDT, и он действительно сработал. - person Sunday Okpokor; 05.04.2012