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 "NullPointerException"


Sujet :

Android

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre averti
    Profil pro
    Inscrit en
    Octobre 2011
    Messages
    29
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2011
    Messages : 29
    Par défaut Erreur "NullPointerException"
    Bonjour à tous,

    je suis entrain de faire un fichier config.xml pour pouvoir configurer des valeurs dans mon application, mais j'ai un NullPointerException, et je ne sais pas comment le résoudre


    voila mon code pour charger et parser le fichier 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
     
    public class XmlConfig {
    private int niveau_zoom;		
     
    	public XmlConfig() 
     {
     
    		String configFilePath= Environment.getExternalStorageDirectory()+"/Projet/config.xml";
    		try {
    			configFileStr = new FileInputStream(configFilePath);
    		} catch (FileNotFoundException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		}
     
     
    			try {
     
    			XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();
    			parser.setInput(configFileStr, null);
     
    			int eventType = parser.getEventType();
     
    			while(eventType != XmlPullParser.END_DOCUMENT) {
     
    				switch(eventType) {
     
    				case XmlPullParser.START_DOCUMENT:
    					break;
     
    	           	 case XmlPullParser.START_TAG:
     
    	            	String tagName = parser.getName();
     
    	            	if(tagName.equalsIgnoreCase("Zoom")) {
    	            		niveau_zoom = Integer.parseInt(parser.getAttributeValue(0));
     
    	            	}
     
     
    		}
    		catch (XmlPullParserException e) { } 
     
     
    	}
    	public int getnZoom()
    	{
    		return niveau_zoom;
    	}
    }
    voila la ligne xml
    <?xml version="1.0" encoding="UTF-8"?>
    <Zoom>1</Zoom>

    Et lorsque j’insère le constructeur dans mon main, new XmlConfig() pour pouvoir utiliser la variable niveau_zoom, cela fait planter l'application avec l'erreur:

    08-07 15:58:21.940: ERROR/AndroidRuntime(403): java.lang.RuntimeException: Unable to start activity ComponentInfo{fr.projet.affichage/fr.projet.affichage.Main}: java.lang.NullPointerException

    08-07 15:58:21.940: ERROR/AndroidRuntime(403): Caused by: java.lang.NullPointerException


    Merci d'avance pour votre aide.

  2. #2
    Modérateur
    Avatar de Hizin
    Homme Profil pro
    Développeur mobile
    Inscrit en
    Février 2010
    Messages
    2 180
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France

    Informations professionnelles :
    Activité : Développeur mobile

    Informations forums :
    Inscription : Février 2010
    Messages : 2 180
    Par défaut
    Stacktrace complet s'il te plaît

    Première remarque : NE PAS IGNORER LES EXCEPTIONS !
    Merci de ne pas laisser ce catch vide, mais au minimum de faire un printStackTrace.
    Le mieux étant de faire un Log.e(TAG, "Erreur parsing", e);.
    C'est Android, PAS Androïd, ou Androïde didiou !
    Le premier est un OS, le second est la mauvaise orthographe du troisième, un mot français désignant un robot à forme humaine.

    Membre du comité contre la phrase "ça marche PAS" en titre et/ou explication de problème.

    N'oubliez pas de consulter les FAQ Android et les cours et tutoriels Android

  3. #3
    Expert confirmé

    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
    Billets dans le blog
    3
    Par défaut
    J'ai une petite idée néanmoins sans stacktrace (ma boule de crystal remarche !!!)
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
     
    String configFilePath= Environment.getExternalStorageDirectory()+"/Projet/config.xml";
    		try {
    			configFileStr = new FileInputStream(configFilePath);
    		} catch (FileNotFoundException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		}
    Donc, grosso-modo, là tu dis:
    J'ouvre un fichier en lecture... et si je n'y arrive pas, j'affiche pourquoi quelque part (on ne sait pas trop ou, mais on va dire dans la console), mais c'est pas grave, je peux continuer sans fichier !

    Hors... juste après:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    try {
          XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();
          parser.setInput(configFileStr, null);
          ...
    } catch (XmlPullParserException e) { }
    Et bim ... on utilise configFileStr qui est null !! ca sent le NPE à plein nez....


    Je sais, les exceptions c'est bien gavant, Eclipse affiche tout un tas d'erreur, mais c'est fait exprès... Hormis dans l'UI (ou on veut afficher un message à l'utilisateur), il est très rare qu'on catch des exceptions , sauf pour les transformer en une autre exception plus "générique"... Par exemple:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
    try {
        ....
    } catch (XmlPullParserException ex) {
       throw new MyApplicationDataException("Couldn't read XML file",ex);
       // et on n'oublie pas de coller l'exception initiale en 'cause'.
    }

  4. #4
    Membre averti
    Profil pro
    Inscrit en
    Octobre 2011
    Messages
    29
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2011
    Messages : 29
    Par défaut
    Bonjour nicroman et Hizin et merci pour vos réponses,

    Voila pour voir si le fichier existe je fait:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
     
    String configFilePath= Environment.getExternalStorageDirectory()+"/Projet/config.xml";
     
            try {
            	configFileStr = new FileInputStream(configFilePath);
                Log.e("XMLPARSER: "," fichier  ok");
    		} 
    		catch (FileNotFoundException e) {
     
                Log.e("XMLPARSER: ","erreur fichier ");
     
    		}
    Et la j'ai dans le logcat :
    08-08 10:02:40.430: ERROR/XMLPARSER 4535): fichier ok

    Pour le deuxième catch je fait :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     
    catch (XmlPullParserException e) {
    	Log.e("error", "Erreur parsing",e);} 
    		}
    mais il ne rentre pas dans ce catch (pour le catch proposé par nicroman je n'ai pas réussi à le mettre en place...)

    et voila tous les erreurs du logcat:
    08-08 10:02:40.430: ERROR/XMLPARSER 4535): fichier ok
    08-08 10:03:18.840: ERROR/InputDispatcher(299): channel '40ef2b08 fr.projet.affichage/fr.projet.affichage.Main (server)' ~ Consumer closed input channel or an error occurred. events=0x8
    08-08 10:03:18.840: ERROR/InputDispatcher(299): channel '40ef2b08 fr.projet.affichage/fr.projet.affichage.Main (server)' ~ Channel is unrecoverably broken and will be disposed!
    08-08 10:03:19.050: ERROR/android.os.Debug(299): Dumpstate > /data/log/dumpstate_app_error
    08-08 10:03:19.050: ERROR/AndroidRuntime(4593): FATAL EXCEPTION: main
    08-08 10:03:19.050: ERROR/AndroidRuntime(4593): java.lang.RuntimeException: Unable to start activity ComponentInfo{fr.projet.affichage/fr.projet.affichage.Main}: java.lang.NullPointerException
    08-08 10:03:19.050: ERROR/AndroidRuntime(4593): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1818)
    08-08 10:03:19.050: ERROR/AndroidRuntime(4593): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1834)
    08-08 10:03:19.050: ERROR/AndroidRuntime(4593): at android.app.ActivityThread.access$500(ActivityThread.java:122)
    08-08 10:03:19.050: ERROR/AndroidRuntime(4593): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1027)
    08-08 10:03:19.050: ERROR/AndroidRuntime(4593): at android.os.Handler.dispatchMessage(Handler.java:99)
    08-08 10:03:19.050: ERROR/AndroidRuntime(4593): at android.os.Looper.loop(Looper.java:132)
    08-08 10:03:19.050: ERROR/AndroidRuntime(4593): at android.app.ActivityThread.main(ActivityThread.java:4126)
    08-08 10:03:19.050: ERROR/AndroidRuntime(4593): at java.lang.reflect.Method.invokeNative(Native Method)
    08-08 10:03:19.050: ERROR/AndroidRuntime(4593): at java.lang.reflect.Method.invoke(Method.java:491)
    08-08 10:03:19.050: ERROR/AndroidRuntime(4593): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:844)
    08-08 10:03:19.050: ERROR/AndroidRuntime(4593): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
    08-08 10:03:19.050: ERROR/AndroidRuntime(4593): at dalvik.system.NativeStart.main(Native Method)
    08-08 10:03:19.050: ERROR/AndroidRuntime(4593): Caused by: java.lang.NullPointerException
    08-08 10:03:19.050: ERROR/AndroidRuntime(4593): at fr.projet.affichage.Main.onCreate(Main.java:152)
    08-08 10:03:19.050: ERROR/AndroidRuntime(4593): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1050)
    08-08 10:03:19.050: ERROR/AndroidRuntime(4593): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1782)
    08-08 10:03:19.050: ERROR/AndroidRuntime(4593): ... 11 more


    Merci d'avance.

  5. #5
    Membre émérite
    Profil pro
    Inscrit en
    Janvier 2011
    Messages
    757
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2011
    Messages : 757
    Par défaut
    Ligne 152 de ta classe Main (dans la méthode onCreate) correspond à quoi ?

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
     at fr.projet.affichage.Main.onCreate(Main.java:152)

  6. #6
    Membre averti
    Profil pro
    Inscrit en
    Octobre 2011
    Messages
    29
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2011
    Messages : 29
    Par défaut
    Voila ce que j'ai à la ligne 152 :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
     
    surfaceView = (GLSurfaceView) this.findViewById(R.id.glSurface);
     
            lv = (ListView) this.findViewById(R.id.listView1);
            lvAdapter = new ArrayAdapter<Information>(this,android.R.layout.simple_list_item_1,vds.getQuestions());//ligne 152
            lv.setAdapter(lvAdapter);
    Et plus loin dans le main, et c'est la ou je veux utiliser la variable récupérer dans le fichier ConfigXML:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
     
    private void afficherArticles(int zoomState) {
     
    		XmlConfig nZoom = new XmlConfig(context);
    		selectedQuestions = new ArrayList<Information> ();
    		if ((vds .getScenes().get(1).getZooms().get(nZoom.getnZoom()).getInformations()!=null)&&(zoomState==0)) {
     
    		    for (int i=0;i<vds .getScenes().get(1).getZooms().get(nZoom.getnZoom()).getInformations().size();i++) {
    		    	Information article =vds .getScenes().get(1).getZooms().get(nZoom.getnZoom()).getInformations().get(i);
    	    		selectedQuestions.add(article);
    	    	}
    		}

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