8

I'm looking for a very basic function. I'm trying to design an app and all I want it to do is load an image from a URL. I've found a few questions and websites, but they all seem to be older and dated, but what I think I'm having issues with is linking the code to activity main.xml for ImageView.

Any suggestions or links you have I would greatly appreciate, thank you.

SystemIsGod
  • 145
  • 1
  • 1
  • 6

4 Answers4

12

Here, this is how I display image from url in the image view
you have to call this code from thread other than main thread

ImageView img = (ImageView) findViewById(R.id.imageView1);
try {
        URL url = new URL("Your URL");
        //try this url = "http://0.tqn.com/d/webclipart/1/0/5/l/4/floral-icon-5.jpg"
        HttpGet httpRequest = null;

        httpRequest = new HttpGet(url.toURI());

        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = (HttpResponse) httpclient
                .execute(httpRequest);

        HttpEntity entity = response.getEntity();
        BufferedHttpEntity b_entity = new BufferedHttpEntity(entity);
        InputStream input = b_entity.getContent();

        Bitmap bitmap = BitmapFactory.decodeStream(input);

        img.setImageBitmap(bitmap);

    } catch (Exception ex) {

    }

Be careful don't forget to surround the code with try catch(I have already done that in this code)

or you can use webview to load image from url

WebView web = (WebView) findViewById(R.id.webView1);
web.loadUrl("Your Url");

if you are trying to load image from the assets folder url will start like this "file:///android_asset/yourimage.jpg"
else normal internet url like this "http://0.tqn.com/d/webclipart/1/0/5/l/4/floral-icon-5.jpg"

hope this works for you Good Luck

Amalan Dhananjayan
  • 2,277
  • 1
  • 34
  • 47
  • 1
    I try to edit your post but I think somehow the answer is not updated yet. Can you put addition note in the answer with bold font mentioning that you have to call this code from thread other than main thread. – VendettaDroid Feb 14 '13 at 03:40
  • But I did not call it from the thread and it works fine for me. Can you please clarify it.Thank You. – Amalan Dhananjayan Feb 14 '13 at 03:45
  • 1
    android now has a strict policy on any network communication. You should try this code again. The code that you have written can take any amount of time to get image from remote url depending on the network speed and image size. If you are calling this code from UI then there is a chance that your UI thread will be blocked and give you ANR. Try this code on ICS if you can. It should probably give an exception "NetWorkOnMainThread". or you can simply google search for this exception. – VendettaDroid Feb 14 '13 at 03:50
  • I have written two answers above, hope the thread is needed for the first answer.I have updated thank you. – Amalan Dhananjayan Feb 14 '13 at 03:55
  • 1
    No problem , Yes the thread is needed for first answer. In Webview, it is handled for you already. – VendettaDroid Feb 14 '13 at 03:57
  • I used the code you sent and it seemed there were 2 missing brackets so I added them, and doing so makes no errors in Eclipse. However, the app force closes when ran, and I believe it's due to the "main thread" but I'm not sure how to address the issue. – SystemIsGod Feb 14 '13 at 05:14
  • what is the Android version you are running the app in? Main thread is needed if you are running it on a ICS(Android 4.0), Its working fine with GB(Android 2.3) without the thread.But it is good to add the thread. – Amalan Dhananjayan Feb 14 '13 at 05:17
  • I changed the target to 2.3 and I still get the same force close. – SystemIsGod Feb 14 '13 at 05:25
  • can you please post your code where you have added my coding. – Amalan Dhananjayan Feb 14 '13 at 05:27
  • ImageView img = (ImageView) findViewById(R.id.imageView1); ImageView img = (ImageView) findViewById(R.id.imageView1); { <--- – SystemIsGod Feb 14 '13 at 05:28
  • I want the whole code that you have coded inside the try catch. – Amalan Dhananjayan Feb 14 '13 at 05:32
  • All I added was the bracket, I didn't change anything else. Edit, I realize what you're asking now, 1 moment. – SystemIsGod Feb 14 '13 at 05:32
  • May I know where you added those 2 brackets? Because in my code you don't have to add extra brackets, the brackets I used are to enclose the try block and the catch only. Also check Have you given Internet permission in the android manifest – Amalan Dhananjayan Feb 14 '13 at 05:37
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/24489/discussion-between-systemisgod-and-batz) – SystemIsGod Feb 14 '13 at 05:40
  • HttpGet, HttpClient, HttpResponse, HttpEntity, and BufferedHttpEntity are not is not auto-importing in Android Studio and show in red. (https://photos.google.com/share/AF1QipOxQf9sZCE8tEgTpYM5Xm48pRzPOEFWi0x3yBJ2CigRpC3JI3mUQdW6QGNohR6nIQ?key=UWZVSXJrcjNPS1hqd2xZRm1rdUpqVTdoTGxFYi13) – AdamHurwitz Jul 04 '16 at 10:04
4

There is an opensource library called imageloader. It is widely used, you can use it directly or make code similar to it.

https://github.com/nostra13/Android-Universal-Image-Loader

VendettaDroid
  • 3,131
  • 2
  • 28
  • 41
0

You can take the image and on your php side convert it into a base64 and then on Android side decode it into a image.

Taryn
  • 242,637
  • 56
  • 362
  • 405
Sammar javed
  • 153
  • 1
  • 5
0

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.

Varun Vashista
  • 157
  • 1
  • 5