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

avec Java Discussion :

mais pourquoi ce NullPointerException :/


Sujet :

avec Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre éclairé
    Homme Profil pro
    Développeur Web
    Inscrit en
    Avril 2007
    Messages
    500
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 37
    Localisation : France, Loire Atlantique (Pays de la Loire)

    Informations professionnelles :
    Activité : Développeur Web

    Informations forums :
    Inscription : Avril 2007
    Messages : 500
    Par défaut mais pourquoi ce NullPointerException :/
    Bonjour, j'ai actuellement les classes suivantes :

    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
    @Repository
    public class TownService implements ITownService {
     
    	@PersistenceContext(type = PersistenceContextType.TRANSACTION)
    	private EntityManager em;
     
    	@Transactional(propagation = Propagation.REQUIRED)
    	public String getDepartmentNameForDepCode(int depCode) {
    		String myDpt = null;
    		if (depCode > 9) {
    			myDpt = Integer.toString(depCode);
    		} else {
    			myDpt = "0" + Integer.toString(depCode);
    		}
    		System.out.println("myDpt"+myDpt);
    		Query q = em
    				.createQuery("select distinct(t.department) from Town t   where substring(t.zipCode,1,2)=?1");
    		q.setParameter(1, myDpt);
    		String department = (String) q.getSingleResult();
    		return department;
    	}
    }
    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
    public class JSONUtils {
    
       
    	private static TownService monTownService;
    
       public static String JSONJob(IJob job) {
            StringBuilder sb = new StringBuilder();       
            String dept;
            dept =  JSONUtils.getDepartNameForDepCode(44240/*Integer.parseInt(job.getWorkAddress().getZipCode())*/);
            System.out.println("test"+dept);
    
            sb.append("{\"id\":").append(job.getId()).append(",");
    
            sb.append("\"dc\":\"").append(norm(job.getDescription())).append("\",");
    
            sb.append("\"na\":\"").append(norm(job.getName())).append("\",");
    
            sb.append("\"pd\":\"").append(job.getShortFormattedPublicationDate())
                    .append("\",");
    
            sb.append("\"zp\":\"").append(
                    norm(String.valueOf(job.getAddress().getZipCode()))).append("\",");
    
            sb.append("\"st\":\"").append(norm(job.getAddress().getNumberAndStreet()))
                    .append("\",");
    
            sb.append("\"fId\":").append(job.getFunction().getId()).append(",");
    
            sb.append("\"tw\":\"").append(norm(job.getAddress().getTown()))
                    .append("\",");
    
            sb.append("\"func\":\"").append(norm(job.getFunction().getName())).append(
                    "\",");
    
            sb.append("\"typId\":").append(job.getType().getId()).append(",");
    
            sb.append("\"type\":\"").append(norm(job.getType().getName())).append("\",");
    
            sb.append("\"wtw\":\"").append(norm(job.getWorkAddress().getTown())).append(
                    "\",");
            
            sb.append("\"wrg\":\"").append(norm(job.getWorkAddress().getRegion())).append(
            "\",");
            
            sb.append("\"wdpt\":\"").append(norm(dept)).append(
            "\",");
            
            sb.append("\"wzp\":\"").append(norm(job.getWorkAddress().getZipCode()))
                    .append("\",");
    
            sb.append("\"cna\":\"").append(norm(job.getCompany().getName())).append(
                    "\",");
            sb.append("\"externalCandidateURL\":\"").append(job.getUrl()).append("\",");
    
            sb.append("\"cId\":").append(job.getCompany().getId());
    
            if (job.getLatitude() != null) {
                sb.append(",\"lat\":").append(job.getLatitude());
                sb.append(",\"lg\":").append(job.getLongitude());
            }
    
            if (job.getCompany().getUrlSite() == null) {
                sb.append(",\"urlSite\":").append(job.getCompany().getUrlSite()).append(
                        "");
            } else {
                sb.append(",\"urlSite\":\"").append(job.getCompany().getUrlSite())
                        .append("\"");
            }
    
            sb.append("}");
            return sb.toString();
        }	
    
    	private static String getDepartNameForDepCode(int nb){
    		System.out.println("test1"+monTownService.toString());
    		String result = monTownService.getDepartmentNameForDepCode(nb);
    		return result;
    	}
    }
    mon soucis actuellement c'est que java me retourne un NullPointerException sur mon monTownService, pourtant je ne vois pas où est le probleme et encore moins comment le corriger :/

  2. #2
    Modérateur

    Profil pro
    Inscrit en
    Septembre 2004
    Messages
    12 582
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2004
    Messages : 12 582
    Par défaut
    L'exception te dit dans quelle classe et à quelle ligne du fichier elle arrive. Mais toi, tu ne nous le dis pas.

    A priori, ton EntityManager em est null.


    En Java comme pour le reste de l'informatique, on copie les messages d'erreur tels que. Ou du moins on garde sa partie principale telle que. On ne la retape pas à la main.
    N'oubliez pas de consulter les FAQ Java et les cours et tutoriels Java

  3. #3
    Expert éminent
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 482
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 46
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 482
    Par défaut
    comme je dit toujours:

    pas de stacktrace -> pas de chocolat!

  4. #4
    Membre éclairé
    Homme Profil pro
    Développeur Web
    Inscrit en
    Avril 2007
    Messages
    500
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 37
    Localisation : France, Loire Atlantique (Pays de la Loire)

    Informations professionnelles :
    Activité : Développeur Web

    Informations forums :
    Inscription : Avril 2007
    Messages : 500
    Par défaut
    hm oui, oubli de ma part pour la trace :

    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
    java.lang.NullPointerException
    	at com.apps.needprofileclient.servlet.utils.JSONUtils.getDepartNameForDepCode(JSONUtils.java:554)
    	at com.apps.needprofileclient.servlet.utils.JSONUtils.JSONJob(JSONUtils.java:314)
    	at com.apps.needprofileclient.servlet.utils.JSONUtils.JSONJobs(JSONUtils.java:388)
    	at com.apps.needprofileclient.servlet.utils.JSONUtils.JSONJobs(JSONUtils.java:485)
    	at com.apps.needprofileclient.servlet.RetrieveJobs.doGet(RetrieveJobs.java:61)
    	at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    	at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    	at com.zlatkovic.HttpRedirectFilter.doFilter(HttpRedirectFilter.java:243)
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    	at com.components.needprofilecommon.filter.UTF8Filter.doFilter(UTF8Filter.java:24)
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
    	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
    	at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:857)
    	at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:565)
    	at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1509)
    	at java.lang.Thread.run(Thread.java:619)
    j'ai pointé les lignes en rouge dans le 1er post.

    Concernant l'entity manager, si j'enleve les lignes liées à TownService, tout se lance correctement, c'est donc clairement lié à cette classe, mais c'est là ou je bloque, je pense avoir codé correctement là :/

  5. #5
    Modérateur

    Profil pro
    Inscrit en
    Septembre 2004
    Messages
    12 582
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2004
    Messages : 12 582
    Par défaut
    Bah voilà, c'est tout de suite plus clair.

    Le problème est que monTownService est null. Il faut l'initialiser. Faire un new TownService() ou je ne sais pas comment tu est censé obtenir un TownService, mais faire ça.
    N'oubliez pas de consulter les FAQ Java et les cours et tutoriels Java

  6. #6
    Membre émérite
    Profil pro
    Inscrit en
    Avril 2007
    Messages
    764
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2007
    Messages : 764
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    public class JSONUtils {
       
       private static TownService monTownService;
       
       private static String getDepartNameForDepCode(int nb) {
          System.out.println("test1"+monTownService.toString());
          String result = monTownService.getDepartmentNameForDepCode(nb);
          return result;
       }
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    java.lang.NullPointerException
    	at com.apps.needprofileclient.servlet.utils.JSONUtils.getDepartNameForDepCode(JSONUtils.java:554)
    [...]
    Ton objet monTownService n'est jamais initialisé...

  7. #7
    Expert éminent
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 482
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 46
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 482
    Par défaut
    private static TownService monTownService;


    tu ne donne jamais de valeur à ce champ, donc il est nul, donc tu ne peux pas appeler de méthodes dessus....

    edit: trop lent

  8. #8
    Membre éclairé
    Homme Profil pro
    Développeur Web
    Inscrit en
    Avril 2007
    Messages
    500
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 37
    Localisation : France, Loire Atlantique (Pays de la Loire)

    Informations professionnelles :
    Activité : Développeur Web

    Informations forums :
    Inscription : Avril 2007
    Messages : 500
    Par défaut
    En effet je me doutais bien que l'erreur allait venir de là au départ, pourtant dans une autre classe il y a ceci :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    	@Autowired
    	@Qualifier("townService")
    	private ITownService townService;
     
    	public List<IRegion> getRegionList() {
    		return townService.getRegionsList();
    	}
     
    	public List<IDepartement> getDepartList(){
    		return townService.getDepartementsList();
    	}
    Et là, townService n'est jamais initialisé, c'est ca que je trouve bizarre^^

Discussions similaires

  1. NullPointerException, Mais pourquoi ?
    Par toshiro92 dans le forum Android
    Réponses: 6
    Dernier message: 06/07/2011, 17h47
  2. Un NullPointerException mais pourquoi ?
    Par Franck.H dans le forum Langage
    Réponses: 8
    Dernier message: 13/11/2006, 20h35
  3. erreur LOOP attendu , mais pourquoi?
    Par ahage4x4 dans le forum ASP
    Réponses: 10
    Dernier message: 23/05/2005, 16h22
  4. Mais pourquoi ... Avec IE les tableaux sont décentrés ?
    Par nebule dans le forum Balisage (X)HTML et validation W3C
    Réponses: 3
    Dernier message: 26/11/2004, 10h04
  5. [Execution] qtintf70.dll Mais pourquoi?
    Par Pedro dans le forum EDI
    Réponses: 4
    Dernier message: 03/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