Tenho uma classe chamada “CharacterHeroTemp”, quando depurei o código vi que estava entrando no trecho de codigo em que ele recebe um objeto “CharacterHeroTemp = new CharacterHero();”
Engraçado que ele recebe valores normalmente sem reclamar de “null pointer excepetion” na hora, mas quando mando adicionar ele a outra ref, recebo um null pointer referente a ele ( pois seus atributos tem valor)
Vou reiniciar o PC, se não for isso não sei oque mais pode ser. (rsrsr…)
@Edit
Reiniciei e nada, to olhando o codigo e vejo o objeto ser criado, masnão acho a origem do problema.
Código da classe
package game.xml;
import game.objects.CharacterHero;
import game.objects.Classe;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* @author Michel Montenegro
*/
public class CharacterHeroXMLReader extends DefaultHandler{
/** Buffer que guarda as informações quando um texto é encontrado */
private StringBuffer valorAtual = new StringBuffer(50);
/** Lista que possui os contatos do arquivo XML */
private ArrayList<CharacterHero> characterHeros = new ArrayList<CharacterHero>();
public ArrayList<CharacterHero> getCharacterHeros() {
return characterHeros;
}
/** Objetos temporários, apenas para coletar as informações do XML */
private CharacterHero characterHeroTemp;
//contantes que representam as tags do arquivo XML
private final String NODE_CHARACTER_HERO = "characterHero";
private final String ATT_ID = "id";
private final String ATT_NAME = "name";
private final String NODE_TOTAL_BONUS_LEVEL = "totalBonusLevel";
private final String NODE_LEVEL = "level";
private final String NODE_EXPERIENCE = "experience";
private final String NODE_HP = "hp";
private final String NODE_MP = "mp";
private final String NODE_STRENGTH = "strength";
private final String NODE_DEXTERITY = "dexterity";
private final String NODE_INTELLIGENCE = "intelligence";
private final String NODE_CONSTITUTION = "constitution";
private final String NODE_CHARISMA = "charisma";
private final String NODE_GENDER = "gender";
private final String NODE_GOLD = "gold";
private final String NODE_HISTORY = "history";
private final String NODE_TYPECLASS = "typeClass";
private final String NODE_CLASSE = "classe";
private final String ATT_CLASSE_ID = "id";
private String currentElement = null;
private static CharacterHeroXMLReader instance;
public static CharacterHeroXMLReader getInstance() {
if (instance == null) {
instance = new CharacterHeroXMLReader();
}
return instance;
}
public CharacterHeroXMLReader() {
super();
try {
parse();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public CharacterHero getCharacterHero(int id){
Iterator<CharacterHero> it = characterHeros.iterator();
while (it.hasNext()) {
CharacterHero characterHero = it.next();
System.out.println(characterHero.getId()+"-"+ id);
if (characterHero.getId()==id){
return characterHero;
}
}
return null;
}
public CharacterHero getCharacterHero(String name){
Iterator<CharacterHero> it = characterHeros.iterator();
while (it.hasNext()) {
CharacterHero characterHero = it.next();
if (characterHero.getName().equals(name)){
return characterHero;
}
}
return null;
}
/**
* Constutor que inicializa os objetos necessários para fazer o parse
* do arquivo contato.xml
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
*/
public void parse() throws ParserConfigurationException, SAXException, IOException {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser parser = spf.newSAXParser();
parser.parse("resources/xml/characterHero.xml", this );
}
/**
* Indica que o parser achou o início do documento XML. Este evento não
* lhe passa qualquer informação, apenas indica que o parser vai começar
* a escanear o arquivo XML.
*/
public void startDocument() {
System.out.println("Iniciando a leitura do XML");
}
/**
* Indica que o parser achou e fim do documento XML.
*/
public void endDocument() {
System.out.println("Acabou a leitura do XML");
}
/**
* Indica que o parser achou o início de uma tag (tag de abertura/início).
* Este evento fornece o nome do elemento, o nome e valor dos atributos
* deste elemento, e também pode fornecer as informações sobre o namespace.
*/
public void startElement(String uri, String localName, String tag, Attributes atributos){
//cria os Objetos
if (tag.equalsIgnoreCase(NODE_CHARACTER_HERO)){
this.characterHeroTemp = new CharacterHero();
System.out.println(this.characterHeroTemp);
currentElement = NODE_CHARACTER_HERO;
} else if (tag.equalsIgnoreCase(NODE_CLASSE)){
//---
currentElement = NODE_CLASSE;
}
//imprime o caminho da tag
System.out.print("\n" + tag + ": ");
//se o elemento possui atributos, imprime
for (int i=0; i< atributos.getLength(); i++){
System.out.print(" " + atributos.getQName(i) + "=" + atributos.getValue(i));
if (currentElement.equals(NODE_CHARACTER_HERO)==true && atributos.getQName(i).equalsIgnoreCase(ATT_ID)){
this.characterHeroTemp.setId(Integer.parseInt(atributos.getValue(i)));
} else if (currentElement.equals(NODE_CHARACTER_HERO)==true && atributos.getQName(i).equalsIgnoreCase(ATT_NAME)){
this.characterHeroTemp.setName(atributos.getValue(i));
} else if (currentElement.equals(NODE_CLASSE)==true && atributos.getQName(i).equalsIgnoreCase(ATT_CLASSE_ID)){
Classe classe = ClasseXMLReader.getInstance().getClasse(Integer.parseInt(atributos.getValue(i)));
this.characterHeroTemp.setAnimationObjectMovement(classe.getAnimationObjectMovement());
this.characterHeroTemp.setCharisma(classe.getCharisma());
this.characterHeroTemp.setConstitution(classe.getConstitution());
this.characterHeroTemp.setDexterity(classe.getDexterity());
this.characterHeroTemp.setExperience(classe.getExperience());
this.characterHeroTemp.setGender(classe.getGender());
this.characterHeroTemp.setGold(classe.getGold());
this.characterHeroTemp.setHp(classe.getHp());
this.characterHeroTemp.setImagemFace(classe.getImagemFace());
this.characterHeroTemp.setIntelligence(classe.getIntelligence());
this.characterHeroTemp.setLevel(classe.getLevel());
this.characterHeroTemp.setMp(classe.getMp());
this.characterHeroTemp.setNameClasse(classe.getNameClasse());
this.characterHeroTemp.setStrength(classe.getStrength());
this.characterHeroTemp.setTerrainType(classe.getTerrainType());
this.characterHeroTemp.setHistory(classe.getHistory());
this.characterHeroTemp.setTypeClass(classe.getTypeClass());
this.characterHeroTemp.setSkills(classe.getSkills());
}
}
}
/**
* Indica que o parser achou o fim de uma tag/elemento.
* Este evento fornece o nome do elemento, e também pode
* fornecer as informações sobre o namespace.
*/
public void endElement(String uri, String localName, String tag){
//adiciona os objetos em suas slistas
if (tag.equalsIgnoreCase(NODE_CHARACTER_HERO)){
this.characterHeros.add(this.characterHeroTemp);
System.out.println();
}
//CharacterHero
else if (currentElement.equals(NODE_CHARACTER_HERO) && tag.equalsIgnoreCase(NODE_TOTAL_BONUS_LEVEL)){
this.characterHeroTemp.setTotalBonusLevel(Integer.parseInt(valorAtual.toString().trim()));
}else if (currentElement.equals(NODE_CHARACTER_HERO) && tag.equalsIgnoreCase(NODE_LEVEL)){
this.characterHeroTemp.setLevel(Integer.parseInt(valorAtual.toString().trim()));
} else if (currentElement.equals(NODE_CHARACTER_HERO) && tag.equalsIgnoreCase(NODE_EXPERIENCE)){
this.characterHeroTemp.setExperience(Integer.parseInt(valorAtual.toString().trim()));
} else if (currentElement.equals(NODE_CHARACTER_HERO) && tag.equalsIgnoreCase(NODE_HP)){
this.characterHeroTemp.setHp(Integer.parseInt(valorAtual.toString().trim()));
} else if (currentElement.equals(NODE_CHARACTER_HERO) && tag.equalsIgnoreCase(NODE_MP)){
this.characterHeroTemp.setMp(Integer.parseInt(valorAtual.toString().trim()));
} else if (currentElement.equals(NODE_CHARACTER_HERO) && tag.equalsIgnoreCase(NODE_STRENGTH)){
this.characterHeroTemp.setStrength(Integer.parseInt(valorAtual.toString().trim()));
} else if (currentElement.equals(NODE_CHARACTER_HERO) && tag.equalsIgnoreCase(NODE_DEXTERITY)){
this.characterHeroTemp.setDexterity(Integer.parseInt(valorAtual.toString().trim()));
} else if (currentElement.equals(NODE_CHARACTER_HERO) && tag.equalsIgnoreCase(NODE_INTELLIGENCE)){
this.characterHeroTemp.setIntelligence(Integer.parseInt(valorAtual.toString().trim()));
} else if (currentElement.equals(NODE_CHARACTER_HERO) && tag.equalsIgnoreCase(NODE_CONSTITUTION)){
this.characterHeroTemp.setConstitution(Integer.parseInt(valorAtual.toString().trim()));
} else if (currentElement.equals(NODE_CHARACTER_HERO) && tag.equalsIgnoreCase(NODE_CHARISMA)){
this.characterHeroTemp.setCharisma(Integer.parseInt(valorAtual.toString().trim()));
} else if (currentElement.equals(NODE_CHARACTER_HERO) && tag.equalsIgnoreCase(NODE_GENDER)){
this.characterHeroTemp.setGender(Integer.parseInt(valorAtual.toString().trim()));
} else if (currentElement.equals(NODE_CHARACTER_HERO) && tag.equalsIgnoreCase(NODE_GOLD)){
this.characterHeroTemp.setGold(Integer.parseInt(valorAtual.toString().trim()));
} else if (currentElement.equals(NODE_CHARACTER_HERO) && tag.equalsIgnoreCase(NODE_HISTORY)){
this.characterHeroTemp.setHistory(valorAtual.toString().trim());
} else if (currentElement.equals(NODE_CHARACTER_HERO) && tag.equalsIgnoreCase(NODE_TYPECLASS)){
this.characterHeroTemp.setTypeClass(valorAtual.toString().trim());
}
//limpa o valor Atual
valorAtual.delete(0, valorAtual.length());
}
/**
* Indica que o parser achou algum Texto (Informação).
*/
public void characters(char[] ch, int start, int length) {
System.out.print(String.copyValueOf(ch,start,length).trim());
valorAtual.append(ch,start,length);
}
/**
* Imprime valores
*/
public void imprime(){
for (int i=0; i<characterHeros.size(); i++){
System.out.println(characterHeros.get(i));
}
}
public static void main(String[] args){
try {
CharacterHeroXMLReader reader = new CharacterHeroXMLReader();
reader.parse();
System.out.println("\n\n<<<<Monstrando as informações coletadas:>>>>");
reader.imprime();
} catch (ParserConfigurationException e) {
System.out.println("O parser não foi configurado corretamente.");
e.printStackTrace();
} catch (SAXException e) {
System.out.println("Problema ao fazer o parse do arquivo.");
e.printStackTrace();
} catch (IOException e) {
System.out.println("O arquivo não pode ser lido.");
e.printStackTrace();
}
}
}