1

I want that If my app start first time it should download image from web and store that image in Device/Emulator, from Device/Emulator that should be displayed in ImageView. I have tried in this way :

ImageView myImgView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);     

    myImgView = (ImageView) findViewById(R.id.imageView1);      

    new MyAsnyc();
     Log.d(MY_TAGT, "AsyncTask Executed.....");

}
private class MyAsnyc extends AsyncTask<Void, Void,Void>{
    public File file ;
    InputStream is;
    private Bitmap bitmap;
    protected void doInBackground() throws IOException{

        File path = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES);
        file = new File(path, "DemoPicture.jpg");
        try{
            // Make sure the Pictures directory exists.
            path.mkdirs();

            URL url = new      URL(BASE_URL);
            /* Open a connection to that URL. */
            URLConnection ucon = url.openConnection();

            /*
             * Define InputStreams to read from the URLConnection.
             */
            is = ucon.getInputStream();

            OutputStream os = new FileOutputStream(file);
            byte[] data = new byte[is.available()];
            is.read(data);
            Log.i(MY_TAGT, "Picture is readable........");
            os.write(data);
            Log.i(MY_TAGT, "Picture is Saved........");
            is.close();
            os.close();

        }
        catch (IOException e) {
            Log.d("ImageManager", "Error: " + e);
        }
    }
    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub

        try {
            doInBackground();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }
    protected void onPostExecute(){

        try{
            // Tell the media scanner about the new file so that it is
            // immediately available to the user.

            MediaScannerConnection.scanFile(null,
                    new String[] { file.toString() }, null,
                    new MediaScannerConnection.OnScanCompletedListener() {
                public void onScanCompleted(String path, Uri uri) {
                    Log.i("ExternalStorage", "Scanned " + path + ":");
                    Log.i("ExternalStorage", "-> uri=" + uri);
                }
            });
        }
        catch (Exception e) {
            // TODO: handle exception

        }

        /*Here I want to set this image in ImageView*/

        bitmap = BitmapFactory.decodeFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString()+"/DemoPicture.jpg");
        myImgView.setImageBitmap(bitmap);
    }
}

But in this way MyAsync class is not executed, please tell how to do that.

EDIT this is my log

enter image description here

5 Answers5

6

Use execute to call it.

new MyAsnyc().execute();
Chirag
  • 56,621
  • 29
  • 151
  • 198
1

use

new MyAsnyc().execute();

instead of

new MyAsnyc();

because AsyncTask.execute(Params... params) method used for executing an AsyncTask

EDIT :

use While or for loop for writing data in file as :

OutputStream os = new FileOutputStream(file);
            byte[] data = new byte[is.available()];

            Log.i(MY_TAGT, "Picture is readable........");
            int count;
            while ( (count = is.read(data)) >= 0 ) {
              os.write(data,0,count)
             }

            Log.i(MY_TAGT, "Picture is Saved........");
            is.close();
            os.close();
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
  • Ok! dear, now I have done this `new MyAsync().execute();`, but image is not set in `ImageView` –  Mar 07 '13 at 12:40
  • @Fandroid you have to write your image code in onPostExecute function. – Chirag Mar 07 '13 at 12:41
  • @Fandroid : use `bitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); myImgView.setImageBitmap(bitmap);` for setting downloaded image to ImageView – ρяσѕρєя K Mar 07 '13 at 12:43
  • @ChiragRaval I have allredy done that but still image is not loaded in `ImageView` is this `bitmap = BitmapFactory.decodeFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString()); myImgView.setImageBitmap(bitmap); Log.d(MY_TAGT, "Image is set");` correct to load image? –  Mar 07 '13 at 12:45
  • @Fandroid : and in your current way as you are doning use file name also with Directory path as :`bitmap = BitmapFactory.decodeFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/DemoPicture.jpg");` – ρяσѕρєя K Mar 07 '13 at 12:46
  • Because you have to use imagepath with image name . Here i see u only set the image path not the image name. Same as ρяσѕρєя K suggest, do like that. – Chirag Mar 07 '13 at 12:46
  • @ρяσѕρєяK that does not work for me any other suggestion, plz!! –  Mar 07 '13 at 12:52
  • @Fandroid : First check manually you are getting downloaded image inside Pictures Dir on SDCARD – ρяσѕρєя K Mar 07 '13 at 13:11
  • @ρяσѕρєяK sorry there is no any file `sdcard` is empty! –  Mar 07 '13 at 13:16
  • @Fandroid : i mean check Pictures dir on SDCARD – ρяσѕρєя K Mar 07 '13 at 13:20
  • @Fandroid : if still not solved then see [this](http://www.charlesli.org/java/articles/copyURL/page2.html)tutorials for saving file from web – ρяσѕρєя K Mar 07 '13 at 13:32
  • @ρяσѕρєяK dear still I'm stuck there, because image is not loaded properly –  Mar 07 '13 at 17:45
  • @Fandroid : but u are getting image now in imageView ? – ρяσѕρєя K Mar 07 '13 at 17:46
  • @Fandroid : what issue u have now – ρяσѕρєя K Mar 09 '13 at 11:44
  • Dear! AsyncTask is still giving problems! –  Mar 09 '13 at 11:49
0

You forgot to execute the AsyncTask:

(new MyAsnyc()).execute();
kadrei
  • 11
  • 4
0

Before line Log.d(MY_TAGT, "AsyncTask Executed....."); you just construct new AsyncTask object but you didn't call execution on it with execute() method..

EDIT: second problem is that it is not so clear WHICH picture actually you want to display in that ImageView.. cause bitmap = BitmapFactory.decodeFile(..blahblahblah..) will probably be null after this.. It seems to me u r giving folder name and you wanted to decode that "file" to bitmap.. Make some logs about this decoding and bitmap value and show us..

Edit2:

File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); File file = new File(path, "DemoPicture.jpg"); bitmap = BitmapFactory.decodeFile(file);

