Setting image from url - android

I have an image view in my Android app, where I have to set a simple image from url. I tried the below code, but it doesn't set the image from url.
try {
URL url = new URL("https://drive.google.com/...");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream stream = connection.getInputStream();
Bitmap teamBmpImage = BitmapFactory.decodeStream(stream);
teamImgView.setImageBitmap(teamBmpImage);
}
catch (Exception e) {
}
Could someone guide me to achieve this please?
UPDATED CODE: Which gives Nullpointer exception
public class AboutActivity extends ActionBarActivity {
ImageView teamImgView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
teamImgView = (ImageView) this.findViewById(R.id.teamImageView);
new DownloadImageTask(teamImgView).execute("http://docs.oracle.com/javase/tutorial/2d/images/examples/strawberry.jpg");
}
class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
//pd.show();
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
//pd.dismiss();
bmImage.setImageBitmap(result);
}
}
}

I guess you are executing your code on the MainThread, which leads to a NetworkOnMainThreadException in android. Try to execute your code asynchronous like in the example below
new AsyncTask<String, Integer, Bitmap>() {
#Override
protected Bitmap doInBackground(String... params) {
try {
URL url = new URL(params[0]);
return BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap bm) {
ImageView teamImgView = (ImageView) findViewById(R.id.teamImageView);
teamImgView.setImageBitmap(bm);
}
}.execute("https://drive.google.com/uc?....");

You can use Picasso library and here is a detailed tutorial on how to do this.
This is very simple example usage
Picasso.with(activityContext)
.load("https://drive.google.com/uc?....")
.placeholder(R.drawable.image_name)
.into(imageView);

As bojan says you can use Picasso library wich handles many common pitfalls of image loading on Android.
Picasso.with(context).load("http://myurl/myImage.png").into(imageView);
Picasso
Anyway, check out this threat too :)
How to load an ImageView by URL in Android?

Try following this link:
http://www.tutorialsbuzz.com/2014/11/android-volley-url-imageview.html
This will help you to load your image using Volley library which will do all the networking stuff on networking thread and set your image on main UI thread. It has also the LRUCache part which you can skip if you want.

Related

Display Images in Recyclerview without using any library [duplicate]

I'm trying to download an image using a URL and a button in my app. When I'm running it on my phone, I,m not able to download the image. Can anyone please point out the problem with this. Thanks for the help in advance :)
This is my code.
public class MainActivity extends AppCompatActivity {
ImageView download;
public void downloadImage(View view){
DownloadImage image = new DownloadImage();
Bitmap result;
try {
result = image.execute("https://en.wikipedia.org/wiki/File:Bart_Simpson_200px.png").get();
download.setImageBitmap(result);
}
catch(Exception e)
{
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
download = (ImageView) findViewById(R.id.imageView);
}
public class DownloadImage extends AsyncTask<String, Void, Bitmap>{
#Override
protected Bitmap doInBackground(String... urls) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.connect();
InputStream in = urlConnection.getInputStream();
Bitmap Image = BitmapFactory.decodeStream(in);
in.close();
return Image;
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
you can download image from url in two ways
1.you can user Glide library to load image from url look the below code it can help you in simple way
compile this library
implementation 'com.github.bumptech.glide:glide:4.6.1'
than load image like this
Glide.with(MainActivity.this)
.load(url)
.apply(new RequestOptions().placeholder(R.drawable.booked_circle).error(R.drawable.booked_circle))
.into(imageview);
2 .try this if you dont want to use third party library
new DownloadImage(imamgeview).execute(url);
create a Async Task
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImage(ImageView bmImage) {
this.bmImage = (ImageView ) bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.d("Error", e.getStackTrace().toString());
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
i hope that it will work in your case
You did not call the function
downloadImage(view);
In the oncreate (after the findviewbyid line)
Also check if the internet permision is in the Android Manifest file :
<uses-permission android:name="android.permission.INTERNET" />
Having said that you should use a library like Glide\Picasso\Ion etc... much better than asynctask for this purpuse
https://github.com/bumptech/glide - Glide
https://github.com/koush/ion - Ion
http://square.github.io/picasso/ - picasso
Hope it helped.

load .png from url's in the existing imageview

i seen this, and made how they say.
my app loads and shows .jpg, but don't show .png. He shows empty screen. (tested on versions 4.1 and 4.2)
if (isOnline()) {
new DownloadImageTask((ImageView) findViewById(R.id.imageViewSA))
.execute(img);
} else {
tv_info.setText("Включите интернет для загрузки");
}
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
you can use universal image loader library instead, so easy to integrate in your code, you can display images from URL to imageView like this
imageLoader.displayImage(url, imageView);
here's a good example of using UIL
and the library
good luck ;)

How to read image from server via emulator

I want to read image from server using android studio via emulator. Please any one help me because I had tried a lot of ways but not yet success.
My peace of code are like this.
In Acitivity.java file code is like this.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn=(Button)findViewById(R.id.button);
imageView=(ImageView)findViewById(R.id.imageView);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
iv = (ImageView) findViewById(R.id.imageView);
bitmap = getBitmapFromURL("http://10.0.2.2/img.bmp");
iv.setImageBitmap(bitmap);
}
});
}
And I use this Function.
public Bitmap getBitmapFromURL(String src){
try{
URL url= new URL(src);
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input=(connection).getInputStream();
Bitmap myBitmap= BitmapFactory.decodeStream(input);
return myBitmap;
}catch (Exception e){
e.printStackTrace();
Toast.makeText(this,e.getMessage(),Toast.LENGTH_LONG).show();
return null;
}
}
Please any one help me.
Use Picasso for downloading and caching images.Add this in your dependencies using compile 'com.squareup.picasso:picasso:2.5.2' if you are using android studio otherwise add the jar in your libs.
it's a one line code to manage everything :
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
just pass your url and you are done.
I try many things at last I found this I think this will useful for you. So try this.
Do this in your Activity.
new DownloadImageTask(your_imageview).execute("http://10.0.2.2/img.bmp);
And method is like this.
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
bmImage.setImageBitmap(result);
}
}

