The best practice to download image is to be done on the background Thread, so that it doesn't interrupt your Main Thread,then update the User Interface as needed.
public class MainActivity extends AppCompatActivity {
FrameLayout frameLayout;
ImageView imageView;
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frameLayout= (FrameLayout) findViewById(R.id.containerlayout);
imageView= (ImageView) findViewById(R.id.imageView);
progressBar= (ProgressBar) findViewById(R.id.progressBar);
String url="http://www.flat-e.com/flate5/wp-content/uploads/cover-960x857.jpg";
MyTask myTask= new MyTask();
myTask.execute(url);
}
class MyTask extends AsyncTask<String, Void, Bitmap> {
@Override
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
}
@Override
protected Bitmap doInBackground(String... voids) {
Bitmap bitmap=null;
try {
URL url =new URL(voids[0]);
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
InputStream inputStream= connection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
progressBar.setVisibility(View.GONE);
imageView.setImageBitmap(bitmap);
}
}
}
Here, in this example I created an inner class MyTask which extends the AsyncTask where i have done all my network operations. Make sure to add the Uses permission in your Manifest File.
Hope this works for you too.