should work a bit better..

Ewoks
  • 12,285
  • 8
  • 58
  • 67
  • Now I done that but image is not displayed in `ImageView` please can you give some hint! –  Mar 07 '13 at 12:59
  • Have a look at my logcat that is! –  Mar 07 '13 at 13:48
  • I saw that before but how u refer to that picture again when u want to set it to ImageView? check what I wrote u in edit of my answer before and what @ρяσѕρєя wrote in comments.. u r refering to folder instead of actual image later.. – Ewoks Mar 07 '13 at 14:55
  • Now i have given picture name as `bitmap = BitmapFactory.decodeFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString()+"/DemoPicture.jpg");` but still does not work!! –  Mar 07 '13 at 15:09
  • here u have almost exact example.. just for records.. with logsld be much easier.. http://developer.android.com/reference/android/os/Environment.html#getExternalStoragePublicDirectory(java.lang.String) – Ewoks Mar 07 '13 at 21:36
0

You must try this :

public class DownloadImage {    
public static File getImage(String imageUrl, String fileName){
File file = null;
try {
    //set the download URL, a url that points to a file on the internet
    //this is the file to be downloaded         
    URL url = new URL(imageUrl);
    Log.d("INFORMATION..", "FILE FOUNDED....");
    //create the new connection
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

    //set up some things on the connection
    urlConnection.setRequestMethod("GET");
    urlConnection.setDoOutput(true);

    //and connect!
    urlConnection.connect();
    Log.d("INFORMATION..", "FILE CONECTED....");
    //set the path where we want to save the file
    //in this case, going to save it on the root directory of the
    //sd card.
    File SDCardRoot = Environment.getExternalStorageDirectory();
    //create a new file, specifying the path, and the filename
    //which we want to save the file as.
    file = new File(SDCardRoot, fileName);

    //this will be used to write the downloaded data into the file we created
    FileOutputStream fileOutput = new FileOutputStream(file);
    Log.d("INFORMATION..", "WRINTING TO FILE DOWNLOADED...." + file);
    //this will be used in reading the data from the internet
    InputStream inputStream = urlConnection.getInputStream();

    //this is the total size of the file
    int totalSize = urlConnection.getContentLength();
    //variable to store total downloaded bytes
    int downloadedSize = 0;

    //create a buffer...
    byte[] buffer = new byte[1024];
    int bufferLength = 0; //used to store a temporary size of the buffer

    //now, read through the input buffer and write the contents to the file
    while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
        //add the data in the buffer to the file in the file output stream (the file on the sd card
        fileOutput.write(buffer, 0, bufferLength);
        //add up the size so we know how much is downloaded
        downloadedSize += bufferLength;
        Log.d("INFORMATION..", "FILE DOWNLOADED....");
        //this is where you would do something to report the prgress, like this maybe
        //updateProgress(downloadedSize, totalSize);

    }
    //close the output stream when done
    fileOutput.close();
    Log.d("INFORMATION..", "FILE DOWNLOADING COMPLETED....");
    //catch some possible errors...
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
return file;


 }
}

Call this DownloadImage.getImage(String imageUrl, String fileName) in MainActivity.java like this :

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ImageView imageView = (ImageView) findViewById(R.id.imageView1);

String url = "http://4.bp.blogspot.com/-8v_k_fOcfP8/UQIL4ufghBI/AAAAAAAAEDo/9ffRRTM9AnA/s1600/android-robog-alone.png"; 

String file = DownloadImage.getImage(url, "My Image.jpg").toString();

// Get file path on device and set it to imageView
Bitmap bitmap = BitmapFactory.decodeFile(file);
imageView.setImageBitmap(bitmap);
}
}

I think this what you are looking for! hope this will help you

Arshad Ali
  • 3,082
  • 12
  • 56
  • 99