RUVIDEO
Поделитесь видео 🙏

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

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/wp-content/uploads/2023/05/flower.png?w=977&ssl=1

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/how-to-fix-android-os-networkonmainthreadexception-in-your-android-studio-code/



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/wp-content/uploads/2023/05/flower.png?w=977&ssl=1";
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());
}
}
}


--

Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «How to fix NetworkOnMainThreadException using StrictMode.ThreadPolicy in your Android Studio code?», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.

Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.

Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!

Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.