0

I am trying to download an image from url and i want to display it in an imageview.My code is as follows:

package com.example.imageinternalstorage;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
Button btnstoreinternal,btnloadfrominternal;
ImageView iv_category;
boolean download_success;
String URL_image="http://footballultimate.com/storelocator/resource/uploads/";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnstoreinternal=(Button) findViewById(R.id.btnstoreinternal);
        btnloadfrominternal=(Button) findViewById(R.id.btnloadfrominternal);
        iv_category=(ImageView) findViewById(R.id.iv_category);
        btnstoreinternal.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                download_success=downloadFile(URL_image+"Hospital.png");
                if(download_success==true)
                {
                    Toast.makeText(getApplicationContext(),"Download success",Toast.LENGTH_LONG).show();
                }
                else
                {
                    Toast.makeText(getApplicationContext(),"Download failed",Toast.LENGTH_LONG).show();
                }

            }
        });
        btnloadfrominternal.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                iv_category.setImageBitmap(getImageBitmap(MainActivity.this,"Hospital.png"));

            }
        });
    }

    public boolean downloadFile(final String path)
    {
        try
        {
            URL url = new URL(path);

            URLConnection ucon = url.openConnection();
            ucon.setReadTimeout(5000);
            ucon.setConnectTimeout(10000);

            InputStream is = ucon.getInputStream();
            BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);

            File file = new File(MainActivity.this.getDir("filesdir", Context.MODE_PRIVATE) + "/Hospital.png");

            if (file.exists())
            {
                file.delete();
            }
            file.createNewFile();

            FileOutputStream outStream = new FileOutputStream(file);
            byte[] buff = new byte[5 * 1024];

            int len;
            while ((len = inStream.read(buff)) != -1)
            {
                outStream.write(buff, 0, len);
            }

            outStream.flush();
            outStream.close();
            inStream.close();

        }
        catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    public Bitmap getImageBitmap(Context context,String name){
          try{
            FileInputStream fis = context.openFileInput(name);
                Bitmap b = BitmapFactory.decodeStream(fis);
                fis.close();
                return b;
            }
            catch(Exception e){
            }
            return null;
        }
}

When i click the first button the download is shown as successfull.But when i click the second button to display the image in the imageview nothing happens.So can anyone give me a replacement code for the retrival code from memory:

public Bitmap getImageBitmap(Context context,String name){
          try{
            FileInputStream fis = context.openFileInput(name);
                Bitmap b = BitmapFactory.decodeStream(fis);
                fis.close();
                return b;
            }
            catch(Exception e){
            }
            return null;
        }

The code for dowloading is:

public boolean downloadFile(final String path)
    {
        try
        {
            URL url = new URL(path);

            URLConnection ucon = url.openConnection();
            ucon.setReadTimeout(5000);
            ucon.setConnectTimeout(10000);

            InputStream is = ucon.getInputStream();
            BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);

            File file = new File(MainActivity.this.getDir("filesdir", Context.MODE_PRIVATE) + "/Hospital.png");

            if (file.exists())
            {
                file.delete();
            }
            file.createNewFile();

            FileOutputStream outStream = new FileOutputStream(file);
            byte[] buff = new byte[5 * 1024];

            int len;
            while ((len = inStream.read(buff)) != -1)
            {
                outStream.write(buff, 0, len);
            }

            outStream.flush();
            outStream.close();
            inStream.close();

        }
        catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }

        return true;
    }
user3852672
  • 285
  • 1
  • 8
  • 17
  • What errors are being thrown. Please try to isolate where this problem is happening. – Scary Wombat Jul 31 '14 at 05:20
  • Check out my ans here : http://stackoverflow.com/questions/2471935/how-to-load-an-imageview-by-url-in-android/24134425#24134425 – Haresh Chhelana Jul 31 '14 at 05:22
  • You should use an `AsyncTask` to access the network, otherwise an Exception will be thrown. – zozelfelfo Jul 31 '14 at 05:23
  • I dubugged the code with a breakpoint at the code where the image for the imageview is being set and the method is returning a null. – user3852672 Jul 31 '14 at 05:24
  • @haresh You have used android query,But if the image is already present in the cache i dont want it be downloaded from the network.Will that be taken care of in the android query? – user3852672 Jul 31 '14 at 05:27
  • Yes i already mention main featured of AndroidQuery in ans please read carefully then still you have any problem just ask me. – Haresh Chhelana Jul 31 '14 at 05:28
  • I am new to android.I used android query on a previous post by you.But what i wanted to know was that if the images are downloaded the first time and i run the app again will the retrieval from the network happen or will it be retrieved from the internal memory? – user3852672 Jul 31 '14 at 05:30

2 Answers2

1

Android does not allow such Network operations in the onCreate method ever since version >2.2 I think.
Solutions:
1- Try using a private class inside the main class that extends AsyncTask and if you are not sure about the return type you can use Void. E.g take a look at this AndroidHive tutorial ,while he is retrieving JSON data from a website he calls the 'GetContacts' class which he created to do the network operations.

2-If you are not feeling all this AsyncTask stuff take a look at Android Volley library which has a nice AndroidHive tutorial as well.

Manny265
  • 1,709
  • 4
  • 23
  • 42
0

while downloading image you are storing it in "filesdir" while for retrieving image you are using openFileInput(name) replace FileInputStream fis = context.openFileInput(name); By File file = new File("filesdir", FILENAME); else use this for storing downloaded image

String path=context.getFilesDir().getAbsolutePath();                
 File file = new File(path + File.separator + fileName);

and this for retriving image

 File myFile = new File ( path+ File.separator + fileName); 
                byte [] mybytearray  = new byte [(int)myFile.length()];
                FileInputStream fis = new FileInputStream(myFile);
                BufferedInputStream bis = new BufferedInputStream(fis);
jaimin
  • 563
  • 8
  • 25
  • Then if the fileinputstream is commented then what do i use for Bitmap b = BitmapFactory.decodeStream(fis); line? – user3852672 Jul 31 '14 at 05:35
  • public Bitmap getImageBitmap(Context context,String name){ try{ //FileInputStream fis = context.openFileInput(name); File file = new File("filesdir", name); Bitmap b = BitmapFactory.decodeStream(new FileInputStream(file)); //fis.close(); return b; } catch(Exception e){ } return null; } – user3852672 Jul 31 '14 at 05:45