Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9089257
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T22:06:46+00:00 2026-06-16T22:06:46+00:00

I’m new in Java and Android dev. I tried to download jpg images from

  • 0

I’m new in Java and Android dev. I tried to download jpg images from google image and show them in a grid but BitmapFactory.decode always returns null. I work on a mac and i didn’t suceed to launch an avd to check the files downloaded (i don’t have access to the files hierarchy on a device with ADT … i guess it works only for an AVD). I checked not to download CMJN images, i checked that the files are well downloaded without success…

Here is the full code … any help is appreciated 🙂

Android Manisfest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.downloadjpgtest"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk
    android:minSdkVersion="15"
    android:targetSdkVersion="16" />
<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
        <activity
            android:name="com.test.downloadjpgtest.Main"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/gridview"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:columnWidth="90dp"
    android:numColumns="auto_fit"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
/>

com.test.downloadjpgtest/Main.java

package com.test.downloadjpgtest;

import java.io.File;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

public class Main extends Activity {
GridView gridview;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // GetLibraryTask
    DownloadTask downloadTask = new DownloadTask(this);
    downloadTask.execute("http://sphotos-b.xx.fbcdn.net/hphotos-ash4/c0.0.400.400/p403x403/382050_498705510162306_1891776516_n.jpg",
                                                "http://data.alipson.fr/ravensburger.17/ravensburger-puzzle-1000-pieces-panoramique-amitie-entre-animaux-.44481-1.jpg",
                                                "http://a388.idata.over-blog.com/400x400/3/03/14/36/mammiferes/lynx-canada-04.jpg",
                                                "http://photos.ugal.com/6353/43314/205322/246370/vignette-chapeaux-animaux.400.jpg"
                                                );

    // grille des couvertures
    gridview = (GridView) findViewById(R.id.gridview);
}

// called well all downloads finished
public void setGridAdapter(){
    gridview.setAdapter(new ImageAdapter(this));

    gridview.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            Toast.makeText(Main.this, "" + position, Toast.LENGTH_SHORT).show();
        }
    });
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
    }
    return super.onOptionsItemSelected(item);
}


public class ImageAdapter extends BaseAdapter {
    private Context mContext;
    public Bitmap[] imgs;

    public ImageAdapter(Context c) {
        mContext = c;
        get_images();
    }

    public int getCount() {
        return imgs.length;
    }

    public Object getItem(int position) {
        return imgs[position];
    }

    public long getItemId(int position) {
        return 0;
    }

    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {  // if it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
        } else {
            imageView = (ImageView) convertView;
        }
        imageView.setImageBitmap(imgs[position]);
        return imageView;
    }

    private void get_images(){
        File directory = mContext.getDir("jpgfolder", Context.MODE_PRIVATE);
        File[] filesInJPGFolder = directory.listFiles();
        imgs = new Bitmap[filesInJPGFolder.length];

        for (int cpt=0; cpt<filesInJPGFolder.length;cpt++){
            File imgFile = new  File(filesInJPGFolder[cpt].toString());
            imgs[cpt] = BitmapFactory.decodeFile(imgFile.getAbsolutePath()); // imgs[cpt] Always Null !!!!!!!!!
            Log.d("Main", "imgCovers[cpt] " + imgs[cpt]);
        }
    }
}

}

com.test.downloadjpgtest/DownloadTask.java

package com.test.downloadjpgtest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.client.ClientProtocolException;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.os.AsyncTask;
import android.util.Log;


