IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Android Discussion :

BitmapFactory.decode retourne null


Sujet :

Android

  1. #1
    Membre habitué
    Profil pro
    Inscrit en
    Octobre 2007
    Messages
    268
    Détails du profil
    Informations personnelles :
    Âge : 44
    Localisation : France

    Informations forums :
    Inscription : Octobre 2007
    Messages : 268
    Points : 128
    Points
    128
    Par défaut BitmapFactory.decode retourne null
    Hello !

    Je suis nouveau en java et en dev android. j'ai essayé de télécharger des images jpg à partir de google image et les afficher dans une grid mais BitmapFactory.decode retourne toujours null, je ne comprends pas pourquoi ... J'ai bien vérifié qu'il ne s'agissait pas d'image en CMJN car je sais qu'il y a un bug dans le framework à ce sujet, j'ai vérifier que les images sont bien téléchargées et enregistrées sur la mémoire interne de la tablette et c'est bien le cas ... par avance, merci de votre aide

    en PJ, je projet eclipse
    Fichiers attachés Fichiers attachés

  2. #2
    Expert éminent

    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Février 2007
    Messages
    4 253
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Février 2007
    Messages : 4 253
    Points : 7 618
    Points
    7 618
    Billets dans le blog
    3
    Par défaut
    Je poste le code ici.... plus simple

    DownloadTask:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
     
    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);
    			Boolean result = newFile.createNewFile();
    			Log.d("DownloadTask", "newFile.createNewFile() " + result);
    			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();
    		}
    	}
    }

    Déjà remplacer les "e.printStackTrace()" par Log.e("XXXX","Erreur à tel ou tel endroit",e);

    Ensuite, je trouve dangereux de faire une référence au tableau en disant qu'il y a 4 éléments...
    Une simple boucle éviterait les probleme....
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    	@Override
    	protected String doInBackground(String... args) {
                    int idx = 0;
                    for (String url : args) {		
                        String name = Integer.toString(++idx)+".jpg";
    		    saveFileOnDisk(url, name);
                    }
    		return "ok"; // just to return a string
    	}
    Ensuite, si on regarde bien... les paramètres sont des URL... pourquoi ne pas passer directement des objets URL donc ? (ce qui permettrait au client d'avoir directement une erreur si une URL n'est pas formatée correctement)

    Il manque un "finally" au bloc try de saveFileOnDisk... il devrait ressembler à:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
     
    InputStream input = null;
    try {
        ...
        input = url.openConnection().getInputStream();
        ....
    } catch (Exception ex) {
        Log.e("TASK","Failed to download image file",ex);
    } finally {
        if (input != null) try { input.close(); } catch (Exception ex) { log.wtf("TASK","Failed to gracefully close input stream",ex); }
    }

    Il y a du code dupliqué pour le directory... Rajouter des fonctions genre:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    public static File getImageDirectory(Context ctxt)
    {
        return ctxt.getDir("jpgfolder", Context.MODE_PRIVATE);
    }
     
    public static File[] getImages(Context ctxt)
    {
        return getImageDirectory(ctxt).listFiles();
    }
    D'ailleurs je ne comprends pas trop le truc du ContextWrapper... on a DEJA un context avec l'activité, autant l'utiliser non ?

    Côté "activité":

    Le code:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
     
    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]);
    	        }
    	    }
    	}
    }
    Premier soucis, on récupère le gridview *après* avoir démarré la tache... donc il est possible d'avoir la fonction setGridAdapter() qui est appelé *avant* que gridview soit initialisé....

    Je suis étonné par les trucs qu'on fait dans get_images().... on recoit déjà un array de File.... pourquoi transformer chaque File en:
    File imageFile = new File(file.toString()); // toString() ???? pas sur que cela renvoit un path !

    Ne serait-il pas mieux de faire un truc genre:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    private void get_images() {
        ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>();
        for (File imgfile : DownloadTask.getImages(this.context)) {
           Bitmap bmp = BitmapFactory.decodeFile(imgfile.getAbsolutePath());
           if (bmp != null)
               bitmaps.add(bmp);
         }
         this.imgs = bitmaps.toArray(new Bitmap[bitmaps.size()]);
    }
    N'oubliez pas de cliquer sur mais aussi sur si un commentaire vous a été utile !
    Et surtout

  3. #3
    Membre habitué
    Profil pro
    Inscrit en
    Octobre 2007
    Messages
    268
    Détails du profil
    Informations personnelles :
    Âge : 44
    Localisation : France

    Informations forums :
    Inscription : Octobre 2007
    Messages : 268
    Points : 128
    Points
    128
    Par défaut
    Salut nicroman ! Tout d'abord je te remercie de ton aide précieuse car comme tu as pu le remarqué je suis encore un grand débutant
    Suite à tes remarques pertinentes, j'ai corrigé le code (en espérant ne rien avoir oublié) comme suis :

    Main.java

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
     
    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
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
     
    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;
     
    	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){
    		InputStream input = null;
    		try {
    			// in
    			input = url.openConnection().getInputStream();
     
    			// out
    			File directory = DownloadTask.getImageDirectory(this.activity);
    			File newFile = new File(directory, outputName);
    			Boolean result = newFile.createNewFile();
    			Log.d("DownloadTask", "newFile.createNewFile() " + result);
    			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();
    			return newFile.getAbsolutePath();
    		} catch (Exception ex) {
    			Log.e("TASK","Failed to download image file",ex);
    		} finally {
    		    if (input != null)
    		    	try { 
    		    		input.close(); 
    		    	}
    		    	catch (Exception ex) {
    		    		Log.e("TASK","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)
    	{
    	    return getImageDirectory(ctxt).listFiles();
    	}
     
    	public static File getImageDirectory(Context ctxt)
    	{
    	    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", "file " + i + " > " + filesInDirectory[i] + " exist?" + filesInDirectory[i].exists());
    			}
    			// set grid adapter ... cf Main.java
    			((Main) this.activity).setGridAdapter();
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    voici la sortie de logcat
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
     
    12-27 15:48:03.321: D/DownloadTask(27664): newFile.createNewFile() true
    12-27 15:48:03.453: D/DownloadTask(27664): newFile.createNewFile() true
    12-27 15:48:03.602: D/DownloadTask(27664): newFile.createNewFile() true
    12-27 15:48:03.766: D/DownloadTask(27664): newFile.createNewFile() true
    12-27 15:48:03.875: D/DownloadTask(27664): All downloads finished
    12-27 15:48:03.883: I/DownloadTask(27664): file 0 > /data/data/com.test.downloadjpgtest/app_jpgfolder/1.jpg exist?true
    12-27 15:48:03.883: I/DownloadTask(27664): file 1 > /data/data/com.test.downloadjpgtest/app_jpgfolder/2.jpg exist?true
    12-27 15:48:03.883: I/DownloadTask(27664): file 2 > /data/data/com.test.downloadjpgtest/app_jpgfolder/3.jpg exist?true
    12-27 15:48:03.883: I/DownloadTask(27664): file 3 > /data/data/com.test.downloadjpgtest/app_jpgfolder/4.jpg exist?true
    12-27 15:48:03.883: I/System.out(27664): Not a DRM File, opening notmally
    12-27 15:48:03.883: I/System.out(27664): buffer returned 
    12-27 15:48:03.891: D/skia(27664): --- SkImageDecoder::Factory returned null
    12-27 15:48:03.891: I/System.out(27664): Not a DRM File, opening notmally
    12-27 15:48:03.891: I/System.out(27664): buffer returned 
    12-27 15:48:03.891: D/skia(27664): --- SkImageDecoder::Factory returned null
    12-27 15:48:03.891: I/System.out(27664): Not a DRM File, opening notmally
    12-27 15:48:03.891: I/System.out(27664): buffer returned 
    12-27 15:48:03.899: D/skia(27664): --- SkImageDecoder::Factory returned null
    12-27 15:48:03.899: I/System.out(27664): Not a DRM File, opening notmally
    12-27 15:48:03.899: I/System.out(27664): buffer returned 
    12-27 15:48:03.899: D/skia(27664): --- SkImageDecoder::Factory returned null
    Je continue à chercher ...

  4. #4
    Expert éminent

    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Février 2007
    Messages
    4 253
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Février 2007
    Messages : 4 253
    Points : 7 618
    Points
    7 618
    Billets dans le blog
    3
    Par défaut
    Haaa ben un logcat ca va aller mieux....

    Donc en fait... skImageDecoder returned null, ca veut dire en général que les fichiers n'existent pas ou ne sont pas des images....

    Est-ce que tu peux les afficher directement depuis la galerie ?
    (si besoin change le chemin vers un chemin "public", c'est facile désormais puisque le code est à un seul endroit )

    Sinon, rajoutes un peu de log dans la fonction getImages()
    par exemple avec le chemin de l'image (file.getAbsoluteFilePath()), et les 8/10 premiers octets du fichier....
    N'oubliez pas de cliquer sur mais aussi sur si un commentaire vous a été utile !
    Et surtout

  5. #5
    Membre habitué
    Profil pro
    Inscrit en
    Octobre 2007
    Messages
    268
    Détails du profil
    Informations personnelles :
    Âge : 44
    Localisation : France

    Informations forums :
    Inscription : Octobre 2007
    Messages : 268
    Points : 128
    Points
    128
    Par défaut
    Après avoir changé les permissions dans le Manifest, je tente d'enregistrer sur la carte SD dans le répertoire des images :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
     
    public static File[] getImages(Context ctxt)
    	{
    		File[] files = getImageDirectory(ctxt).listFiles();
    		for(File f : files){
    			Log.d("DownloadTask", "getImages: " + f.getAbsolutePath());
    			if(f.canRead()){
    				int ch;
    				InputStream in = null;
    				try {
    					if(f.isFile()){
    					     in = new FileInputStream(f));
    					     if((ch = in.read()) != -1)
    					         Log.d("DownloadTask", "contenu du fichier : " + ch);
    					     else
    					    	 Log.d("DownloadTask", "fichier VIDE ! ");
    					}
    				} catch (FileNotFoundException e) {
    					Log.e("DownloadTask", "FileNotFoundException", e);
    				} catch (IOException e) {
    					Log.e("DownloadTask", "IOException", e);
    				}finally {
    				     if (in != null) {
    				         try {
    							in.close();
    						} catch (IOException e) {
    							Log.e("DownloadTask", "IOException", e);
    						}
    				      }
    				}
    			}
    		}
    	    return files;
    	}
     
    	public static File getImageDirectory(Context ctxt)
    	{
    		return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    	    //return ctxt.getDir("jpgfolder", Context.MODE_PRIVATE);
    	}
    ce qui donne le logcat :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
     
    12-27 17:47:46.203: D/DownloadTask(30966): saveFileOnDisk: newFile.createNewFile() false
    12-27 17:47:46.461: D/DownloadTask(30966): saveFileOnDisk: newFile.createNewFile() false
    12-27 17:47:46.594: D/DownloadTask(30966): saveFileOnDisk: newFile.createNewFile() false
    12-27 17:47:46.750: D/DownloadTask(30966): saveFileOnDisk: newFile.createNewFile() false
    12-27 17:47:46.844: D/DownloadTask(30966): All downloads finished
    12-27 17:47:46.852: D/DownloadTask(30966): getImages: /mnt/sdcard/Pictures/Screenshots
    12-27 17:47:46.852: D/DownloadTask(30966): getImages: /mnt/sdcard/Pictures/1.jpg
    12-27 17:47:46.852: D/DownloadTask(30966): fichier VIDE ! 
    12-27 17:47:46.852: D/DownloadTask(30966): getImages: /mnt/sdcard/Pictures/2.jpg
    12-27 17:47:46.852: D/DownloadTask(30966): fichier VIDE ! 
    12-27 17:47:46.852: D/DownloadTask(30966): getImages: /mnt/sdcard/Pictures/3.jpg
    12-27 17:47:46.852: D/DownloadTask(30966): fichier VIDE ! 
    12-27 17:47:46.852: D/DownloadTask(30966): getImages: /mnt/sdcard/Pictures/4.jpg
    12-27 17:47:46.852: D/DownloadTask(30966): fichier VIDE ! 
    12-27 17:47:46.852: I/DownloadTask(30966): onPostExecute: file 0 > /mnt/sdcard/Pictures/Screenshots exist?true
    12-27 17:47:46.852: I/DownloadTask(30966): onPostExecute: file 1 > /mnt/sdcard/Pictures/1.jpg exist?true
    12-27 17:47:46.852: I/DownloadTask(30966): onPostExecute: file 2 > /mnt/sdcard/Pictures/2.jpg exist?true
    12-27 17:47:46.852: I/DownloadTask(30966): onPostExecute: file 3 > /mnt/sdcard/Pictures/3.jpg exist?true
    12-27 17:47:46.852: I/DownloadTask(30966): onPostExecute: file 4 > /mnt/sdcard/Pictures/4.jpg exist?true
    12-27 17:47:46.860: D/DownloadTask(30966): getImages: /mnt/sdcard/Pictures/Screenshots
    12-27 17:47:46.860: D/DownloadTask(30966): getImages: /mnt/sdcard/Pictures/1.jpg
    12-27 17:47:46.860: D/DownloadTask(30966): fichier VIDE ! 
    12-27 17:47:46.860: D/DownloadTask(30966): getImages: /mnt/sdcard/Pictures/2.jpg
    12-27 17:47:46.860: D/DownloadTask(30966): fichier VIDE ! 
    12-27 17:47:46.860: D/DownloadTask(30966): getImages: /mnt/sdcard/Pictures/3.jpg
    12-27 17:47:46.860: D/DownloadTask(30966): fichier VIDE ! 
    12-27 17:47:46.860: D/DownloadTask(30966): getImages: /mnt/sdcard/Pictures/4.jpg
    12-27 17:47:46.860: D/DownloadTask(30966): fichier VIDE ! 
    12-27 17:47:46.860: I/System.out(30966): Not a DRM File, opening notmally
    12-27 17:47:46.860: I/System.out(30966): Not a DRM File, opening notmally
    12-27 17:47:46.860: I/System.out(30966): buffer returned 
    12-27 17:47:46.868: D/skia(30966): --- SkImageDecoder::Factory returned null
    12-27 17:47:46.868: I/System.out(30966): Not a DRM File, opening notmally
    12-27 17:47:46.868: I/System.out(30966): buffer returned 
    12-27 17:47:46.868: D/skia(30966): --- SkImageDecoder::Factory returned null
    12-27 17:47:46.868: I/System.out(30966): Not a DRM File, opening notmally
    12-27 17:47:46.868: I/System.out(30966): buffer returned 
    12-27 17:47:46.868: D/skia(30966): --- SkImageDecoder::Factory returned null
    12-27 17:47:46.868: I/System.out(30966): Not a DRM File, opening notmally
    12-27 17:47:46.868: I/System.out(30966): buffer returned 
    12-27 17:47:46.868: D/skia(30966): --- SkImageDecoder::Factory returned null
    Bon déjà je pense qu'il faudrait que j'attende que les 4 images soient complétement téléchargée pour appeler
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    ((Main) this.activity).setGridAdapter();
    car la ligne
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Log.d("DownloadTask", "All downloads finished");
    se déclenche à la fin du premier téléchargement.

    Cependant je ne vois rien dans la Galerie et les fichiers ne semblent pas s'enregistrer correctement (log "fichier VIDE") ...

  6. #6
    Membre habitué
    Profil pro
    Inscrit en
    Octobre 2007
    Messages
    268
    Détails du profil
    Informations personnelles :
    Âge : 44
    Localisation : France

    Informations forums :
    Inscription : Octobre 2007
    Messages : 268
    Points : 128
    Points
    128
    Par défaut
    Quelques changements : buffering de l'écriture du fichier téléchargé sur la carte SD, Affichage des octets écris dans la fonction saveFileOnDisk, et dans getimages lecture des premiers octets des images ...

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
     
    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);
    			Boolean result = newFile.createNewFile();
    			Log.d("DownloadTask", "saveFileOnDisk: newFile.createNewFile() " + result);
    			BufferedOutputStream bos = new BufferedOutputStream(this.activity.openFileOutput(outputName, Context.MODE_PRIVATE));
    			int bytesRead;
    	        byte[] data = new byte[1024];
    	        while ((bytesRead = bis.read(data)) != -1){
    	        	Log.d("DownloadTask", "writing data " + data);
    	        	bos.write(data, 0, bytesRead);
    	        }
    	        bos.flush();
    			bos.close();
    			return newFile.getAbsolutePath();
    		} catch (Exception ex) {
    			Log.e("DownloadTask","Failed to download 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";
    	}
     
    public static File[] getImages(Context ctxt)
    	{
    		File[] files = getImageDirectory(ctxt).listFiles();
    		for(File f : files){
    			Log.d("DownloadTask", "getImages: " + f.getAbsolutePath());
    			if(f.canRead()){
    				InputStream in = null;
    				try {
    					if(f.isFile()){
    						int bytesRead;
    						byte[] data = new byte[512];
    					     in = new FileInputStream(f);
    					     if((bytesRead = in.read(data)) != -1)
    					         Log.d("DownloadTask", "contenu du fichier : " + data);
    					     else
    					    	 Log.d("DownloadTask", "fichier VIDE ! ");
    					}
    				} catch (FileNotFoundException e) {
    					Log.e("DownloadTask", "FileNotFoundException", e);
    				} catch (IOException e) {
    					Log.e("DownloadTask", "IOException", e);
    				}finally {
    				     if (in != null) {
    				         try {
    							in.close();
    						} catch (IOException e) {
    							Log.e("DownloadTask", "IOException", e);
    						}
    				      }
    				}
    			}
    		}
    	    return files;
    	}
    logcat
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
     
    12-28 10:38:45.071: D/OpenGLRenderer(13203): Enabling debug mode 0
    12-28 10:38:45.305: D/DownloadTask(13203): saveFileOnDisk: newFile.createNewFile() false
    12-28 10:38:45.305: D/DownloadTask(13203): writing data [B@412862e0
    12-28 10:38:45.461: D/DownloadTask(13203): writing data [B@412862e0
    12-28 10:38:45.461: D/DownloadTask(13203): writing data [B@412862e0
    ...
    12-28 10:38:45.594: D/DownloadTask(13203): saveFileOnDisk: newFile.createNewFile() false
    12-28 10:38:45.594: D/DownloadTask(13203): writing data [B@41291840
    12-28 10:38:45.594: D/DownloadTask(13203): writing data [B@41291840
    12-28 10:38:45.594: D/DownloadTask(13203): writing data [B@41291840
    ...
    12-28 10:38:45.789: D/DownloadTask(13203): saveFileOnDisk: newFile.createNewFile() false
    12-28 10:38:45.805: D/DownloadTask(13203): writing data [B@4129a820
    12-28 10:38:45.805: D/DownloadTask(13203): writing data [B@4129a820
    12-28 10:38:45.813: D/DownloadTask(13203): writing data [B@4129a820
    ...
    12-28 10:38:46.071: D/DownloadTask(13203): saveFileOnDisk: newFile.createNewFile() false
    12-28 10:38:46.078: D/DownloadTask(13203): writing data [B@412a5f28
    12-28 10:38:46.078: D/DownloadTask(13203): writing data [B@412a5f28
    12-28 10:38:46.102: D/DownloadTask(13203): writing data [B@412a5f28
    12-28 10:38:46.203: D/DownloadTask(13203): writing data [B@412a5f28
    ...
    12-28 10:38:46.227: D/DownloadTask(13203): All downloads finished
    12-28 10:38:46.227: D/DownloadTask(13203): getImages: /mnt/sdcard/Pictures/Screenshots
    12-28 10:38:46.227: D/DownloadTask(13203): getImages: /mnt/sdcard/Pictures/1.jpg
    12-28 10:38:46.227: D/DownloadTask(13203): fichier VIDE ! 
    12-28 10:38:46.227: D/DownloadTask(13203): getImages: /mnt/sdcard/Pictures/2.jpg
    12-28 10:38:46.227: D/DownloadTask(13203): fichier VIDE ! 
    12-28 10:38:46.227: D/DownloadTask(13203): getImages: /mnt/sdcard/Pictures/3.jpg
    12-28 10:38:46.227: D/DownloadTask(13203): fichier VIDE ! 
    12-28 10:38:46.227: D/DownloadTask(13203): getImages: /mnt/sdcard/Pictures/4.jpg
    12-28 10:38:46.227: D/DownloadTask(13203): fichier VIDE ! 
    12-28 10:38:46.227: I/DownloadTask(13203): onPostExecute: file 0 > /mnt/sdcard/Pictures/Screenshots exist?true
    12-28 10:38:46.227: I/DownloadTask(13203): onPostExecute: file 1 > /mnt/sdcard/Pictures/1.jpg exist?true
    12-28 10:38:46.227: I/DownloadTask(13203): onPostExecute: file 2 > /mnt/sdcard/Pictures/2.jpg exist?true
    12-28 10:38:46.227: I/DownloadTask(13203): onPostExecute: file 3 > /mnt/sdcard/Pictures/3.jpg exist?true
    12-28 10:38:46.227: I/DownloadTask(13203): onPostExecute: file 4 > /mnt/sdcard/Pictures/4.jpg exist?true
    12-28 10:38:46.235: D/DownloadTask(13203): getImages: /mnt/sdcard/Pictures/Screenshots
    12-28 10:38:46.235: D/DownloadTask(13203): getImages: /mnt/sdcard/Pictures/1.jpg
    12-28 10:38:46.235: D/DownloadTask(13203): fichier VIDE ! 
    12-28 10:38:46.235: D/DownloadTask(13203): getImages: /mnt/sdcard/Pictures/2.jpg
    12-28 10:38:46.235: D/DownloadTask(13203): fichier VIDE ! 
    12-28 10:38:46.235: D/DownloadTask(13203): getImages: /mnt/sdcard/Pictures/3.jpg
    12-28 10:38:46.235: D/DownloadTask(13203): fichier VIDE ! 
    12-28 10:38:46.235: D/DownloadTask(13203): getImages: /mnt/sdcard/Pictures/4.jpg
    12-28 10:38:46.235: D/DownloadTask(13203): fichier VIDE ! 
    12-28 10:38:46.235: I/System.out(13203): Not a DRM File, opening notmally
    12-28 10:38:46.235: I/System.out(13203): Not a DRM File, opening notmally
    12-28 10:38:46.235: I/System.out(13203): buffer returned 
    12-28 10:38:46.243: D/skia(13203): --- SkImageDecoder::Factory returned null
    12-28 10:38:46.243: I/System.out(13203): Not a DRM File, opening notmally
    12-28 10:38:46.243: I/System.out(13203): buffer returned 
    12-28 10:38:46.243: D/skia(13203): --- SkImageDecoder::Factory returned null
    12-28 10:38:46.243: I/System.out(13203): Not a DRM File, opening notmally
    12-28 10:38:46.243: I/System.out(13203): buffer returned 
    12-28 10:38:46.266: D/skia(13203): --- SkImageDecoder::Factory returned null
    12-28 10:38:46.266: I/System.out(13203): Not a DRM File, opening notmally
    12-28 10:38:46.266: I/System.out(13203): buffer returned 
    12-28 10:38:46.266: D/skia(13203): --- SkImageDecoder::Factory returned null
    12-28 10:38:46.282: D/dalvikvm(13203): GC_CONCURRENT freed 360K, 6% free 6811K/7239K, paused 2ms+2ms
    Avec la galerie, je vois bien qu'il y a 4 images mais elles sont toutes noires

  7. #7
    Membre habitué
    Profil pro
    Inscrit en
    Octobre 2007
    Messages
    268
    Détails du profil
    Informations personnelles :
    Âge : 44
    Localisation : France

    Informations forums :
    Inscription : Octobre 2007
    Messages : 268
    Points : 128
    Points
    128
    Par défaut
    Lorsque je récupère les images sur le device :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
     
    adb pull "/sdcard/Pictures/1.jpg"
    adb pull "/sdcard/Pictures/2.jpg"
    adb pull "/sdcard/Pictures/3.jpg"
    adb pull "/sdcard/Pictures/4.jpg"
    les JPGs font 0 octets ...

  8. #8
    Membre habitué
    Profil pro
    Inscrit en
    Octobre 2007
    Messages
    268
    Détails du profil
    Informations personnelles :
    Âge : 44
    Localisation : France

    Informations forums :
    Inscription : Octobre 2007
    Messages : 268
    Points : 128
    Points
    128
    Par défaut
    Bon sur la carte SD ça fonctionne en changeant ceci (probablement une erreur de chemin ... ) :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
     
    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);
    	        }
    	        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";
    	}

Discussions similaires

  1. BitmapFactory.decodeStream(.) qui retourne null ?
    Par Matf4ke dans le forum Android
    Réponses: 9
    Dernier message: 03/08/2012, 14h03
  2. TTF_OpenFont() retournant NULL
    Par FabaCoeur dans le forum SDL
    Réponses: 4
    Dernier message: 11/04/2007, 16h30
  3. GetDC retourne NULL Oo
    Par Groove dans le forum OpenGL
    Réponses: 3
    Dernier message: 02/03/2007, 17h46
  4. Réponses: 3
    Dernier message: 02/03/2007, 11h41
  5. opérateur + dans SELECT retourne null ?
    Par david_chardonnet dans le forum MS SQL Server
    Réponses: 2
    Dernier message: 19/01/2007, 10h47

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo