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 :

Erreur "FATAL EXCEPTION: main"


Sujet :

Android

  1. #1
    Membre du Club
    Femme Profil pro
    Etudiante
    Inscrit en
    Février 2013
    Messages
    95
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Etudiante
    Secteur : Communication - Médias

    Informations forums :
    Inscription : Février 2013
    Messages : 95
    Points : 68
    Points
    68
    Par défaut Erreur "FATAL EXCEPTION: main"
    Bonjour tout le monde,

    J'ai créé une application qui construit un tableau myList à partir d'un première activité et la transfère vers une autre activité où elle va être triée et affichée dans un ListView.
    Mais lorsque je teste mon application, j'obtiens les erreurs suivantes dans mon logcat :
    04-12 01:27:45.362: D/AndroidRuntime(899): Shutting down VM
    04-12 01:27:45.372: W/dalvikvm(899): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
    04-12 01:27:45.442: E/AndroidRuntime(899): FATAL EXCEPTION: main
    04-12 01:27:45.442: E/AndroidRuntime(899): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.projet_fin_etude/com.example.projet_fin_etude.Trie}: java.lang.NullPointerException
    04-12 01:27:45.442: E/AndroidRuntime(899): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
    04-12 01:27:45.442: E/AndroidRuntime(899): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
    04-12 01:27:45.442: E/AndroidRuntime(899): at android.app.ActivityThread.access$600(ActivityThread.java:141)
    04-12 01:27:45.442: E/AndroidRuntime(899): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
    04-12 01:27:45.442: E/AndroidRuntime(899): at android.os.Handler.dispatchMessage(Handler.java:99)
    04-12 01:27:45.442: E/AndroidRuntime(899): at android.os.Looper.loop(Looper.java:137)
    04-12 01:27:45.442: E/AndroidRuntime(899): at android.app.ActivityThread.main(ActivityThread.java:5041)
    04-12 01:27:45.442: E/AndroidRuntime(899): at java.lang.reflect.Method.invokeNative(Native Method)
    04-12 01:27:45.442: E/AndroidRuntime(899): at java.lang.reflect.Method.invoke(Method.java:511)
    04-12 01:27:45.442: E/AndroidRuntime(899): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    04-12 01:27:45.442: E/AndroidRuntime(899): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    04-12 01:27:45.442: E/AndroidRuntime(899): at dalvik.system.NativeStart.main(Native Method)
    04-12 01:27:45.442: E/AndroidRuntime(899): Caused by: java.lang.NullPointerException
    04-12 01:27:45.442: E/AndroidRuntime(899): at com.example.projet_fin_etude.Trie.onCreate(Trie.java:44)
    04-12 01:27:45.442: E/AndroidRuntime(899): at android.app.Activity.performCreate(Activity.java:5104)
    04-12 01:27:45.442: E/AndroidRuntime(899): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
    04-12 01:27:45.442: E/AndroidRuntime(899): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
    04-12 01:27:45.442: E/AndroidRuntime(899): ... 11 more
    Voici mes classes java:
    Marqueur.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
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
            case R.id.menu_trie:
     
                   Intent intent = new Intent(MarqueurActivity.this, Trie.class);
                               intent.putExtra("myList", (Serializable)myList);
                               startActivity(intent);
            default:
                return super.onOptionsItemSelected(item);
            }
        }
     
        @Override
        protected boolean isRouteDisplayed() {
            return false;
        }
     
        @Override
        public void onLocationChanged(Location location) {
            lat = location.getLatitude();
            lng = location.getLongitude();
     
            Toast.makeText(
                getBaseContext(),"Location change to : Latitude = " + lat + " Longitude = "
                    + lng, Toast.LENGTH_LONG).show();
     
            GeoPoint p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
            mc.animateTo(p);
            mc.setCenter(p);
              Intent intent = getIntent();
              if (intent != null)
              { 
                  String text=intent.getStringExtra(EXTRA_SUJET_RECHERCHE);
                  Drawable drawable = this.getResources().getDrawable(R.drawable.marqueur1);
                    final ListItimizedOverlay itemizedoverlay = new ListItimizedOverlay(drawable,this);
                    final  String url ="https://maps.googleapis.com/maps/api/place/textsearch/json?query="+text+"&key=AIzaSyDxms7wMJorpD9LZVRL9OiozgV1D9wJKxo&sensor=true&location="+lat+","+lng+"&radius=500";
     
                    new AsyncTask<Void, Void, JSONObject>(){
                        @Override
                    protected JSONObject doInBackground(Void... params) {
                            // instancier la classe JsonParser
                            JsonParser jParser = new JsonParser ();
                            // récupérer le JSONObject à partir de l’url du fichier employes.json
                            JSONObject json = jParser.getJSONFromUrl(url);
     
                            return json;
                        };
     
                    protected void onPostExecute(JSONObject json) {
     
                        try {
     
                            // récupérer la liste de tous les employés
                            JSONArray results = json.getJSONArray(TAG_results);
                            int j=results.length();
                             myList = new Place[j];
     
     
                            // parcourir toute la liste des employés
                            for(int i = 0; i < results.length(); i++){
     
                            // récupérer un employé de type JSONObject
                            JSONObject emp = results.getJSONObject(i);
     
                            // récupérer le JSONObject phone qui contient deux items
                            JSONObject geometry = emp.getJSONObject(TAG_geometry);
                            JSONObject location = geometry.getJSONObject(TAG_location);
                            String latitude = location.getString(TAG_lat);
                            String longitude= location.getString(TAG_lng);
                            double b = Double.parseDouble(latitude);
                            double c = Double.parseDouble(longitude);
                            String nom= emp.getString(TAG_name);
                            String adresse=emp.getString(TAG_adresse);
                            String reference =emp.getString(TAG_reference);
                            myList[i]=new Place(reference,nom,adresse,b,c);
     
                        GeoPoint geoPoint = new GeoPoint((int) (b* 1E6) , (int)(c* 1E6));
                        OverlayItem overlayitem = new OverlayItem(geoPoint, nom, adresse);
                        itemizedoverlay.addOverlayItem(overlayitem);
     
     
                        List<Overlay> mapOverlays = mapView.getOverlays();
                        mapOverlays.add(itemizedoverlay);
     
                        }
                        }
                        catch(JSONException e)
                        {
                            e.printStackTrace();
                        }
                    };
     
                }.execute();
        }
        }
    Trie.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
    115
    116
    117
    118
    package com.example.projet_fin_etude;
     
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.HashMap;
     
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
     
    import android.app.ListActivity;
    import android.content.Intent;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;
    import android.widget.Toast;
     
    public class Trie  extends ListActivity {
        Place [] myList;
        private static final String TAG_rows = "rows";
        private static final String TAG_elements = "elements";
        private static final String TAG_distance= "distance";
        private static final String TAG_value= "value";
        String url;
     
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.listplaceholder);
            ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
            Intent intent = getIntent();
            Bundle extras = intent.getExtras();
            if (extras != null){
                this.myList = (Place[])extras.getSerializable("myList");
                 url="http://maps.googleapis.com/maps/api/distancematrix/json?origins="+myList[0].getLatitude()+","+myList[0].getLongitude()+"|"+"&destinations=";
                for(int i=1;i<myList.length;i++)
                {
                url=url+myList[i].getLatitude()+","+myList[i].getLongitude()+"|";    
                }
                url=url+"&mode=walking&language=fr-FR&sensor=true";
                new AsyncTask<Void, Void, JSONObject>(){
                    @Override
                    protected JSONObject doInBackground(Void... params) {
                            // instancier la classe JsonParser
                            JsonParser jParser = new JsonParser ();
                            // récupérer le JSONObject à partir de l’url du fichier employes.json
                            JSONObject json = jParser.getJSONFromUrl(url);
     
                            return json;
                        };
     
                        protected void onPostExecute(JSONObject json) {
     
                            try {
     
                                // récupérer la liste de tous les employés
                                JSONArray results = json.getJSONArray(TAG_rows);
     
                                // parcourir toute la liste des employés
                                for(int i = 0; i < results.length(); i++){
     
                                // récupérer un employé de type JSONObject
                                JSONObject emp = results.getJSONObject(i);
     
                                // récupérer le JSONObject phone qui contient deux items
                                JSONObject elements = emp.getJSONObject(TAG_elements);
                                JSONObject dist = elements.getJSONObject(TAG_distance);
                                String value = dist.getString(TAG_value);
                                int val_dist=Integer.parseInt(value);
                                myList[i].setDistance(val_dist);
                }
                            }
                            catch(JSONException e)
                            {
                                e.printStackTrace();
                            }
                        };
     
                    }.execute();
                }
            Arrays.sort(myList);
            for(int i=0;i<myList.length;i++)
            {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("id",  String.valueOf(i));
                map.put("name",myList[i].getNom());
                map.put("adresse", myList[i].getAdresse());
                list.add(map);
            }
              ListAdapter adapter = new SimpleAdapter(this, list , R.layout.activity_trie, 
                      new String[] { "name", "adresse" }, 
                      new int[] { R.id.item_title, R.id.item_subtitle });
     
      setListAdapter(adapter);
      final ListView lv = getListView();
      lv.setTextFilterEnabled(true);    
      lv.setOnItemClickListener(new OnItemClickListener() {
          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {                
              @SuppressWarnings("unchecked")
                HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);                    
              Toast.makeText(Trie.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show(); 
            }
        });
            }
     
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.activity_trie, menu);
            return true;
        }
    }
    Quelqu'un saurait-il m'indiquer d'où vient le problème ?

    Merci d'avance pour votre aide.

  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
    04-12 01:27:45.442: E/AndroidRuntime(899): Caused by: java.lang.NullPointerException
    04-12 01:27:45.442: E/AndroidRuntime(899): at com.example.projet_fin_etude.Trie.onCreate(Trie.java:44)


    Donc.... utilisation d'une reference null, à la ligne 44 du fichier Trie.java (?) dans la fonction Trie.onCreate()

    Soit dans:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    url="http://maps.googleapis.com/maps/api/distancematrix/json?origins="+myList[0].getLatitude()+","+myList[0].getLongitude()+"|"+"&destinations=";
    DONC, myList est null ou myList[0] est null... et vu le code, comme myList n'est pas initialisé... c'est le premier cas.
    N'oubliez pas de cliquer sur mais aussi sur si un commentaire vous a été utile !
    Et surtout

  3. #3
    Membre actif
    Inscrit en
    Décembre 2008
    Messages
    280
    Détails du profil
    Informations forums :
    Inscription : Décembre 2008
    Messages : 280
    Points : 261
    Points
    261
    Par défaut
    2 cas possible :

    - Comme dit nicroman : ton objet est null avant que tu l'envoie à l'activity suivante.

    - sinon peut être que ta classe "Place" n'implémente pas Serializable ???
    Paye Tes Dettes - Applciation android.

    DevHackSecure - Pense bête d'un étudiant en informatique - Tutos DEV

    " I also realize that _everybody_ thinks that they are right, and that they are supported by all other right-thinking people. That's just how people work. We all think we're better than average." Linus Torvalds

  4. #4
    Membre du Club
    Femme Profil pro
    Etudiante
    Inscrit en
    Février 2013
    Messages
    95
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Etudiante
    Secteur : Communication - Médias

    Informations forums :
    Inscription : Février 2013
    Messages : 95
    Points : 68
    Points
    68
    Par défaut
    Merci beaucoup pour vos réponses ,
    justement ma classe place n'implémente pas Serialisable ,
    Voila je l'ajoutes ,
    Voila maintenant ma classe Place.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
    package com.example.projet_fin_etude;
     
    import java.io.Serializable;
     
    public class Place implements Comparable<Place> , Serializable {
        /**
         * 
         */
        private static final long serialVersionUID = -3330720473929601380L;
        /**
         * 
         */
     
        private String reference;
        private String nom;
        private String adresse ;
        private double latitude ;
        private double longitude;
        private int distance;
        public Place()
        {
        }
     
        public Place(String reference,String nom, String adresse, double latitude, double longitude )
        {
            this.reference=reference;
            this.nom=nom;
            this.adresse=adresse;
            this.latitude=latitude;
            this.longitude=longitude;
        }
        public String getReference() {
            return reference;
        }
     
        public void setReference(String reference) {
            this.reference = reference;
        }
     
        public String getNom() {
            return nom;
        }
     
        public void setNom(String nom) {
            this.nom = nom;
        }
     
        public String getAdresse() {
            return adresse;
        }
     
        public void setAdresse(String adresse) {
            this.adresse = adresse;
        }
        public double getLatitude() {
            return latitude;
        }
     
        public void setLatitude(double latitude) {
            this.latitude = latitude;
        }
        public double getLongitude() {
            return longitude;
        }
     
        public void setLongitude(double longitude) {
            this.longitude = longitude;
        }
        public int getDistance() {
            return distance;
        }
     
        public void setDistance(int distance) {
            this.distance = distance;
        }
     
        @Override
        public int compareTo(Place p) {
            // TODO Auto-generated method stub
            if((this.distance)<p.getDistance())
                return -1;
            else if((this.distance)>p.getDistance())
                return 1;
            else
            return 0;
        }
     
    }
    Mais je n'arrive pas à comprendre l'utilité de cette instruction:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
        private static final long serialVersionUID = -3330720473929601380L;
    et les erreurs dans le kogcat ont changées maintenant:

    04-12 11:09:50.802: D/AndroidRuntime(938): Shutting down VM
    04-12 11:09:50.813: W/dalvikvm(938): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
    04-12 11:09:50.882: E/AndroidRuntime(938): FATAL EXCEPTION: main
    04-12 11:09:50.882: E/AndroidRuntime(938): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.projet_fin_etude/com.example.projet_fin_etude.Trie}: java.lang.ClassCastException: java.lang.Object[] cannot be cast to com.example.projet_fin_etude.Place[]
    04-12 11:09:50.882: E/AndroidRuntime(938): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
    04-12 11:09:50.882: E/AndroidRuntime(938): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
    04-12 11:09:50.882: E/AndroidRuntime(938): at android.app.ActivityThread.access$600(ActivityThread.java:141)
    04-12 11:09:50.882: E/AndroidRuntime(938): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
    04-12 11:09:50.882: E/AndroidRuntime(938): at android.os.Handler.dispatchMessage(Handler.java:99)
    04-12 11:09:50.882: E/AndroidRuntime(938): at android.os.Looper.loop(Looper.java:137)
    04-12 11:09:50.882: E/AndroidRuntime(938): at android.app.ActivityThread.main(ActivityThread.java:5041)
    04-12 11:09:50.882: E/AndroidRuntime(938): at java.lang.reflect.Method.invokeNative(Native Method)
    04-12 11:09:50.882: E/AndroidRuntime(938): at java.lang.reflect.Method.invoke(Method.java:511)
    04-12 11:09:50.882: E/AndroidRuntime(938): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    04-12 11:09:50.882: E/AndroidRuntime(938): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    04-12 11:09:50.882: E/AndroidRuntime(938): at dalvik.system.NativeStart.main(Native Method)
    04-12 11:09:50.882: E/AndroidRuntime(938): Caused by: java.lang.ClassCastException: java.lang.Object[] cannot be cast to com.example.projet_fin_etude.Place[]
    04-12 11:09:50.882: E/AndroidRuntime(938): at com.example.projet_fin_etude.Trie.onCreate(Trie.java:43)
    04-12 11:09:50.882: E/AndroidRuntime(938): at android.app.Activity.performCreate(Activity.java:5104)
    04-12 11:09:50.882: E/AndroidRuntime(938): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
    04-12 11:09:50.882: E/AndroidRuntime(938): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
    04-12 11:09:50.882: E/AndroidRuntime(938): ... 11 more
    Merci d'avance pour votre aide.

  5. #5
    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
    Tout dépend de la ligne 44... si je m'en réfère au code posté...

    Sinon...
    Mais je n'arrive pas à comprendre l'utilité de cette instruction:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    	private static final long serialVersionUID = -3330720473929601380L;
    C'est le code "magique" placé au début de la serialisation, qui permet de savoir si l'objet peut être lu (même code) ou non (code différent).
    N'oubliez pas de cliquer sur mais aussi sur si un commentaire vous a été utile !
    Et surtout

  6. #6
    Membre du Club
    Femme Profil pro
    Etudiante
    Inscrit en
    Février 2013
    Messages
    95
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Etudiante
    Secteur : Communication - Médias

    Informations forums :
    Inscription : Février 2013
    Messages : 95
    Points : 68
    Points
    68
    Par défaut
    Merci pour votre réponse mais je n'ai pas pu corriger la faute.

    Avez vous plus d'idées s'il vous plait ?

  7. #7
    Membre actif
    Inscrit en
    Décembre 2008
    Messages
    280
    Détails du profil
    Informations forums :
    Inscription : Décembre 2008
    Messages : 280
    Points : 261
    Points
    261
    Par défaut
    Alors là.. je t'avouerai que je n'utilise pas souvent des tableaux d'objets complexes mais plutôt des listes (que tu peux ensuite convertir en tableau si tu as envi).

    Ici l'erreur dit qu'il ne veut pas convertir object[] qu'il reçoit en Place[] que tu cast. Et ça je ne comprends pas vraiment pourquoi ... Je le fais avec des listes et ça fonctionne parfaitement...

    Donc question :

    - Est tu obligé d'utiliser un tableau ? Je pense que c'est ça qui fait péter le truc car peut être qu'il faudrait ici que ta classe implémente Parcelable ducoup pour passer un tableaux alors qu'avec Serializable on peut faire passer une liste ... (enfin c'est ce que j'en ai compris en lisant des trucs à droite à gauche... Si quelqu'un peut confirmer?!)
    Paye Tes Dettes - Applciation android.

    DevHackSecure - Pense bête d'un étudiant en informatique - Tutos DEV

    " I also realize that _everybody_ thinks that they are right, and that they are supported by all other right-thinking people. That's just how people work. We all think we're better than average." Linus Torvalds

  8. #8
    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
    Là:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    intent.putExtra("myList", (Serializable)myList);
    Va mapper sur la fonction du bundle:
    putSerializable(String key, Serializable value)
    Mais si les objets sont des Serializable, rien ne dit que l'array en est !

    En règle générale, en Java, *sauf* durant la récupération de données, on n'utilise jamais de "cast"
    J'imagine que sans le cast eclipse refuse de compiler ? cela veut dire que le code n'est pas bon... il FAUT passer un OBJET (et non un array) qui implémente Serializable.


    Enfin, bon... le plus simple est encore de transformer l'objet en Parcelable, et on passe l'array directement.
    N'oubliez pas de cliquer sur mais aussi sur si un commentaire vous a été utile !
    Et surtout

  9. #9
    Membre du Club
    Femme Profil pro
    Etudiante
    Inscrit en
    Février 2013
    Messages
    95
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Etudiante
    Secteur : Communication - Médias

    Informations forums :
    Inscription : Février 2013
    Messages : 95
    Points : 68
    Points
    68
    Par défaut
    Merci beaucoup pour vos réponses ,
    Pouvez vous me donner le code de transformation d'un objet à Parcelable et les instructions pour passer l'array directement ??
    Encore grand merci pour vos aide et bonsoir.

  10. #10
    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
    google "parcelable" donne comme premier lien le bon: http://developer.android.com/referen...arcelable.html
    N'oubliez pas de cliquer sur mais aussi sur si un commentaire vous a été utile !
    Et surtout

  11. #11
    Membre du Club
    Femme Profil pro
    Etudiante
    Inscrit en
    Février 2013
    Messages
    95
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Etudiante
    Secteur : Communication - Médias

    Informations forums :
    Inscription : Février 2013
    Messages : 95
    Points : 68
    Points
    68
    Par défaut
    Bonjour,
    Merci pour votre réponse .
    J'ai passé un grand temps de recherche mais je n'arrives pas à comprendre comment déclarer , remplir , manipuler et passer dans un intent un array de Parcelable ?
    Pouvez vous me donner un tutoriel ou un exemple utile pour mon application et merci beaucoup.

  12. #12
    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
    Pour faire un parcelable il suffit d'implémenter le code suivant:
    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
     
    public class MyParcelable implements Parcelable {
         private int mData;
     
         public int describeContents() {
             return 0;
         }
     
         public void writeToParcel(Parcel out, int flags) {
             out.writeInt(mData);
         }
     
         public static final Parcelable.Creator<MyParcelable> CREATOR
                 = new Parcelable.Creator<MyParcelable>() {
             public MyParcelable createFromParcel(Parcel in) {
                 return new MyParcelable(in);
             }
     
             public MyParcelable[] newArray(int size) {
                 return new MyParcelable[size];
             }
         };
     
         private MyParcelable(Parcel in) {
             mData = in.readInt();
         }
     }
    (code extrait du lien ci-dessus... remplacer mData / MyParcelable bien sur)

    Et ensuite pour passer à l'intent un array de parcelable:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    intent.putExtra("myarray",array);
    N'oubliez pas de cliquer sur mais aussi sur si un commentaire vous a été utile !
    Et surtout

  13. #13
    Membre du Club
    Femme Profil pro
    Etudiante
    Inscrit en
    Février 2013
    Messages
    95
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Etudiante
    Secteur : Communication - Médias

    Informations forums :
    Inscription : Février 2013
    Messages : 95
    Points : 68
    Points
    68
    Par défaut
    Bonjour,
    Merci pour votre aide nicroman.
    Mon problème est le fait de remplir le tableau par des objets Parcelable .
    Quelle constructeur je veux utiliser?
    Est ce constructeur ?
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     private MyParcelable(Parcel in) {
             mData = in.readInt();
         }
    Comment je peut construire le paramètre (parcel in)?
    Et comment je peux lire à partir du tableau ?
    S'il vous plait aidez moi et merci d'avance .

  14. #14
    Membre actif
    Inscrit en
    Décembre 2008
    Messages
    280
    Détails du profil
    Informations forums :
    Inscription : Décembre 2008
    Messages : 280
    Points : 261
    Points
    261
    Par défaut
    Ici c'est ta classe Place que tu dois faire devenir parcelable. Donc dans la fonction :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    private MyParcelable(Parcel in) {
             mData = in.readInt();
         }
    Tu vas mettre tous les champs de ta classe Place.

    Ensuite tu créera ton tableau de la même manière que d'habitude.
    Paye Tes Dettes - Applciation android.

    DevHackSecure - Pense bête d'un étudiant en informatique - Tutos DEV

    " I also realize that _everybody_ thinks that they are right, and that they are supported by all other right-thinking people. That's just how people work. We all think we're better than average." Linus Torvalds

  15. #15
    Membre du Club
    Femme Profil pro
    Etudiante
    Inscrit en
    Février 2013
    Messages
    95
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Etudiante
    Secteur : Communication - Médias

    Informations forums :
    Inscription : Février 2013
    Messages : 95
    Points : 68
    Points
    68
    Par défaut
    Merci beaucoup,
    J'ai déjà modifiée la fonction:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
      public Place(Parcel in) {
    		// TODO Auto-generated constructor stub
    		reference=in.readString();
    		nom=in.readString();
    		adresse=in.readString();
    		latitude=in.readDouble();
    		longitude=in.readDouble();
                    distance=in.readInt();
    	}
    Mon problème est à cette emplacement:
    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
    for(int i = 0; i < results.length(); i++){
     
    						// récupérer un employé de type JSONObject
    						JSONObject emp = results.getJSONObject(i);
     
    						// récupérer le JSONObject phone qui contient deux items
    						JSONObject geometry = emp.getJSONObject(TAG_geometry);
    						JSONObject location = geometry.getJSONObject(TAG_location);
    						String latitude = location.getString(TAG_lat);
    						String longitude= location.getString(TAG_lng);
    						double b = Double.parseDouble(latitude);
    						double c = Double.parseDouble(longitude);
    						String nom= emp.getString(TAG_name);
    						String adresse=emp.getString(TAG_adresse);
    						String reference =emp.getString(TAG_reference);
    						myList[i]=new Place(reference,nom,adresse,b,c);
    C'est à dire lorsque j'essaie de remplir les cases du tableau myList par des objets parcelables Place.
    Et dans la nouvelle activité lorsque j'essaie de récupérer les valeurs de mes cases .
    Merci pour votre aide et bonsoir.

  16. #16
    Membre actif
    Inscrit en
    Décembre 2008
    Messages
    280
    Détails du profil
    Informations forums :
    Inscription : Décembre 2008
    Messages : 280
    Points : 261
    Points
    261
    Par défaut
    soit plus précis sur ton problème, dis ce qui coince parce que là je vois pas ce qui t'arrive !

    et d'autres bout de code là ou ça coince
    Paye Tes Dettes - Applciation android.

    DevHackSecure - Pense bête d'un étudiant en informatique - Tutos DEV

    " I also realize that _everybody_ thinks that they are right, and that they are supported by all other right-thinking people. That's just how people work. We all think we're better than average." Linus Torvalds

  17. #17
    Membre du Club
    Femme Profil pro
    Etudiante
    Inscrit en
    Février 2013
    Messages
    95
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Etudiante
    Secteur : Communication - Médias

    Informations forums :
    Inscription : Février 2013
    Messages : 95
    Points : 68
    Points
    68
    Par défaut
    Désolé,
    Mon problème est à cette instruction:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    myList[i]=new Place(reference,nom,adresse,b,c);
    Sachant que la classe Place.java est:
    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
    package com.example.projet_fin_etude;
    import android.os.Parcel;
    import android.os.Parcelable;
     
    public class Place implements Comparable<Place> ,Parcelable   {
     
     
    	/**
             * 
             */
     
    	private String reference;
    	private String nom;
    	private String adresse ;
    	private double latitude ;
    	private double longitude;
    	private int distance;
    	public Place()
    	{
     
    	}
     
     
     
    	public String getReference() {
    		return reference;
    	}
     
    	public void setReference(String reference) {
    		this.reference = reference;
    	}
     
    	public String getNom() {
    		return nom;
    	}
     
    	public void setNom(String nom) {
    		this.nom = nom;
    	}
     
    	public String getAdresse() {
    		return adresse;
    	}
     
    	public void setAdresse(String adresse) {
    		this.adresse = adresse;
    	}
    	public double getLatitude() {
    		return latitude;
    	}
     
    	public void setLatitude(double latitude) {
    		this.latitude = latitude;
    	}
    	public double getLongitude() {
    		return longitude;
    	}
     
    	public void setLongitude(double longitude) {
    		this.longitude = longitude;
    	}
    	public int getDistance() {
    		return distance;
    	}
     
    	public void setDistance(int distance) {
    		this.distance = distance;
    	}
     
    	@Override
    	public int compareTo(Place p) {
    		// TODO Auto-generated method stub
    		if((this.distance)<p.getDistance())
    			return -1;
    		else if((this.distance)>p.getDistance())
    			return 1;
    		else
    		return 0;
    	}
     
    	@Override
    	public int describeContents() {
    		// TODO Auto-generated method stub
    		return 0;
    	}
     
    	@Override
    	public void writeToParcel(Parcel dest, int flags) {
    		// TODO Auto-generated method stub
    		dest.writeString(reference);
    		dest.writeString(nom);
    		dest.writeString(adresse);
    		dest.writeDouble(latitude);
    		dest.writeDouble(longitude);
    		dest.writeInt(distance);
    	}
     
        public static final Parcelable.Creator<Place> CREATOR
                = new Parcelable.Creator<Place>() {
            public Place createFromParcel(Parcel in) {
                return new Place(in);
            }
     
            public Place[] newArray(int size) {
                return new Place[size];
            }
        };
        public Place(Parcel in) {
    		// TODO Auto-generated constructor stub
    		reference=in.readString();
    		nom=in.readString();
    		adresse=in.readString();
    		latitude=in.readDouble();
    		longitude=in.readDouble();
    		distance=in.readInt();
    	}
     
     
     
    }

  18. #18
    Membre actif
    Inscrit en
    Décembre 2008
    Messages
    280
    Détails du profil
    Informations forums :
    Inscription : Décembre 2008
    Messages : 280
    Points : 261
    Points
    261
    Par défaut
    alala !! as tu instancié ton tableau ?

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Place[] myList = new Place[Result.lenght]
    Paye Tes Dettes - Applciation android.

    DevHackSecure - Pense bête d'un étudiant en informatique - Tutos DEV

    " I also realize that _everybody_ thinks that they are right, and that they are supported by all other right-thinking people. That's just how people work. We all think we're better than average." Linus Torvalds

  19. #19
    Membre du Club
    Femme Profil pro
    Etudiante
    Inscrit en
    Février 2013
    Messages
    95
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Etudiante
    Secteur : Communication - Médias

    Informations forums :
    Inscription : Février 2013
    Messages : 95
    Points : 68
    Points
    68
    Par défaut
    Oui , je l'ai instanciée .
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    int j=results.length();
    	 myList = new Place[j];

  20. #20
    Membre actif
    Inscrit en
    Décembre 2008
    Messages
    280
    Détails du profil
    Informations forums :
    Inscription : Décembre 2008
    Messages : 280
    Points : 261
    Points
    261
    Par défaut
    Il n'y a pas d'erreur dans les logs ?
    Paye Tes Dettes - Applciation android.

    DevHackSecure - Pense bête d'un étudiant en informatique - Tutos DEV

    " I also realize that _everybody_ thinks that they are right, and that they are supported by all other right-thinking people. That's just how people work. We all think we're better than average." Linus Torvalds

+ Répondre à la discussion
Cette discussion est résolue.
Page 1 sur 2 12 DernièreDernière

Discussions similaires

  1. Erreur "FATAL EXCEPTION: main"
    Par bza88 dans le forum Android
    Réponses: 1
    Dernier message: 06/06/2013, 03h28
  2. FATAL EXCEPTION: main android
    Par nhmidi dans le forum Android
    Réponses: 1
    Dernier message: 25/02/2013, 12h22

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