filmov
tv
How to fix NetworkOnMainThreadException using StrictMode.ThreadPolicy in your Android Studio 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:
Then it uses the local thread policy to override it in the StrictMode's Thread policy.
Complete source code and other details/ steps of this video are posted in the below link:
However, the main Java code is copied below also for reference:
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
}
public void buttonInternetUsage(View view){
try {
InputStream inputStream = (InputStream) new URL(stringURL).getContent();
} catch (Exception e) {
}
}
}
--