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 :

création d'une listview dynamique


Sujet :

Composants graphiques Android

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre averti
    Homme Profil pro
    Etudiant
    Inscrit en
    Décembre 2011
    Messages
    9
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Etudiant
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Décembre 2011
    Messages : 9
    Par défaut création d'une listview dynamique
    Salut,

    J'ai une ListView, que je remplis dynamiquement avec des valeurs que je récupères d'une fichier xml, que j'ai déjà 'parser' avec les données de type string. Ça marche bien, mais mon problème avec le widget ratingbar et qu'il n'affiche rien.
    Pour information, je suis débutant en android

    voilà mon fichier Xml à parser
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    <results count="3">
    <result>
    <vote>1</vote>
    <nom>mahdi</nom>
    <score>234</score>
    </result>
    <result>
    <vote>2</id>
    <nom>aaaaa</nom>
    <score>2343</score>
    <vote>4</id>
    <nom>bbbbb</nom>
    <score>2343</score>
    </result>
    voila mes layoutes

    listeplacerholde.xml
    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
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">	
     
        <ListView
    	 	android:id="@id/android:list"
    	    android:layout_width="fill_parent"
    	    android:layout_height="wrap_content"
    	    android:layout_weight="1"
    	 	android:drawSelectorOnTop="false" />
     
        <TextView
            android:id="@id/android:empty"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="No data"/>
     
    </LinearLayout>

    main.xml
    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
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
        <LinearLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/i"
            android:layout_width="216dp"
            android:layout_height="123dp"
            android:orientation="vertical"
            android:paddingLeft="10dip" >
     
     
            <TextView
                android:id="@+id/item_title"
                android:layout_width="160dp"
                android:layout_height="wrap_content"
                android:padding="2dp"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textSize="20dp" />
     
     
            <TextView
                android:id="@+id/item_subtitle"
                android:layout_width="157dp"
                android:layout_height="wrap_content"
                android:padding="2dp"
                android:textSize="13dp" />
     
     
     
     
     
            <TextView
                android:id="@+id/item_su"
                android:layout_width="158dp"
                android:layout_height="wrap_content"
                android:padding="2dp"
                android:textSize="13dp" />
     
     
     
     
            <RatingBar
                android:id="@+id/rating"
                style="?android:attr/ratingBarStyleSmall"
                android:layout_width="180dp"
                android:layout_height="wrap_content"
                android:numStars="5"
                android:stepSize="1" />
     
        </LinearLayout>
     
    </LinearLayout>

    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
    package com.test.aa;
     
    import java.util.ArrayList;
    import java.util.HashMap;
     
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.NodeList;
    import android.app.ListActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.RatingBar;
    import android.widget.SimpleAdapter;
    import android.widget.Toast;
     
    public class Main extends ListActivity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.listplaceholder);
     
            ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
     
     
            String xml = XMLfunctions.getXML();
            Document doc = XMLfunctions.XMLfromString(xml);
     
            int numResults = XMLfunctions.numResults(doc);
     
            if((numResults <= 0)){
            	Toast.makeText(Main.this, "pas de resultas", Toast.LENGTH_LONG).show();  
            	finish();
            }
     
    		NodeList nodes = doc.getElementsByTagName("result");
     
    		for (int i = 0; i < nodes.getLength(); i++) {							
    			HashMap<String, String> map = new HashMap<String, String>();	
     
    			Element e = (Element)nodes.item(i);
    			map.put("vote", XMLfunctions.getValue(e, "vote"));
            	map.put("name", "nom:" + XMLfunctions.getValue(e, "nom"));
            	map.put("Score", "Score: " + XMLfunctions.getValue(e, "score"));
     
            	mylist.add(map);			
    		}		
     
            ListAdapter adapter = new SimpleAdapter(this,mylist,R.layout.main, 
                            new String[] {"name","Score"}, 
                            new int[] { R.id.item_title, R.id.item_subtitle});
            RatingBar stars=(RatingBar) findViewById(R.id.rating);
        	stars.setNumStars(5);
        	stars.setRating("id");/* au niveau de ce ligne eclipse m'afficher erreur suivante"the methode setrating(float) in the type ratingbar is not applicable for argument (string)**/
            setListAdapter(adapter);
     
     
        }
    }

    XMLfunction.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
    113
    114
    package com.test.aa;
     
    import java.io.IOException;
    import java.io.StringReader;
    import java.io.UnsupportedEncodingException;
    import java.net.MalformedURLException;
     
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
     
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.util.EntityUtils;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
     
     
    public class XMLfunctions {
     
    	public final static Document XMLfromString(String xml){
     
    		Document doc = null;
     
    		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            try {
     
    			DocumentBuilder db = dbf.newDocumentBuilder();
     
    			InputSource is = new InputSource();
    	        is.setCharacterStream(new StringReader(xml));
    	        doc = db.parse(is); 
     
    		} catch (ParserConfigurationException e) {
    			System.out.println("XML parse error: " + e.getMessage());
    			return null;
    		} catch (SAXException e) {
    			System.out.println("Wrong XML file structure: " + e.getMessage());
                return null;
    		} catch (IOException e) {
    			System.out.println("I/O exeption: " + e.getMessage());
    			return null;
    		}
     
            return doc;
     
    	}
     
    	/** Returns element value
              * @param elem element (it is XML tag)
              * @return Element value otherwise empty String
              */
    	 public final static String getElementValue( Node elem ) {
    	     Node kid;
    	     if( elem != null){
    	         if (elem.hasChildNodes()){
    	             for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
    	                 if( kid.getNodeType() == Node.TEXT_NODE  ){
    	                     return kid.getNodeValue();
    	                 }
    	             }
    	         }
    	     }
    	     return "";
    	 }
     
    	 public static String getXML(){	 
    			String line = null;
     
    			try {
     
    				DefaultHttpClient httpClient = new DefaultHttpClient();
    				HttpPost httpPost = new HttpPost("http://testandroid.hebergratuit.com/bb.xml");
     
    				HttpResponse httpResponse = httpClient.execute(httpPost);
    				HttpEntity httpEntity = httpResponse.getEntity();
    				line = EntityUtils.toString(httpEntity);
     
    			} catch (UnsupportedEncodingException e) {
    				line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
    			} catch (MalformedURLException e) {
    				line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
    			} catch (IOException e) {
    				line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
    			}
     
    			return line;
     
    	}
     
    	public static int numResults(Document doc){		
    		Node results = doc.getDocumentElement();
    		int res = -1;
     
    		try{
    			res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
    		}catch(Exception e ){
    			res = -1;
    		}
     
    		return res;
    	}
     
    	public static String getValue(Element item, String str) {		
    		NodeList n = item.getElementsByTagName(str);		
    		return XMLfunctions.getElementValue(n.item(0));
    	}
    }
    Merci

  2. #2
    Invité de passage
    Profil pro
    etudiant
    Inscrit en
    Février 2012
    Messages
    1
    Détails du profil
    Informations personnelles :
    Localisation : Brésil

    Informations professionnelles :
    Activité : etudiant

    Informations forums :
    Inscription : Février 2012
    Messages : 1
    Par défaut
    salut ,
    moi aussi j'ai le même problème que vous ??????????? avez vous trouvé une solution ???????
    Merci

  3. #3
    Membre éprouvé
    Profil pro
    Inscrit en
    Décembre 2009
    Messages
    141
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2009
    Messages : 141
    Par défaut
    Si tu regardes la doc, le SimpleAdapter ne gère que Checkable, TextView et ImageView.

    http://developer.android.com/referen...leAdapter.html

    Personnellement j’implémenterai un ArrayAdapter<T> histoire d'avoir plus de liberté.

  4. #4
    Membre averti
    Homme Profil pro
    Etudiant
    Inscrit en
    Décembre 2011
    Messages
    9
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Etudiant
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Décembre 2011
    Messages : 9
    Par défaut Personnellement j’implémenterai un ArrayAdapter<T> histoire d'avoir plus de liberté.
    salut
    merci UbentuMan pour votre réponse,alors il faut que je remplacer le SimpleAdapter par arrayadapter
    j'ai essaie de faire les modification suivantes mais encore pas de résultas mem je ne sais pas comment ajouter le widget ratingbar pour le arrayadapter
    Mercii.
    je sais que je fait des fautes débiles mais je suis encore débutant
    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
     
     
    package com.test.aa;
     
    import java.util.ArrayList;
    import java.util.HashMap;
     
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.NodeList;
    import android.app.ListActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.RatingBar;
    import android.widget.SimpleAdapter;
    import android.widget.Toast;
     
    public class Main extends ListActivity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.listplaceholder);
     
            ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
     
     
            String xml = XMLfunctions.getXML();
            Document doc = XMLfunctions.XMLfromString(xml);
     
            int numResults = XMLfunctions.numResults(doc);
     
            if((numResults <= 0)){
            	Toast.makeText(Main.this, "pas de resultas", Toast.LENGTH_LONG).show();  
            	finish();
            }
     
    		NodeList nodes = doc.getElementsByTagName("result");
     
    		for (int i = 0; i < nodes.getLength(); i++) {							
    			HashMap<String, String> map = new HashMap<String, String>();	
     
    			Element e = (Element)nodes.item(i);
    			map.put("vote", XMLfunctions.getValue(e, "vote"));
            	map.put("name", "nom:" + XMLfunctions.getValue(e, "nom"));
            	map.put("Score", "Score: " + XMLfunctions.getValue(e, "score"));
     
            	mylist.add(map);			
    		}		
     
             setListAdapter(new ArrayAdapter(this, mylist
                  R.layout.main   new String[] {"name","Score"}, 
                            new int[] { R.id.item_title, R.id.item_subtitle});
          //  Listeadapter adapter = simpleadapter(this,mylist,R.layout.main, 
                            //new String[] {"name","Score"}, 
                           // new int[] { R.id.item_title, R.id.item_subtitle});
          //  RatingBar stars=(RatingBar) findViewById(R.id.rating);
        	//stars.setNumStars(5);
        //	stars.setRating("id");/* au niveau de ce ligne eclipse m'afficher erreur suivante"the methode setrating(float) in the type ratingbar is not applicable for argument (string)**/
            setListAdapter(adapter);

Discussions similaires

  1. création d'une liste dynamique aspx/vb
    Par akara dans le forum ASP.NET
    Réponses: 1
    Dernier message: 27/09/2007, 07h39
  2. <débutant> création d'une liste dynamique (aspx/vb)
    Par akara dans le forum Général Dotnet
    Réponses: 1
    Dernier message: 11/09/2007, 15h46
  3. Création d'une bibiothèque dynamique.
    Par Pragmateek dans le forum C++
    Réponses: 22
    Dernier message: 31/03/2006, 22h00
  4. création d'une librairie dynamique
    Par bilo2000 dans le forum Autres éditeurs
    Réponses: 3
    Dernier message: 26/08/2004, 15h17
  5. [Plugin] Création d'une vue dynamiquement
    Par The Bonze dans le forum Eclipse Platform
    Réponses: 2
    Dernier message: 15/06/2004, 13h23

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