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 :

Parser JSON problème d'image


Sujet :

Android

  1. #21
    Membre habitué
    Homme Profil pro
    Inscrit en
    Octobre 2011
    Messages
    281
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Octobre 2011
    Messages : 281
    Points : 161
    Points
    161
    Par défaut
    J'ai essayer sans l'image et cela fonctionne très bien mais lorsque que je met l'image (donc thumb), j'ai des erreurs à ces 3 lignes :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    URL url = new URL(mylist.get (position).get ("thumb").toString ());
    		URLConnection ucon = url.openConnection();
    		InputStream is = ucon.getInputStream();
    Il me propose de faire un surround with try/catch.

    Pour rappel voici mon Adapter

    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.pxr.tutorial.json;
     
    import java.io.BufferedInputStream;
    import java.io.InputStream;
    import java.net.URL;
    import java.net.URLConnection;
    import java.util.ArrayList;
    import java.util.HashMap;
    import com.pxr.tutorial.xmltest.R;
    import android.content.Context;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;
     
    public class myBaseAdapter extends BaseAdapter
    {
    	ArrayList<HashMap<String, String>> mylist;
    	LayoutInflater	inflater;
    	ImageView img;
     
    	public myBaseAdapter (Context context, ArrayList<HashMap<String, String>> myList)
    	{
    		inflater = LayoutInflater.from (context);
    		this.mylist = myList;
    	}
     
    	public int getCount ()
    	{
    		return mylist.size ();
    	}
     
    	public Object getItem (int position)
    	{
    		return mylist.get (position);
    	}
     
    	public long getItemId (int position)
    	{
    		// TODO Auto-generated method stub
    		return position;
    	}
     
    	public View getView (int position, View convertView, ViewGroup parent)
    	{
    		ViewHolder holder;
    		if (convertView == null)
    		{
    			holder = new ViewHolder ();
    			convertView = inflater.inflate (R.layout.listplaceholder, null);
    			holder.titre = (TextView) convertView.findViewById (R.id.item_title);
    			holder.extrait = (TextView) convertView.findViewById (R.id.item_subtitle);
    		    holder.thumb = (ImageView) convertView.findViewById (R.id.item_thumb);
    			holder.date = (TextView) convertView.findViewById (R.id.item_date);
    		}
    		else
    		{
    			holder = (ViewHolder) convertView.getTag ();
    		}
     
    		holder.titre.setText (mylist.get (position).get ("titre").toString ());
    		holder.extrait.setText (mylist.get (position).get ("extrait").toString ());
    		holder.date.setText (mylist.get (position).get ("date").toString ());
     
     
    		URL url = new URL(mylist.get (position).get ("thumb").toString ());
    		URLConnection ucon = url.openConnection();
    		InputStream is = ucon.getInputStream();
    		BufferedInputStream bis = new BufferedInputStream(is);
     
    		Bitmap bm = BitmapFactory.decodeStream(is);
    		holder.thumb.setImageBitmap(bm);	
     
    		convertView.setTag (holder);
     
    		return convertView;
    	}
     
    	public class ViewHolder
    	{
    		TextView	titre;
    		TextView	extrait;
    		ImageView	thumb;
    		TextView	date;
    	}
     
     
    }

  2. #22
    Rédacteur
    Avatar de David55
    Homme Profil pro
    Ingénieur informatique
    Inscrit en
    Août 2010
    Messages
    1 542
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Ingénieur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Août 2010
    Messages : 1 542
    Points : 2 808
    Points
    2 808
    Par défaut
    Pouvons nous avoir l'erreur?

    De plus, ajoute un try/catch c'est mieux effectivement!

  3. #23
    Membre habitué
    Homme Profil pro
    Inscrit en
    Octobre 2011
    Messages
    281
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Octobre 2011
    Messages : 281
    Points : 161
    Points
    161
    Par défaut
    C'est bon j'ai régler le problème et tout marche.

    Par contre mon activité se trouve sur une navigation par onglet. Et j'ai remarqué que le temps de passage d'un onlget quelconque à mon onglet où se trouve mes items (articles), est très long.

    Je pense que c'est à cause des images. N'y a t'il pas un moyen pour que les images se mettent dans le cache pour pas qu'a chaque fois que je revienne sur l'onglet cela mette du temps à s'afficher

  4. #24
    Rédacteur
    Avatar de David55
    Homme Profil pro
    Ingénieur informatique
    Inscrit en
    Août 2010
    Messages
    1 542
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Ingénieur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Août 2010
    Messages : 1 542
    Points : 2 808
    Points
    2 808
    Par défaut
    Tu peux toujours enregistrer tes images dans un tableau que tu enregistrerais dans une variable globale. D'ailleurs, je te conseille d'enregistrer tes images dans un tableau dans ton adapteur afin de ne pas les télécharger à chaque fois que tu scroll!

    Sinon, d'une façon plus propre tu peux créer un thread afin de ne pas bloquer ton application lors du chargement!

  5. #25
    Membre habitué
    Homme Profil pro
    Inscrit en
    Octobre 2011
    Messages
    281
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Octobre 2011
    Messages : 281
    Points : 161
    Points
    161
    Par défaut
    Citation Envoyé par David55 Voir le message
    Tu peux toujours enregistrer tes images dans un tableau que tu enregistrerais dans une variable globale. D'ailleurs, je te conseille d'enregistrer tes images dans un tableau dans ton adapteur afin de ne pas les télécharger à chaque fois que tu scroll!
    Comment faire ca ?

  6. #26
    Rédacteur
    Avatar de David55
    Homme Profil pro
    Ingénieur informatique
    Inscrit en
    Août 2010
    Messages
    1 542
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Ingénieur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Août 2010
    Messages : 1 542
    Points : 2 808
    Points
    2 808
    Par défaut
    Et bien c'est assez long à expliquer!


    Il faut que tu crées une classe qui étend Application:
    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
     
    public class myApplication extends Application
    {
    	private GlobalClass	_global	= null;
     
    	public GlobalClass	getGlobalClass ()
    	{
    		if (_global == null)
    		{
    			_global = new GlobalClass ();
    		}
    		return (_global);
    	}
     
    	@Override
    	public void onCreate ()
    	{
    		super.onCreate ();
    	}
     
    	@Override
    	public void onConfigurationChanged (Configuration newConfig)
    	{
    		super.onConfigurationChanged (newConfig);
    	}
    }
    Ensuite, il faut créer la classe GlobalClass:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
     
    public class GlobalClass
    {
    // Ici tu stockes ton tableau d'image en public ou en privé avec getter et setter du coup
    }
    Puis dans ton activité pour récupérer l'instance de ta classe GlobalClass tu fais:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    GlobalClass _global = ((myApplication) getApplication ()).getGlobalClass ();
    Puis tu peux récupérer ton tableau facilement!

    Il ne faut pas oublier de changer dans ton manifest le nom d eton application:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
     
    <application
            android:name="com.webtiss.avenance.presence.myApplication"
            android:icon="@drawable/icon"
            android:label="@string/app_name" >

  7. #27
    Membre habitué
    Homme Profil pro
    Inscrit en
    Octobre 2011
    Messages
    281
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Octobre 2011
    Messages : 281
    Points : 161
    Points
    161
    Par défaut
    Cette instruction

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    GlobalClass _global = ((myApplication) getApplication ()).getGlobalClass ();
    Je la met dans mon Adapter ?

  8. #28
    Rédacteur
    Avatar de David55
    Homme Profil pro
    Ingénieur informatique
    Inscrit en
    Août 2010
    Messages
    1 542
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Ingénieur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Août 2010
    Messages : 1 542
    Points : 2 808
    Points
    2 808
    Par défaut
    Si tu veux la mettre dans ton adapter alors il faut passer ton activity en paramètre dans ton constructeur!

  9. #29
    Membre habitué
    Homme Profil pro
    Inscrit en
    Octobre 2011
    Messages
    281
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Octobre 2011
    Messages : 281
    Points : 161
    Points
    161
    Par défaut
    Bonjour,

    j'ai trouver un exemple de classe sur google, pensez vous que cela puisse faire l'affaire ?

    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
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    package com.example;
     
    import java.io.File;
    import java.io.FileOutputStream;
    import java.lang.ref.SoftReference;
    import java.net.URL;
    import java.util.HashMap;
    import java.util.Stack;
     
    import android.app.Activity;
    import android.content.Context;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.widget.ImageView;
     
    public class ImageManager {
     
    	private HashMap<String, SoftReference<Bitmap>> imageMap = new HashMap<String, SoftReference<Bitmap>>();
     
    	private File cacheDir;
    	private ImageQueue imageQueue = new ImageQueue();
    	private Thread imageLoaderThread = new Thread(new ImageQueueManager());
     
    	public ImageManager(Context context) {
    		// Make background thread low priority, to avoid affecting UI performance
    		imageLoaderThread.setPriority(Thread.NORM_PRIORITY-1);
     
    		// Find the dir to save cached images
    		String sdState = android.os.Environment.getExternalStorageState();
    		if (sdState.equals(android.os.Environment.MEDIA_MOUNTED)) {
    			File sdDir = android.os.Environment.getExternalStorageDirectory();		
    			cacheDir = new File(sdDir,"data/codehenge");
    		}
    		else
    			cacheDir = context.getCacheDir();
     
    		if(!cacheDir.exists())
    			cacheDir.mkdirs();
    	}
     
    	public void displayImage(String url, Activity activity, ImageView imageView) {
    		if(imageMap.containsKey(url))
    			imageView.setImageBitmap(imageMap.get(url).get());
    		else {
    			queueImage(url, activity, imageView);
    			imageView.setImageResource(R.drawable.icon);
    		}
    	}
     
    	private void queueImage(String url, Activity activity, ImageView imageView) {
    		// This ImageView might have been used for other images, so we clear 
    		// the queue of old tasks before starting.
    		imageQueue.Clean(imageView);
    		ImageRef p=new ImageRef(url, imageView);
     
    		synchronized(imageQueue.imageRefs) {
    			imageQueue.imageRefs.push(p);
    			imageQueue.imageRefs.notifyAll();
    		}
     
    		// Start thread if it's not started yet
    		if(imageLoaderThread.getState() == Thread.State.NEW)
    			imageLoaderThread.start();
    	}
     
    	private Bitmap getBitmap(String url) {
    		String filename = String.valueOf(url.hashCode());
    		File f = new File(cacheDir, filename);
     
    		// Is the bitmap in our cache?
    		Bitmap bitmap = BitmapFactory.decodeFile(f.getPath());
    		if(bitmap != null) return bitmap;
     
    		// Nope, have to download it
    		try {
    			bitmap = BitmapFactory.decodeStream(new URL(url).openConnection().getInputStream());
    			// save bitmap to cache for later
    			writeFile(bitmap, f);
     
    			return bitmap;
    		} catch (Exception ex) {
    			ex.printStackTrace();
    			return null;
    		}
    	}
     
    	private void writeFile(Bitmap bmp, File f) {
    		FileOutputStream out = null;
     
    		try {
    			out = new FileOutputStream(f);
    			bmp.compress(Bitmap.CompressFormat.PNG, 80, out);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		finally { 
    			try { if (out != null ) out.close(); }
    			catch(Exception ex) {} 
    		}
    	}
     
    	/** Classes **/
     
    	private class ImageRef {
    		public String url;
    		public ImageView imageView;
     
    		public ImageRef(String u, ImageView i) {
    			url=u;
    			imageView=i;
    		}
    	}
     
    	//stores list of images to download
    	private class ImageQueue {
    		private Stack<ImageRef> imageRefs = 
    			new Stack<ImageRef>();
     
    		//removes all instances of this ImageView
    		public void Clean(ImageView view) {
     
    			for(int i = 0 ;i < imageRefs.size();) {
    				if(imageRefs.get(i).imageView == view)
    					imageRefs.remove(i);
    				else ++i;
    			}
    		}
    	}
     
    	private class ImageQueueManager implements Runnable {
    		public void run() {
    			try {
    				while(true) {
    					// Thread waits until there are images in the 
    					// queue to be retrieved
    					if(imageQueue.imageRefs.size() == 0) {
    						synchronized(imageQueue.imageRefs) {
    							imageQueue.imageRefs.wait();
    						}
    					}
     
    					// When we have images to be loaded
    					if(imageQueue.imageRefs.size() != 0) {
    						ImageRef imageToLoad;
     
    						synchronized(imageQueue.imageRefs) {
    							imageToLoad = imageQueue.imageRefs.pop();
    						}
     
    						Bitmap bmp = getBitmap(imageToLoad.url);
    						imageMap.put(imageToLoad.url, new SoftReference<Bitmap>(bmp));
    						Object tag = imageToLoad.imageView.getTag();
     
    						// Make sure we have the right view - thread safety defender
    						if(tag != null && ((String)tag).equals(imageToLoad.url)) {
    							BitmapDisplayer bmpDisplayer = 
    								new BitmapDisplayer(bmp, imageToLoad.imageView);
     
    							Activity a = 
    								(Activity)imageToLoad.imageView.getContext();
     
    							a.runOnUiThread(bmpDisplayer);
    						}
    					}
     
    					if(Thread.interrupted())
    						break;
    				}
    			} catch (InterruptedException e) {}
    		}
    	}
     
    	//Used to display bitmap in the UI thread
    	private class BitmapDisplayer implements Runnable {
    		Bitmap bitmap;
    		ImageView imageView;
     
    		public BitmapDisplayer(Bitmap b, ImageView i) {
    			bitmap=b;
    			imageView=i;
    		}
     
    		public void run() {
    			if(bitmap != null)
    				imageView.setImageBitmap(bitmap);
    			else
    				imageView.setImageResource(R.drawable.icon);
    		}
    	}
    }

Discussions similaires

  1. Réponses: 3
    Dernier message: 05/07/2005, 18h07
  2. problème affichage image
    Par thealpacino dans le forum Balisage (X)HTML et validation W3C
    Réponses: 8
    Dernier message: 30/05/2005, 13h56
  3. [javascript] problème insertion image
    Par Pwill dans le forum Général JavaScript
    Réponses: 6
    Dernier message: 18/05/2005, 16h12
  4. problème dessiner image dans fenêtre
    Par raoulman dans le forum MFC
    Réponses: 5
    Dernier message: 13/12/2004, 15h44
  5. Problème d'image avec DirectX9 et c# VS.net...
    Par lilly_lilly dans le forum DirectX
    Réponses: 1
    Dernier message: 02/03/2004, 14h02

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