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

 Java Discussion :

Erreur "NullPointerException" mais la variable est instanciée


Sujet :

Java

  1. #1
    Membre à l'essai
    Homme Profil pro
    Inscrit en
    Décembre 2012
    Messages
    16
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations forums :
    Inscription : Décembre 2012
    Messages : 16
    Points : 15
    Points
    15
    Par défaut Erreur "NullPointerException" mais la variable est instanciée
    Bonjour,

    Je cherche à trouver la valeur d'un JComboBox. Donc, j'ai instancié une variable :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    public static String Port;
    Ensuite dans ActionListener :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
        private void PortListActionPerformed(java.awt.event.ActionEvent evt) {
            PortList.setSelectedIndex(0);
            Port = PortList.getSelectedItem().toString();
            System.out.println(Port);
        }
    Donc ici le Port s'affiche mais quand je l'appelle dans main le programme m'affiche l'erreur NullPointerException sur :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    JavaSerialPort modeEve = new JavaSerialPort(Port);
    Je sais que cette fonction "JavaSerialPort" demande le Port mais ce que je ne sais pas c'est pourquoi Port est Null.

    Quelqu'un saurait-il m'indiquer d'où peut venir le problème ?

    Merci d'avance pour votre aide.

  2. #2
    Membre expert
    Avatar de Golgotha
    Homme Profil pro
    Full-stack Web Developer
    Inscrit en
    Août 2007
    Messages
    1 386
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Full-stack Web Developer
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Août 2007
    Messages : 1 386
    Points : 3 531
    Points
    3 531
    Billets dans le blog
    1
    Par défaut
    Bonjour,

    Un problème de portée ?
    Consultant et développeur full-stack spécialiste du Web
    faq jQuery - règles du forum - faqs web

  3. #3
    Membre à l'essai
    Homme Profil pro
    Inscrit en
    Décembre 2012
    Messages
    16
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations forums :
    Inscription : Décembre 2012
    Messages : 16
    Points : 15
    Points
    15
    Par défaut
    Oui je veux que la variable "port" soit transmise en valeur dans la dernière méthode dans main().

    Ok, j'ai testé et j'ai trouvé que JavaSerialPort est exécuté avant que la variable Port soit instanciée à une valeur. Donc ma question maintenant est de savoir comment je peux faire pour attendre la valeur du Port et ensuite exécuter JavaSerialPort. Merci encore.

  4. #4
    Invité
    Invité(e)
    Par défaut
    Salut

    Il nous faudrait, pour t'aider, plus de code. Ici, on ne sait pas quelle est la portée de ta variable static Port, dans quel ordre tes appels sont effectués... Tu pourrais nous fournir l'intégralité du code des classes dans lesquelles les segments de code que tu as posté interviennent ?

  5. #5
    Membre à l'essai
    Homme Profil pro
    Inscrit en
    Décembre 2012
    Messages
    16
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations forums :
    Inscription : Décembre 2012
    Messages : 16
    Points : 15
    Points
    15
    Par défaut
    Ok voila 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
    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
    package javatool;
     
    import com.sun.comm.Win32Driver;
    import java.io.*;
    import java.util.*;
    import javax.comm.*;
    import javax.swing.*;
     
     
    public class JavaSerialPort extends Thread implements Runnable,SerialPortEventListener {
     
        // Variables declaration - do not modify
        private static javax.swing.JComboBox PortList;
        private javax.swing.JToggleButton StartCapture;
        private javax.swing.JTextField Traffic;
        private javax.swing.JFrame JFrame;
        private javax.swing.GroupLayout Layout;
        private CommPortIdentifier portId;
        private SerialPort serialPort;
        private BufferedReader fluxLecture;
        private boolean running;
        Thread readthread;
        InputStream inputstream;
     
        public static String Port;
     
         // End of variables declaration
    	/**
             * Constructeur qui récupère l'identifiant du port et lance l'ouverture.
             */
    	public JavaSerialPort(String port ) {
                     initComponents();
    		//initialisation du driver
    		Win32Driver w32Driver = new Win32Driver();
    		w32Driver.initialize();
    		//récupération de l'identifiant du port
    		try {
    			portId = CommPortIdentifier.getPortIdentifier(port);
    		} catch (NoSuchPortException e) {
    		}
     
    		//ouverture du port
    		try {
    			serialPort = (SerialPort) portId.open("Micropixel", 2000);
    		} catch (PortInUseException e) {
    		}
    		//récupération du flux
    		try {
    			inputstream = serialPort.getInputStream();
    		} catch (IOException e) {
    		}
    		//ajout du listener
    		try {
    			serialPort.addEventListener(this);
    		} catch (TooManyListenersException e) {
    		}
    		//paramétrage du port
    		serialPort.notifyOnDataAvailable(true);
    		try {   
    			serialPort.setSerialPortParams(
    				serialPort.getBaudRate(),
    				serialPort.getDataBits(),
    				serialPort. getStopBits(),
    				serialPort.getParity());
    		} catch (UnsupportedCommOperationException e) {
    		}
    		System.out.println("port ouvert, attente de lecture");
    	}
     
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents  () {
     
            PortList = new javax.swing.JComboBox();
            StartCapture = new javax.swing.JToggleButton();
            Traffic = new javax.swing.JTextField();
            JFrame = new javax.swing.JFrame();
            JFrame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            JFrame.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
     
            PortList.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "COM1", "COM2" }));
            PortList.addActionListener(new java.awt.event.ActionListener() {
                @Override
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    PortListActionPerformed(evt);
                }
            });
     
            StartCapture.setText("Start Capture");
            StartCapture.setToolTipText("");
     
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(JFrame.getContentPane());
            JFrame.getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap(46, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(StartCapture)
                            .addGap(95, 95, 95))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(PortList, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(18, 18, 18)
                            .addComponent(Traffic, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(38, 38, 38))))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(122, 122, 122)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(PortList, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(Traffic, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(88, 88, 88)
                    .addComponent(StartCapture)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
     
     
           PortList.setSelectedIndex(0);
     
     
        }// </editor-fold>
     
        private void PortListActionPerformed(java.awt.event.ActionEvent evt) {
     
            Port = PortList.getSelectedItem().toString();
            System.out.println(Port);
        }
    public void TrafficShow (String S)
    {
     
    }
        /**
         * @param args the command line arguments
         */
        @Override
    	public void run() {
    		running = true;
    		while (running) {
    			try {
    				Thread.sleep(2000);
    			} catch (InterruptedException e) {
    			}
    		}
    		//fermeture du flux et port
    		try {
    			inputstream.close();
    		} catch (IOException e) {
    		}
    		serialPort.close();
    	}
    	/**
             * Méthode de gestion des événements.
             */
        @Override
    	public void serialEvent(SerialPortEvent event) {
    		//gestion des événements sur le port :
    		//on ne fait rien sauf quand les données sont disponibles
    		switch (event.getEventType()) {
    			case SerialPortEvent.BI :
    			case SerialPortEvent.OE :
    			case SerialPortEvent.FE :
    			case SerialPortEvent.PE :
    			case SerialPortEvent.CD :
    			case SerialPortEvent.CTS :
    			case SerialPortEvent.DSR :
    			case SerialPortEvent.RI :
    			case SerialPortEvent.OUTPUT_BUFFER_EMPTY :
    				break;
    			case SerialPortEvent.DATA_AVAILABLE :
     
                                byte [] readbuffer = new byte [20];
                                try {
                                    while (inputstream.available () > 0 )
                                    {
                                        int nymBytes = inputstream.read(readbuffer);
                                    }
                                    String tr = new String(readbuffer);
                                    System.out.print(tr);
                                    Traffic.setText(tr);
     
                                }catch (IOException e) {System.out.println(e);}
     
     
    				break;
    		}
    	}
    	/*
    	 * Permet l'arrêt du thread
    	 */
    	public void stopThread() {
     
    		running = false;
    	}
    	/**
             * Méthode principale de l'exemple.
             */
    	public static void main(String[] args) {
    		//Récuperation du port en argument
                  java.awt.EventQueue.invokeLater(new Runnable() {
                     @Override
                public void run() {
                    new TrafficSerialPort().setVisible(true);}});
     
    		//lancement de l'appli
     
                    if (Port == null )
                        {}
                    else
                    {
    		JavaSerialPort modeEve=new JavaSerialPort(Port);
    		modeEve.start();
    		//"interface utilisateur"
    		System.out.println("taper q pour quitter");
    		//construction flux lecture
    		BufferedReader clavier =
    			new BufferedReader(new InputStreamReader(System.in));
    		//lecture sur le flux entrée.
    		try {
    			String lu = clavier.readLine();
    			while (!lu.equals("q")) {
    			}
    		} catch (IOException e) {
    		}
    		modeEve.stopThread();}
    	}
    }

  6. #6
    Membre à l'essai
    Homme Profil pro
    Inscrit en
    Décembre 2012
    Messages
    16
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations forums :
    Inscription : Décembre 2012
    Messages : 16
    Points : 15
    Points
    15
    Par défaut
    Ok, j'ai modifié mon programme est ça fonctionne mais le problème est que je veux qu'il attende la valeur du port et qu'ensuite JavaSerialPort soit appelé, alors j'ai fait ça :
    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
    public class JavaSerialPort extends Thread implements Runnable,SerialPortEventListener {
     
        // Variables declaration - do not modify
        private static javax.swing.JComboBox PortList;
        private javax.swing.JToggleButton StartCapture;
        private javax.swing.JTextField Traffic;
        private javax.swing.JFrame JFrame;
        private javax.swing.GroupLayout Layout;
        private CommPortIdentifier portId;
        private SerialPort serialPort;
        private BufferedReader fluxLecture;
        private boolean running;
        Thread readthread;
        InputStream inputstream;
     
        public static String Port;
     
         // End of variables declaration
        /**
         * Constructeur qui récupère l'identifiant du port et lance l'ouverture.
         */
        public JavaSerialPort( ) {
            initComponents();
            //initialisation du driver
            Win32Driver w32Driver = new Win32Driver();
            w32Driver.initialize();
            //récupération de l'identifiant du port
            try {
                portId = CommPortIdentifier.getPortIdentifier(Port);
            } catch (NoSuchPortException e) {
            }
     
            //ouverture du port
            try {
                serialPort = (SerialPort) portId.open("Micropixel", 2000);
            } catch (PortInUseException e) {
            }
            //récupération du flux
            try {
                inputstream = serialPort.getInputStream();
            } catch (IOException e) {
            }
            //ajout du listener
            try {
                serialPort.addEventListener(this);
            } catch (TooManyListenersException e) {
            }
            //paramétrage du port
            serialPort.notifyOnDataAvailable(true);
            try {   
                serialPort.setSerialPortParams(
                    serialPort.getBaudRate(),
                    serialPort.getDataBits(),
                    serialPort. getStopBits(),
                    serialPort.getParity());
            } catch (UnsupportedCommOperationException e) {
            }
            System.out.println("port ouvert, attente de lecture");
        }
     
        private void PortListActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
     
            Port = PortList.getSelectedItem().toString();
            System.out.println(Port);
        }
     
        public void TrafficShow (String S)
        {
     
        }
     
        /**
         * @param args the command line arguments
         */
        @Override
        public void run() {
            running = true;
            while (running) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                }
            }
            //fermeture du flux et port
            try {
                inputstream.close();
            } catch (IOException e) {
            }
            serialPort.close();
        }
     
        /**
         * Méthode principale de l'exemple.
         */
        public static void main(String[] args) {
            //Récuperation du port en argument
            java.awt.EventQueue.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        new TrafficSerialPort().setVisible(true);
                    }}
                );
     
            //lancement de l'appli
            if (Port == null )
            {;}
            else
            {
                JavaSerialPort modeEve = new JavaSerialPort();
                modeEve.start();
                //"interface utilisateur"
                System.out.println("taper q pour quitter");
                //construction flux lecture
                BufferedReader clavier = new BufferedReader(new InputStreamReader(System.in));
                //lecture sur le flux entrée.
                try {
                    String lu = clavier.readLine();
                    while (!lu.equals("q")) {
                    }
                } catch (IOException e) {
                }
                modeEve.stopThread();
            }
        }
    }
    Mais rien ne s'affiche.

  7. #7
    Membre régulier
    Homme Profil pro
    Inscrit en
    Septembre 2010
    Messages
    116
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Cher (Centre)

    Informations forums :
    Inscription : Septembre 2010
    Messages : 116
    Points : 88
    Points
    88
    Par défaut
    Bonsoir,

    Tu n'affiche rien dans ton While:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    try {
    			String lu = clavier.readLine();
    			while (!lu.equals("q")) {
     
    //si tu mets ici?: System.out.println (lu);
    			}
    		} catch (IOException e) {

  8. #8
    Membre à l'essai
    Homme Profil pro
    Inscrit en
    Décembre 2012
    Messages
    16
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations forums :
    Inscription : Décembre 2012
    Messages : 16
    Points : 15
    Points
    15
    Par défaut
    Oui je n'affiche rien car ce bloc sert à attendre que l'utilisateur entre 'q' pour quitter le programme.

  9. #9
    Modérateur
    Avatar de dinobogan
    Homme Profil pro
    ingénieur
    Inscrit en
    Juin 2007
    Messages
    4 073
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 42
    Localisation : France

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

    Informations forums :
    Inscription : Juin 2007
    Messages : 4 073
    Points : 7 163
    Points
    7 163
    Par défaut
    Citation Envoyé par mad_gozzilla Voir le message
    Oui je n'affiche rien car ce bloc sert à attendre que l'utilisateur entre 'q' pour quitter le programme.
    C'est une boucle infinie. Si la variable lu ne vaut pas "q", la boucle ne finira jamais.
    N'oubliez pas de consulter les FAQ Java et les cours et tutoriels Java
    Que la force de la puissance soit avec le courage de ta sagesse.

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

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