How to fix NetworkOnMainThreadException using StrictMode.ThreadPolicy in your Android Studio code?

Опубликовано: 31 Май 2023
на канале: Programmer World
513
8

This video shows the steps to quickly fix android.os.NetworkOnMainThreadException in your Android Studio Java code.

The fix shown is more of a workaround. Ideal fix would be to run all the network related tasks in a separate thread using async methods.

However, in this video it shows how one can quickly override StrictMode Thread Poilcy by creating a local thread policy and allowing the network related tasks on the main thread which is not the perfect solution. This solution should be used only if the developer knows what kind of Network operation are being done in the main thread. He should be confident that it will not lead to long waiting period in the main thread as it can create issues for the complete App.

In this video it first reproduces the issue by loading the image from below URL in an imageView:
https://i0.wp.com/programmerworld.co/...

Then it uses the local thread policy to override it in the StrictMode's Thread policy.



I hope you like this video. For any questions, suggestions or appreciation please contact us at: https://programmerworld.co/contact/ or email at: [email protected]

Complete source code and other details/ steps of this video are posted in the below link:
https://programmerworld.co/android/ho...



However, the main Java code is copied below also for reference:


package com.programmerworld.networkonmainthreadexceptionfix;

import androidx.appcompat.app.AppCompatActivity;

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

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

private ImageView imageView;
private TextView textView;

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

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

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}

public void buttonInternetUsage(View view){
String stringURL = "https://i0.wp.com/programmerworld.co/...";
try {
InputStream inputStream = (InputStream) new URL(stringURL).getContent();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
inputStream.close();
imageView.setImageBitmap(bitmap);

} catch (Exception e) {
textView.setText(e.toString());
}
}
}


--