android setting layout background to iamgeview

I have a class that extends AsyncTask to get image from a URL:
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
I can load it to every ImageView I want, like that:
new DownloadImageTask(mRecipeImage).execute(ImageURL);
I an getting the image while the app is running (dynamically).
I want to set a Relative Layout's background to the image that I am getting from the web.
any ideas?
Please visit this link:
UniversalImageLoader
may it is help full to you.
It is better if you use an ImageLoader library like picasso, volley for downloading and setting Image.
code snippet for using picasso
Picasso.with(context).load("ur_image_url").into(bmImage);
code snippet for using Volley
String url = "http://i.imgur.com/7spzG.png";
// Retrieves an image specified by the URL, displays it in the UI.
ImageRequest request = new ImageRequest(url,
new Response.Listener() {
#Override
public void onResponse(Bitmap bitmap) {
bmImage.setImageBitmap(bitmap);
}
}, 0, 0, null,
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
bmImage.setImageResource(R.drawable.image_load_error);
}
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(request);

android:display image in listview

I am trying to display an image in listview from url using JSON parsing. the image url displays correctly in log. when i am trying to download image and display in list getting NullPointerException in bmImage.setImageBitmap(result);
i am using following code can anyone tell me the solution..
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
Bitmap bt_img = null;
try {
FileInputStream in = new FileInputStream(urls[0]);
InputStream in = new java.net.URL(urls[0]).openStream();
bt_img = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return bt_img;
}
protected void onPostExecute(Bitmap result) {
try {
bmImage.setImageBitmap(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
If you are getting a nullPointerException on the bmImage variable, it means it has not been initialized. As in the code you provide you are not getting its reference, you have to be passing it to the AsyncTask.
What is the code where you pass the bmImage reference, invoking your AsyncTask? The problem seems to be in that code, not in the AsyncTask itself.
1) best way is use Lazy Loding
and
2) second way is try this code,
try {
URL imageURL = new URL(imgUrl);
qrBitmap = BitmapFactory.decodeStream(imageURL.openStream());
image.setImageBitmap(qrBitmap);
} catch (Exception e) {
Log.d("QRDisplay", e.getMessage());
}
You have to use the Universal Image Loader for getting the images from the server.
this link help to u
https://github.com/nostra13/Android-Universal-Image-Loader

Categories

Resources