Problem Adding Image Inside a Thread

Asked

Viewed 108 times

0

I have this following call class inside the main is working perfectly only problem is for me to set the image I received in msg from the following error

E/Androidruntime FATAL EXCEPTION: Thread-201 android.view.Viewrootimpl$Calledfromwrongthreadexception: Only the original thread that created a view Hierarchy can touch its views.

 class LooperThread extends Thread {

    @Override
    public void run() {

      try {
        while (true) {
            System.out.println("entro");
            Fila fila = new Fila("NocView", "NocView-Campainha", TipoFila.Get, "rabbit01.spacnet.com.br", "campainha", "campainha");
            byte[] teste = fila.consome();
            Mensagem m = new Mensagem().getObjeto(teste);
            Campainha campainha2 = (Campainha) m;
            fila.ack();


            InputStream in = new ByteArrayInputStream(campainha2.getImagem());
            Drawable d = Drawable.createFromStream(in, "src name");

            byte[] data = campainha2.getImagem();
            Bitmap bmp = BitmapFactory.decodeByteArray(campainha2.getImagem(), 0, campainha2.getImagem().length);
            img.setImageBitmap(bmp);  -> erro

    }
}

how could I be solving this problem??

  • I don’t know much about android, but one thing I’ve seen in some languages is that changing the UI via thread causes problems. You can usually notify the main thread to make the change.

  • 1

    On Android you can use AsyncTask to implement these two steps (step 1: load the data and step 2: update the bitmap) in the methods doInBackground() and onPostExecute() (the first wheel on a thread and the second in the thread main, which is the thread that can update the screen). With this you also avoid creating a subclass of Thread, to AsyncTask already does it for you under the table. Search for examples on Google, as this one.

1 answer

1


You can use an Asynctask and place the image manipulation part inside it.

If the processing is not heavy, you can use a Uithread, as in the example below:

 [Sua Activity].this.runOnUiThread(new Runnable() {
            @Override
            public void run() {

                //procesamento aqui
            }
        });

In this case, you need your Activity.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.