error when loading an image from URL to an ImageView

1

I'm trying to load an image in a ImageView , but the image I'm trying to upload is from a URL. The method that loads the image is called cargarDatos() I put it in the OnCreate() so that the image is displayed once the Activity is loaded. I am using a thread to make the connection to the URL.

This is the activity code.

public class MainMenuUsuario extends AppCompatActivity {
   private ImageView img;
    private  Bitmap loadedImage;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pestanias_usuario);


        crearPestanias();
        cargarDatos();
    }

    public void cargarDatos(){
cd.start();    ///Aquí tengo el error.
    }

    Thread cd=new Thread(new Runnable() {
        @Override
        public void run() {
            img=(ImageView)findViewById(R.id.imageView2);
            URL imageUrl = null;
            try {
                imageUrl = new URL("http://192.168.150.101:8080/TDIDP/imagenes/IMG-20173175029");
                HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
                conn.connect();
                loadedImage = BitmapFactory.decodeStream(conn.getInputStream());
                img.setImageBitmap(loadedImage);
            } catch (IOException e) {
                Toast.makeText(getApplicationContext(), "Error cargando la imagen: "+e.getMessage(), Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
        }
    });

    public void crearPestanias(){

        TabHost host = (TabHost)findViewById(R.id.tabHost);
        host.setup();

        TabHost.TabSpec spec = host.newTabSpec("Tab One");
        spec.setContent(R.id.inicio);
        spec.setIndicator("Inicio");
        host.addTab(spec);

        spec = host.newTabSpec("Ventas");
        spec.setContent(R.id.Ventas);
        spec.setIndicator("Ventas");
        host.addTab(spec);

        spec = host.newTabSpec("Compras");
        spec.setContent(R.id.Compras);
        spec.setIndicator("Compras");
        host.addTab(spec);

    }


}

This has the layout.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TabHost
        android:id="@+id/tabHost"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="visible">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:visibility="visible">

            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:visibility="visible" />

            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:visibility="visible">

                <LinearLayout
                    android:id="@+id/inicio"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical"
                    android:visibility="visible">

                    <ScrollView
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        tools:ignore="UselessParent">

                        <LinearLayout
                            android:id="@+id/contenido_inicio"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:orientation="vertical"
                            tools:ignore="UselessLeaf" >

                            <ImageView
                                android:id="@+id/imageView2"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                app:srcCompat="@drawable/cast_abc_scrubber_control_to_pressed_mtrl_000"
                                tools:ignore="ContentDescription" />
                        </LinearLayout>
                    </ScrollView>
                </LinearLayout>

                <LinearLayout
                    android:id="@+id/Ventas"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical"
                    android:visibility="visible">

                    <ScrollView
                        android:layout_width="match_parent"
                        android:layout_height="411dp">


                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:orientation="vertical"
                            tools:ignore="UselessLeaf">

                        </LinearLayout>
                    </ScrollView>

                    <Button
                        android:id="@+id/button4"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:onClick="add"
                        android:text="Agregar Producto"
                        tools:ignore="HardcodedText" />
                </LinearLayout>

                <LinearLayout
                    android:id="@+id/Compras"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical"
                    android:visibility="visible">

                </LinearLayout>
            </FrameLayout>
        </LinearLayout>
    </TabHost>

</LinearLayout>



This is the error that comes to me:

04-18 17:25:47.983 28688-29052/com.example.friky.tdidp E/AndroidRuntime: FATAL EXCEPTION: Thread-8203
                                                                         Process: com.example.friky.tdidp, PID: 28688
                                                                         android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
                                                                             at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6368)
                                                                             at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:926)
                                                                             at android.view.ViewGroup.invalidateChild(ViewGroup.java:4640)
                                                                             at android.view.View.invalidateInternal(View.java:11731)
                                                                             at android.view.View.invalidate(View.java:11695)
                                                                             at android.view.View.invalidate(View.java:11679)
                                                                             at android.widget.ImageView.setImageDrawable(ImageView.java:456)
                                                                             at android.widget.ImageView.setImageBitmap(ImageView.java:542)
                                                                             at com.example.friky.tdidp.MainMenuUsuario$1.run(MainMenuUsuario.java:86)
                                                                             at java.lang.Thread.run(Thread.java:818)
    
asked by FrEqDe 19.04.2017 в 00:29
source

1 answer

1

Use runOnUiThread () so you can perform that operation in the Main Thread:

public class MainMenuUsuario extends AppCompatActivity {
   private ImageView img;
    private  Bitmap loadedImage;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pestanias_usuario);

     crearPestanias();
    // cargarDatos();

    runOnUiThread(new Runnable() {
         public void run() {

       img=(ImageView)findViewById(R.id.imageView2);
                URL imageUrl = null;
                try {
                    imageUrl = new URL("http://192.168.150.101:8080/TDIDP/imagenes/IMG-20173175029");
                    HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
                    conn.connect();
                    loadedImage = BitmapFactory.decodeStream(conn.getInputStream());
                    img.setImageBitmap(loadedImage);
                } catch (IOException e) {
                    Toast.makeText(getApplicationContext(), "Error cargando la imagen: "+e.getMessage(), Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }

      }
    });


}
    
answered by 19.04.2017 / 00:43
source