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

Composants graphiques Android Discussion :

Afficher Images ListView


Sujet :

Composants graphiques Android

  1. #1
    Membre du Club
    Profil pro
    Inscrit en
    Mai 2010
    Messages
    61
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2010
    Messages : 61
    Points : 42
    Points
    42
    Par défaut Afficher Images ListView
    Bonjour à tous,

    Je réalise une application de flux rss, j'ai suivis un petit tuto pour afficher des images et du texte dans une ListView (Le voici: http://a-renouard.developpez.com/tut...iser-listview/ )
    Ma ListView s'affiche avec le texte, mais pas les images. J'ai lu que SimpleAdapter n'était pas à utiliser lorsqu'on est pas en local.

    Lorsque ma liste s'affiche, j'ai ces erreurs dans le logcat:

    10-29 11:26:31.275: E/Bitmap(20655): returned
    10-29 11:26:34.350: E/src(20655): http://rss.nouvelobs.com/c/32262/f/4...pg/6578646.jpg



    Voilà pour chaque image j'ai ça. Voici le code de ma classe:

    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
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    package com.android.rss;
     
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.HashMap;
     
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
     
     
    import android.app.Fragment;
    import android.content.Context;
    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.graphics.drawable.BitmapDrawable;
    import android.graphics.drawable.Drawable;
    import android.os.Bundle;
    import android.os.StrictMode;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.view.WindowManager;
    import android.view.inputmethod.InputMethodManager;
    import android.webkit.WebView;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.ArrayAdapter;
    import android.widget.GridLayout;
    import android.widget.SimpleAdapter;
    import android.widget.ImageView;
    import android.widget.ListView;
    import android.widget.TextView;
     
    public class MyFragmentB extends Fragment {
     
    	String value = "";
    	String str;
    	String urlImg;
     
    	View v;
     
    	TextView text;
    	TextView text2;
    	TextView textInfo;
     
    	ArrayAdapter<String> itemAdapter;
    	ArrayList<String> arrayDescription;
    	ArrayList<String> arrayImage;
    	ArrayList<String> arrayTitre;
     
    	View myFragmentView;
     
    	ListView listView;
    	ListView listView2;
     
    	ImageView imageView;
     
     
    	WebView imgWeb;
     
    	XMLParser file;
     
    	Document doc;
     
    	GridLayout gridLayout;
     
    	//------------------------ Tableau qui sera inséré dans le ListView---------------------
    	//Création de la ArrayList qui nous permettra de remplir la listView
        ArrayList<HashMap<String, String>> listData = new ArrayList<HashMap<String, String>>();
     
        //On déclare la HashMap qui contiendra les informations pour un item
        HashMap<String, String> map;
    		 @Override
    		 public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
     
    			  getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    			  myFragmentView = inflater.inflate(R.layout.fragment_a, container, false);
     
     
     
    			  arrayDescription = new ArrayList<String>();
    			  arrayImage = new ArrayList<String>();
    			  arrayTitre = new ArrayList<String>();
     
     
    			  text = (TextView)myFragmentView.findViewById(R.id.txt2);
     
     
     
    			  InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    		      imm.hideSoftInputFromWindow(myFragmentView.findViewById(R.id.txt).getWindowToken(), 0);
     
     
     
     
    			  str = httpRequest("http://tempsreel.nouvelobs.com/rss.xml");
    			  /*Autres sites
    			  *http://rss.lemonde.fr/c/205/f/3050/index.rss
    			  *http://tempsreel.nouvelobs.com/rss.xml*/
     
    			   setList(str);
     
     
     
     
     
     
    			  return myFragmentView;
     
    		 }
     
     
     
     
    		  public String httpRequest (String adress){
    			  String answer = "", temp = "";
     
    				  try{
    					  URL url = new URL(adress);
    					  HttpURLConnection con = (HttpURLConnection) url.openConnection();
    					  InputStream in = con.getInputStream();
    					  BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    					  while ((temp = reader.readLine()) != null){
    						answer = answer + temp;
    					  }
    					  reader.close();
    				  }catch (Exception e){}
     
    			  return answer;
    		 }
     
     
    		  public void setList(String str){
     
    			    file = new XMLParser();
    	            doc = file.getDomElement(str);
    	            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    				StrictMode.setThreadPolicy(policy);
     
    				//doc.getElementsByTagName("title").getLength()
    	            for(int i=2;i<doc.getElementsByTagName("title").getLength()-2;i++){
     
    	            	try{
    	            		map = new HashMap<String, String>();
    			            Element e = (Element) doc.getElementsByTagName("title").item(i);
    				        String id = file.getElementValue(e);
    					    //Ajout du titre pour un seul item
    					    map.put("titre", id);
     
     
     
    					    Element elemDescription = (Element) doc.getElementsByTagName("description").item(i-1);
    				        String idDescription = file.getElementValue(elemDescription);
    					    arrayDescription.add(idDescription);
     
     
     
    					    Element elemImage = (Element) doc.getElementsByTagName("enclosure").item(i-2);
    				        String idImage = elemImage.getAttribute("url");
    					    arrayImage.add(idImage);
     
     
     
    					    Bitmap bimage = getBitmapFromURL(arrayImage.get(i-2));
    					    Drawable d = new BitmapDrawable(getResources(),bimage);
     
     
    					    map.put("img", String.valueOf(d));
     
    					    listData.add(map);
     
     
     
    	            	}catch(NullPointerException e){} 
    	            }
     
     
    			  listView = (ListView)myFragmentView.findViewById(R.id.list);
     
    			  SimpleAdapter mSchedule = new SimpleAdapter (getActivity().getBaseContext(), listData, R.layout.affichageitem,new String[] {"img", "titre"}, new int[] {R.id.img, R.id.titre});
    			  //On attribue à notre listView l'adapter que l'on vient de créer
    		      listView.setAdapter(mSchedule);
     
    			  //Reaction aux clicks sur les item de la ListView
    			  listView.setOnItemClickListener(new OnItemClickListener() {
    			        public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
    			          //When clicked, show a toast with the TextView text
     
    			        	Intent myIntent[] = new Intent[arrayTitre.size()];
    			        	for(int i = 0;i < arrayTitre.size(); i++){
     
    			        		/*try{
    				        		Intent in = new Intent(Intent.ACTION_VIEW,Uri.parse(arrayURL.get(i)));
    				        		startActivity(in);
    				        		getActivity().finish();
    			        		}catch(ActivityNotFoundException e){}*/
     
    			        		if(position == i){
     
     
    				        		//code specific to first list item    
    							    myIntent[i] = new Intent(view.getContext(), Article.class);
     
    							    //Passage de paramètres à la nouvelle activité
    							    myIntent[i].putExtra("str",value);
    							    myIntent[i].putExtra("img",arrayImage.get(i));
    							    myIntent[i].putExtra("description",arrayDescription.get(i));
    							    myIntent[i].putExtra("titre",arrayTitre.get(i));
    							    startActivityForResult(myIntent[i], 0);
    			        		}
     
     
    			        	}
     
     
    				    }
    			  });
     
     
    		  }
     
     
     
     
    		  public static Bitmap getBitmapFromURL(String src) {
    		          try {
    		              Log.e("src",src);
    		              URL url = new URL(src);
    		              HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    		              connection.setDoInput(true);
    		              connection.connect();
    		              InputStream input = connection.getInputStream();
    		              Bitmap myBitmap = BitmapFactory.decodeStream(input);
    		              Log.e("Bitmap","returned");
    		              return myBitmap;
    		          } catch (IOException e) {
    		              e.printStackTrace();
    		              Log.e("Exception",e.getMessage());
    		              return null;
    		          }
    		      }
     
     
     
    	}
    Merci d'avance pour vos réponse.

    Bien cordialement.

  2. #2
    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
    Le plus simple est de redéfinir ton SimpleAdapter pour afficher ton image.

    Voici comment faire : http://a-renouard.developpez.com/tut...iser-listview/

  3. #3
    Membre du Club
    Profil pro
    Inscrit en
    Mai 2010
    Messages
    61
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2010
    Messages : 61
    Points : 42
    Points
    42
    Par défaut
    Merci,

    mais il ce trouve que c'est exactement ce tuto que j'ai suivi, je ne comprend pas ce que j'ai mal fait...

    Quel adapter me conseillez-vous d'utiliser?

  4. #4
    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
    Oui exact cela ressemble. Par contre ayant déjà testé ce tuto, je te confirme que le code fonctionne.

    En général j'étend un BaseAdapter quand je fais une vue customisée.

  5. #5
    Membre du Club
    Profil pro
    Inscrit en
    Mai 2010
    Messages
    61
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2010
    Messages : 61
    Points : 42
    Points
    42
    Par défaut
    En effet il marche bien avec des images en local, mais pas quand elles sont récupéré sur internet
    J'y suis depuis tôt ce matin, je commence à désespérer

  6. #6
    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
    Oh mais oui effectivement il va chercher ces images directement dans les ressources. Tu n'as pas d'autre choix que de redéfinir ton adapter pour télécharger puis afficher ton image.

  7. #7
    Membre du Club
    Profil pro
    Inscrit en
    Mai 2010
    Messages
    61
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2010
    Messages : 61
    Points : 42
    Points
    42
    Par défaut
    Merci pour ta réponse, *Question newbie* mais comment puis-je le redéfinir ? Je ne comprend pas ce que tu entend par redéfinir?

  8. #8
    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
    Il s'agit de créer une nouvelle classe qui étend BaseAdapteur.

    Tu peux regarder ce post : http://www.developpez.net/forums/d11...s/#post6315941

  9. #9
    Membre du Club
    Profil pro
    Inscrit en
    Mai 2010
    Messages
    61
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2010
    Messages : 61
    Points : 42
    Points
    42
    Par défaut
    Super! Je vais décortiquer ça

    Encore merci!

  10. #10
    Membre du Club
    Profil pro
    Inscrit en
    Mai 2010
    Messages
    61
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2010
    Messages : 61
    Points : 42
    Points
    42
    Par défaut
    Bonjour,

    après avoir bossé sur un adapter (à l'instant), ni mes images, ni mon texte ne s'affiche, pourtant je suis sûr que je ne suis plus très loin de la solution. Voici mon 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
    package com.android.rss;
     
    import java.util.ArrayList;
    import java.util.HashMap;
     
    import android.app.Activity;
    import android.content.Context;
    import android.graphics.Bitmap;
    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 CustomAdapter extends BaseAdapter{
     
    	private static LayoutInflater inflater=null;
    	private String[] mKeys;
    	private ArrayList<HashMap<String, Object>> dat;
     
     
    	public CustomAdapter(Activity a, ArrayList<HashMap<String, Object>> listData){
    		dat = listData;
    	    inflater = ( LayoutInflater )a.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    	}
     
     
    	@Override
    	public long getItemId(int arg0) {
    	    return arg0;
    	}
     
    	public static class ViewHolder{
    		 public TextView text;
    		 public ImageView iv;
     
    	}
     
     
    	@Override
    	public View getView(int pos, View c, ViewGroup parent) {
    	    ViewHolder holder;
    	    View convertView = c;
     
    	    if(convertView == null){
     
    	    	holder = new ViewHolder();
    	    	holder.text = (TextView) convertView.findViewById(R.id.titre);
    	    	holder.iv = (ImageView) convertView.findViewById(R.id.img);
     
    	    	convertView.setTag(holder);
     
     
    	    }else{holder=(ViewHolder) convertView.getTag();}
     
    	    final int position = pos;
     
    	    holder.text.setText(dat.get(position).get("titre").toString());
    	    holder.iv.setImageBitmap((Bitmap) dat.get(position).get("image"));
     
     
     
    	    return convertView;
    	}
     
     
    	@Override
    	public int getCount() {
    		// TODO Auto-generated method stub
    		return dat.size();
    	}
     
     
    	@Override
    	public Object getItem(int position) {
    		// TODO Auto-generated method stub
    		return dat.get(position);
    	}
     
    }
    Qu-est-ce qui pourrait bien clocher? Merci d'avance pour vos réponses!

  11. #11
    Membre du Club
    Profil pro
    Inscrit en
    Mai 2010
    Messages
    61
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2010
    Messages : 61
    Points : 42
    Points
    42
    Par défaut Réponse!
    J'ai trouvé la solution!
    La voici pour ceux qui sont intéressés:

    Remplacer les HashMap<String,String> par des HashMap<String,Object>

    Lorsque l'on passe l'image dans un HashMap, ne pas faire un map.put("key",String.Valueof(monImage)) mais map.put("key",monImage)

    Ensuite il faut faire une nouvelle classe:

    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
    import android.graphics.Bitmap;
    import android.view.View;
    import android.widget.ImageView;
    import android.widget.SimpleAdapter.ViewBinder;
     
    public class MyViewBinder implements ViewBinder {
    @Override
    	public boolean setViewValue(View view, Object data,String textRepresentation) {
    		if( (view instanceof ImageView) & (data instanceof Bitmap) ) {
    			ImageView iv = (ImageView) view;
    			Bitmap bm = (Bitmap) data;
    			iv.setImageBitmap(bm);
    			return true;
    		}
    		return false;
    	}
    }


    Et enfin, quand on passe l'adapter dans la classe principale, il faut rajouter une ligne de code:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    listView = (ListView)myFragmentView.findViewById(R.id.list2);
    			  ListAdapter mSchedule = new SimpleAdapter (getActivity().getBaseContext(), listData, R.layout.affichageitem,new String[] {"image", "titre"}, new int[] {R.id.img, R.id.titre});
     
    			  ((SimpleAdapter) mSchedule).setViewBinder(new MyViewBinder());	// Ce qu'il faut ajouter!		  
    			  listView.setAdapter(mSchedule);

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [struts] Afficher image dans JSP a partir d'un byte[]
    Par igloof dans le forum Struts 1
    Réponses: 1
    Dernier message: 16/05/2006, 11h11
  2. Réponses: 2
    Dernier message: 17/02/2006, 13h26
  3. Réponses: 9
    Dernier message: 27/01/2006, 18h00
  4. [MySQL] Afficher image stockée sous forme binaire
    Par Luffy Duck dans le forum PHP & Base de données
    Réponses: 10
    Dernier message: 26/12/2005, 18h30
  5. afficher image
    Par sanosuke dans le forum Bases de données
    Réponses: 1
    Dernier message: 19/10/2004, 09h43

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