public class DownloadTask extends AsyncTask<String, Void, String> {
private Activity activity;
private static final int files2Download = 4;
private static int filesDownloaded = 0;

public DownloadTask(Activity activity){
    this.activity = activity;
}
@Override
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected String doInBackground(String... args) {               
    this.saveFileOnDisk(args[0], "1.jpg");
    this.saveFileOnDisk(args[1], "2.jpg");
    this.saveFileOnDisk(args[2], "3.jpg");
    this.saveFileOnDisk(args[3], "4.jpg");
    return "ok"; // just to return a string
}

protected String saveFileOnDisk(String urlString, String outputName){
    try {
        // in
        URL url = new URL(urlString);
        InputStream input = url.openConnection().getInputStream();

        // out
        ContextWrapper contextWrapper = new ContextWrapper(activity.getApplicationContext());
        File directory = contextWrapper.getDir("jpgfolder", Context.MODE_PRIVATE);
        File newFile = new File(directory, outputName);
        newFile.createNewFile();
        FileOutputStream fos = this.activity.getApplicationContext().openFileOutput(outputName, Context.MODE_PRIVATE);
        int read;
        byte[] data = new byte[1024];
        while ((read = input.read(data)) != -1)
            fos.write(data, 0, read);
        fos.close();
        DownloadTask.filesDownloaded++;
        return newFile.getAbsolutePath();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "ko";
}

protected void onProgressUpdate(String... progress) {
    Log.i("progress", progress[0]);
}

@Override
protected void onPostExecute(String result) {
    try {
        Log.d("DownloadTask", "All downloads finished");
        // check downloaded files
                    ContextWrapper contextWrapper = new ContextWrapper(activity.getApplicationContext());
                    File directory = contextWrapper.getDir("jpgfolder", Context.MODE_PRIVATE);
                    File[] filesInDirectory = directory.listFiles();
                    for(int i=0, max = filesInDirectory.length; i < max; i++){
                        Log.i("DownloadTask", "file " + i + " > " + filesInDirectory[i] + " exist?" + filesInDirectory[i].exists());
                    }
        // set grid adapter ... cf Main.java
        ((Main) this.activity).setGridAdapter();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T22:06:47+00:00Added an answer on June 16, 2026 at 10:06 pm

    Just a few changes to make i work :

    Main.java

    package com.test.downloadjpgtest;
    
    import java.io.File;
    import java.util.ArrayList;
    
    import android.app.Activity;
    import android.content.Context;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.os.Bundle;
    import android.support.v4.app.NavUtils;
    import android.util.Log;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.BaseAdapter;
    import android.widget.GridView;
    import android.widget.ImageView;
    import android.widget.Toast;
    
    public class Main extends Activity {
        GridView gridview;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            // récupère la GridView
            gridview = (GridView) findViewById(R.id.gridview);
    
            // GetLibraryTask
            DownloadTask downloadTask = new DownloadTask(this);
            downloadTask.execute("http://sphotos-b.xx.fbcdn.net/hphotos-ash4/c0.0.400.400/p403x403/382050_498705510162306_1891776516_n.jpg",
                                 "http://data.alipson.fr/ravensburger.17/ravensburger-puzzle-1000-pieces-panoramique-amitie-entre-animaux-.44481-1.jpg",
                                 "http://a388.idata.over-blog.com/400x400/3/03/14/36/mammiferes/lynx-canada-04.jpg",
                                 "http://photos.ugal.com/6353/43314/205322/246370/vignette-chapeaux-animaux.400.jpg");
        }
    
        // called well all downloads finished
        public void setGridAdapter(){
            gridview.setAdapter(new ImageAdapter(this));
    
            gridview.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                    Toast.makeText(Main.this, "" + position, Toast.LENGTH_SHORT).show();
                }
            });
        }
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                case android.R.id.home:
                    NavUtils.navigateUpFromSameTask(this);
                    return true;
            }
            return super.onOptionsItemSelected(item);
        }
    
    
        public class ImageAdapter extends BaseAdapter {
            private Context mContext;
            public Bitmap[] imgs;
    
            public ImageAdapter(Context c) {
                mContext = c;
                getImages();
            }
    
            public int getCount() {
                return imgs.length;
            }
    
            public Object getItem(int position) {
                return imgs[position];
            }
    
            public long getItemId(int position) {
                return 0;
            }
    
            // create a new ImageView for each item referenced by the Adapter
            public View getView(int position, View convertView, ViewGroup parent) {
                ImageView imageView;
                if (convertView == null) {  // if it's not recycled, initialize some attributes
                    imageView = new ImageView(mContext);
                    imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
                    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    imageView.setPadding(8, 8, 8, 8);
                } else {
                    imageView = (ImageView) convertView;
                }
                imageView.setImageBitmap(imgs[position]);
                return imageView;
            }
    
            private void getImages(){
                ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>();
                for (File imgfile : DownloadTask.getImages(this.mContext)) {
                   Bitmap bmp = BitmapFactory.decodeFile(imgfile.getAbsolutePath());
                   if (bmp != null)
                       bitmaps.add(bmp);
                 }
                 this.imgs = bitmaps.toArray(new Bitmap[bitmaps.size()]);
            }
    
    
        }
    }
    

    DownloadTask.java

    package com.test.downloadjpgtest;
    
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.MalformedURLException;
    import java.net.URL;
    import android.app.Activity;
    import android.content.Context;
    import android.os.AsyncTask;
    import android.os.Environment;
    import android.util.Log;
    
    
    public class DownloadTask extends AsyncTask<String, Void, String> {
        private Activity activity;
    
        public DownloadTask(Activity activity){
            this.activity = activity;
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
    
        @Override
        protected String doInBackground(String... args) {       
            int idx = 0;
            for (String urlString : args) {     
                String name = Integer.toString(++idx)+".jpg";
                URL url = null;
                try {
                    url = new URL(urlString);
                } catch (MalformedURLException ex) {
                    Log.e("DownloadTask","MalformedURLException",ex);
                }
                saveFileOnDisk(url, name);
            }
            return "ok"; // just to return a string
        }
    
        protected String saveFileOnDisk(URL url, String outputName){
            BufferedInputStream bis = null;
            try {
                bis = new BufferedInputStream(url.openConnection().getInputStream());
                File directory = DownloadTask.getImageDirectory(this.activity);
                File newFile = new File(directory, outputName);
    
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFile));
                int bytesRead;
                byte[] data = new byte[4096];
                while ((bytesRead = bis.read(data)) != -1){
                    bos.write(data, 0, bytesRead);
                }
                Log.d("DownloadTask", "writing data bos " + directory.getAbsolutePath() + '/' + outputName);
                bos.flush();
                bos.close();
                return newFile.getAbsolutePath();
            } catch (Exception ex) {
                Log.e("DownloadTask","Failed to download or write image file",ex);
            } finally {
                if (bis != null)
                    try { 
                        bis.close(); 
                    }
                    catch (Exception ex) {
                        Log.e("DownloadTask","Failed to gracefully close input stream",ex);
                    }
            }
            return "ko";
        }
    
        protected void onProgressUpdate(String... progress) {
            Log.i("progress", progress[0]);
        }
    
        public static File[] getImages(Context ctxt)
        {
            File[] files = getImageDirectory(ctxt).listFiles();
            return files;
        }
    
        public static File getImageDirectory(Context ctxt)
        {
            return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            //return ctxt.getDir("jpgfolder", Context.MODE_PRIVATE);
        }
    
        @Override
        protected void onPostExecute(String result) {
            try {
                Log.d("DownloadTask", "All downloads finished");
                // check downloaded files
                File[] filesInDirectory = DownloadTask.getImages(this.activity);
                for(int i=0, max = filesInDirectory.length; i < max; i++){
                    Log.i("DownloadTask", "onPostExecute: file " + i + " > " + filesInDirectory[i]);
                }
                // set grid adapter ... cf Main.java
                ((Main) this.activity).setGridAdapter();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am using jsonparser to parse data and images obtained from json response. When
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text
I want use html5's new tag to play a wav file (currently only supported
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I want to show the soap response to UIWebview.. my soap response is, <p><img
I have a text area in my form which accepts all possible characters from
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.