How to fix android.os.NetworkOnMainThreadException Error by creating new Thread in your Android Studio Code?

In this video it shows the fix for android.os.NetworkOnMainThreadException error. It creates a new thread in the Android code to fix this error.

I hope you like this video. For any questions, suggestions or appreciation please contact us at: https://programmerworld.co/contact/ or email at: programmerworld1990@gmail.com

Complete source code and other details:

package com.programmerworld.fixnetworkonmainthreaderror;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private ImageView imageView;
    private TextView textView;

    private URL url;
    private Bitmap bitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = findViewById(R.id.imageView);
        textView = findViewById(R.id.textView);

        try {
            url = new URL("https://i0.wp.com/programmerworld.co/wp-content/uploads/2023/05/flower.png?w=977&ssl=1");
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }

    public void buttonError(View view){
        try {
            bitmap = BitmapFactory.decodeStream(url.openStream());
            imageView.setImageBitmap(bitmap);
        } catch (Exception e) {
            textView.setText(e.toString());
            imageView.setImageBitmap(null);
        }
    }
    public void buttonResolution(View view){
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    bitmap = BitmapFactory.decodeStream(url.openStream());
                } catch (Exception e) {
                    textView.setText(e.toString());
                }
            }
        });
        thread.start();
        while (thread.isAlive()){
            textView.setText("Thread is processing the request");
        }
        imageView.setImageBitmap(bitmap);
        textView.setText("SUCCESS");
    }
}

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.FixNetworkOnMainThreadError"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.416"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.268" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="31dp"
        android:layout_marginTop="73dp"
        android:onClick="buttonError"
        android:text="Error Code"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="76dp"
        android:layout_marginTop="72dp"
        android:onClick="buttonResolution"
        android:text="Fix with Thread"
        app:layout_constraintStart_toEndOf="@+id/button"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="280dp"
        android:layout_height="252dp"
        android:layout_marginStart="39dp"
        android:layout_marginTop="67dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:srcCompat="@drawable/ic_launcher_background" />

</androidx.constraintlayout.widget.ConstraintLayout>

Screenshots:

The Image in this demo is referred from below URL:

https://i0.wp.com/programmerworld.co/wp-content/uploads/2023/05/flower.png?w=977&ssl=1

Leave a Reply