Obtain an image of a server with GET method

1

Good morning, I have encountered a problem when making my android app with android studio.

What I need is to take a .png image of a server (given a url) using the GET method and display it on the screen.

I have seen some old tutorials but the syntax is now different and does not work correctly. Can someone give me an example of how the code would be to use or pass me an updated link.

This is the code I'm trying to use but it does not work for me: (

I am novatillo in what android applications are concerned and I would need a cable. Thanks in advance and a greeting

XML:

<?xml version="1.0" encoding="utf-8" ?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"> 

 <ImageView android:id="@+id/image_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

</LinearLayout>

.java

package com.jonsegador.examples.externalimage;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.Toast;

public class Main extends Activity {
    private ImageView imageView;
    private Bitmap loadedImage;
    private String imageHttpAddress = "http://jonsegador.com/wp-content/apezz.png";            

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        imageView = (ImageView) findViewById(R.id.image_view);       
        downloadFile(imageHttpAddress);
    }

    void downloadFile(String imageHttpAddress) {
        URL imageUrl = null;
        try {
            imageUrl = new URL(imageHttpAddress);
            HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
            conn.connect();
            loadedImage = BitmapFactory.decodeStream(conn.getInputStream());
            imageView.setImageBitmap(loadedImage);
        } catch (IOException e) {
            Toast.makeText(getApplicationContext(), "Error cargando la imagen: "+e.getMessage(), Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }
}

source: link

    
asked by Jose Luis teleco 08.05.2017 в 09:00
source

1 answer

2

Remember that when you need to make an internet connection, you need to add your AndroidManifest.xml permission:

<uses-permission android:name="android.permission.INTERNET"/>

Regarding the download you do not need to make a request GET to be able to download the image from a url and display it in a ImageView .

The problem that you have in your example, is something obvious since you are trying to perform the download as well as add the image in ImageView in the main thread, you can see it within the LogCat .

For this type of operations I suggest adding an AsyncTask.

How to download image in an ImageView using AsynctTask.

You create an Asynctask where the download process is done within the doInBackground() method:

class LoadImage extends AsyncTask<String, Void, Bitmap> {

    private final WeakReference<ImageView> imageViewReference;

    public LoadImage(ImageView imageView) {
        imageViewReference = new WeakReference<ImageView>(imageView);
    }

    @Override
    protected Bitmap doInBackground(String... params) {
        try {
            return downloadBitmap(params[0]);
        } catch (Exception e) {
            Log.e("LoadImage class", "doInBackground() " + e.getMessage());
        }
        return null;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        if (isCancelled()) {
            bitmap = null;
        }

        if (imageViewReference != null) {
            ImageView imageView = imageViewReference.get();
            if (imageView != null) {
                if (bitmap != null) {
                    imageView.setImageBitmap(bitmap);
                }
            }
        }
    }

    private Bitmap downloadBitmap(String url) {
        HttpURLConnection urlConnection = null;
        try {
            URL uri = new URL(url);
            urlConnection = (HttpURLConnection) uri.openConnection();
            int statusCode = urlConnection.getResponseCode();
            if (statusCode != HttpURLConnection.HTTP_OK) {
                return null;
            }

            InputStream inputStream = urlConnection.getInputStream();
            if (inputStream != null) {
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                return bitmap;
            }
        } catch (Exception e) {
            urlConnection.disconnect();
            Log.e("LoadImage class", "Descargando imagen desde url: " + url);
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
        return null;
    }
}

and you would call in this way the AsyncTask to load the downloaded image, defining the container ImageView and the url of the image to download:

   private ImageView imageView;
   private String imageURL = "http://jonsegador.com/wp-content/apezz.png";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = (ImageView) findViewById(R.id.image_view);
        //downloadFile(imageURL);
        //AsyncTask recibe la referencia del ImageView y la url a descargar.
        new LoadImage(imageView).execute(imageURL);
    }

to get:

I also advise other options that you should review such as GLIDE or PICASSO , whose implementation is very simple.

    
answered by 08.05.2017 в 16:56