Android sax parser error while getting html data - java

Hi Am trying to parse the data from xml which contains the html data using sax parser the data in xml is like below
but while parsing am getting the data between details tag as different strings, not getting as single string which contains full html data between dtails tag.
can anyone help me out please how can i resolve this.
<details>
<html> <b>Animal Care BTEC Level 1</b>
<hr style="height:0.03em;width:18em;border:1px ;border-style:dotted;margin-left:0; color:white"
/>
<body>
<e>Course Length: 1 year</e>
<br />
<e>Fees: Free for 16-18 year olds</e>
<br />
<e>Course Code: B332</e>
<br />
<br />
<body> <b> Overview:</b>
<hr style="height:0.03em;width:18em;border:1px ;border-style:dotted;margin-left:0 ;color:white"
/>
<p>The course provides a basic introduction to working with animals. A practical
approach allows student to develop animal handling skills along side personal
and social development. Student will have access to a wide range of animals
to enable them to develop skills and confidence. Each week practical work
will include time spent on the animal unit, the farm and at the equine
centre to enable students to develop practical ability in all three areas.</p>
</body>
</html>
</details>
package com.bb.mypotential;
import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class SaxHandler extends DefaultHandler {
public static Courseobj courseobj;
public static Subject subjectobj;
public boolean courseidb = false;
public boolean coursesubjectb = false;
public boolean coursetitleb = false;
public boolean subjectidb = false;
public boolean subjectnameb = false;
public boolean subjectcodeb = false;
public boolean subjectdetailsb = false;
public boolean entryRequirementb = false;
public boolean courseContentb = false;
public boolean futhuroptionsb = false;
public boolean additionalInfob = false;
public boolean fundingInfob = false;
public boolean assignmethodb = false;
public String currentvalue = null;
public ArrayList<Subject> subarr = null;
String TAG = getClass().getSimpleName();
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
if (localName.equals("Courses")) {
MainListActivity.value = new ArrayList<Courseobj>();
}
if (localName.equals("Course")) {
courseobj = new Courseobj();
subarr = new ArrayList<Subject>();
String courseid = attributes.getValue(0);// getValue("ID");
courseobj.setCOURSE_ID(courseid);
courseidb = true;
} else if (localName.equalsIgnoreCase("title")) {
coursetitleb = true;
} else if (localName.equals("subject")) {
subjectobj = new Subject();
String subid = attributes.getValue(0);
subjectobj.setSUB_ID(subid);
subjectidb = true;
} else if (localName.equals("name")) {
subjectnameb = true;
} else if (localName.equals("code")) {
subjectcodeb = true;
} else if (localName.equals("details")) {
subjectdetailsb = true;
} else if (localName.equals("entryRequirement")) {
entryRequirementb = true;
} else if (localName.equals("courseContent")) {
courseContentb = true;
} else if (localName.equals("assignmentMethods")) {
assignmethodb = true;
} else if (localName.equals("furtherOptions")) {
futhuroptionsb = true;
} else if (localName.equals("additionalInformation")) {
additionalInfob = true;
} else if (localName.equals("fundingInformation")) {
fundingInfob = true;
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
currentvalue = new String(ch, start, length);
if (coursetitleb) {
courseobj.setTitle(currentvalue);
} else if (subjectnameb) {
subjectobj.setName(currentvalue);
} else if (subjectcodeb) {
subjectobj.setCode(currentvalue);
} else if (subjectdetailsb) {
subjectobj.setDetails(currentvalue);
} else if (entryRequirementb) {
subjectobj.setEntryRequirement(currentvalue);
} else if (courseContentb) {
subjectobj.setCourseContent(currentvalue);
} else if (assignmethodb) {
subjectobj.setCourseContent(currentvalue);
} else if (futhuroptionsb) {
subjectobj.setFuthuroptions(currentvalue);
} else if (additionalInfob) {
subjectobj.setAdditionalInfo(currentvalue);
} else if (fundingInfob) {
subjectobj.setFundingInfo(currentvalue);
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
if (localName.equalsIgnoreCase("Course")) {
courseobj.setSubject(subarr);
MainListActivity.value.add(courseobj);
courseidb = false;
} else if (localName.equalsIgnoreCase("title")) {
coursetitleb = false;
} else if (localName.equals("subject")) {
subarr.add(subjectobj);
subjectidb = false;
} else if (localName.equals("name")) {
subjectnameb = false;
} else if (localName.equals("code")) {
subjectcodeb = false;
} else if (localName.equals("details")) {
subjectdetailsb = false;
} else if (localName.equals("entryRequirement")) {
entryRequirementb = false;
} else if (localName.equals("courseContent")) {
courseContentb = false;
} else if (localName.equals("assignmentMethods")) {
assignmethodb = false;
} else if (localName.equals("furtherOptions")) {
futhuroptionsb = false;
} else if (localName.equals("additionalInformation")) {
additionalInfob = false;
} else if (localName.equals("fundingInformation")) {
fundingInfob = false;
}
}
}

Related

Hibernate does not save in DB using DAO object generated by visual-paradigm

I've a problem with hibernate. I'm trying to save an object into a relational db with hibernate using orm.jar library generated by visual-paradigm tool. The problem is that it does not work but the program does not give me exceptions.
I tried to change my code but the program catches an exception and does not work.
MAIN:
CoordinatorIntrusione c = CoordinatorIntrusione.getInstance();
c.avviaRilevamento();
c.notifyProximityBySerraID(1, 4);
ArrayList<Integer> prova = new ArrayList<Integer>();
prova.add(2);
prova.add(1);
prova.add(9);
c.notifyImageBySerraID(1, prova);
System.out.println("ecco");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
c.ripristinaRilevamento(1, "1");
COORDINATORINTRUSIONE:
public class CoordinatorIntrusione {
private volatile static CoordinatorIntrusione coordinator = null;
private ThreadGroup groupBLThread;
public int avviaRilevamento() {
int code = 0;
EntitySmartFarm esm = EntitySmartFarm.getInstance();
EntityColtivazione[] colt = esm.getColtivazioniAttive();
if(colt.length==0) {
code=-1;
return code;
}
for(int i=0; i<colt.length; i++) {
EntitySerra serra = colt[i].getEntitySerra();
int id = serra.getId();
ControllerRilevaIntrusioneBL controller = new ControllerRilevaIntrusioneBL(id, groupBLThread, "worker"+i);
controller.start();
//System.out.println("ID :"+id);
}
return code;
}
public int negaID(int id, String matricola) {
//throw new UnsupportedOperationException();
int code = -1;
EntitySmartFarm esm = EntitySmartFarm.getInstance();
EntityColtivazione coltivazione = esm.getColtivazioneBySerraID(id);
if(coltivazione == null) return code;
String matResp = coltivazione.getEntitySerra().getResponsabile().getMatricola();
if (!matricola.equals(matResp)) return code;
ControllerRilevaIntrusioneBL controller = this.searchWorkerForID(id);
if (controller == null) return code;
code = controller.negaID();
return code;
}
public int ripristinaRilevamento(int id, String matricola) {
//throw new UnsupportedOperationException();
int code = -1;
EntitySmartFarm esm = EntitySmartFarm.getInstance();
EntityColtivazione coltivazione = esm.getColtivazioneBySerraID(id);
if(coltivazione == null) return code;
String matResp = coltivazione.getEntitySerra().getResponsabile().getMatricola();
if (!matricola.equals(matResp)) return code;
ControllerRilevaIntrusioneBL controller = this.searchWorkerForID(id);
if (controller == null) return code;
code = controller.ripristinaRilevamento();
return code;
}
public int confermaId(int id, String matricola) {
//throw new UnsupportedOperationException();
int code = -1;
EntitySmartFarm esm = EntitySmartFarm.getInstance();
EntityColtivazione coltivazione = esm.getColtivazioneBySerraID(id);
if(coltivazione == null) return code;
String matResp = coltivazione.getEntitySerra().getResponsabile().getMatricola();
if (!matricola.equals(matResp)) return code;
ControllerRilevaIntrusioneBL controller = this.searchWorkerForID(id);
if (controller == null) return code;
code = controller.confermaID();
return code;
// quindi se il code è negativo le matricole non combaciano, se positivo combaciano
}
protected ControllerRilevaIntrusioneBL searchWorkerForID(int idSerra) {
ControllerRilevaIntrusioneBL[] th = new ControllerRilevaIntrusioneBL[groupBLThread.activeCount()];
groupBLThread.enumerate(th);
int i=0;
while(i<th.length) {
if(th[i].getID() == idSerra) return th[i];
i++;
}
return null;
}
private CoordinatorIntrusione() {
groupBLThread = new ThreadGroup("workerCoordinator");
}
public void notifyProximityBySerraID(int idSerra, float value) {
ControllerRilevaIntrusioneBL thread = this.searchWorkerForID(idSerra);
thread.proximityValueArrived(value);
}
public void notifyImageBySerraID(int idSerra, ArrayList<Integer> img) {
ControllerRilevaIntrusioneBL thread = this.searchWorkerForID(idSerra);
thread.imgArrived(img);
}
public static CoordinatorIntrusione getInstance() {
if (coordinator == null) {
synchronized(CoordinatorIntrusione.class){ //Serve la sincronizzazione visto che è solo lettura
if(coordinator == null){
coordinator = new CoordinatorIntrusione();
}
}
}
return coordinator;
}
}
CONTROLLERRILEVAINTRUSIONEBL:
public class ControllerRilevaIntrusioneBL extends Thread{
private int id;
private float[] valoreProssimita;
private ArrayList<Integer> img;
private static final float criticalProxValue =5;
private Semaphore proxsem;
private Semaphore camsem;
private Semaphore ripristinasem;
private Semaphore waitsem ;
protected int rilevaVolti() {
//TODO with python script
//throw new UnsupportedOperationException();
return 0;
}
public synchronized int negaID() {
//throw new UnsupportedOperationException();
int code = 0;
if (waitsem.getQueueLength() > 0) {
waitsem.release();
code = 1;
}
else code = -1;
return code;
}
public synchronized int ripristinaRilevamento() {
//throw new UnsupportedOperationException();
int code = 0;
//System.out.println(ripristinasem.getQueueLength());
if (ripristinasem.getQueueLength() > 0) {
ripristinasem.release();
code = 1;
}
else code = -1;
//System.out.println(ripristinasem.getQueueLength());
return code;
}
public synchronized int confermaID() {
//throw new UnsupportedOperationException();
int code = 0;
if (waitsem.getQueueLength() > 0) {
waitsem.release();
code = 1;
}
else code = -1;
return code;
}
public int getID() {
return id;
}
public void setID(int id) {
this.id = id;
}
#Override
public void run() {
EntitySmartFarm esm = EntitySmartFarm.getInstance();
EntityColtivazione colt = esm.getColtivazioneBySerraID(id);
EntitySerra serra = colt.getEntitySerra();
EntitySensore proximity = serra.getSensoreProssimita();
EntitySensore camera = serra.getSensoreFotografico();
//ProxySerra proxyserra = ProxySerra.getInstance();
while (true) {
//MonitoraggioProssimità
//invio messaggio alla serra
try {
proxsem.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
proximity.setValore(valoreProssimita);
if(valoreProssimita[0] < criticalProxValue){
// invio messaggio camera alla serra
try {
camsem.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
float[] immagine = new float[img.size()];
int index = 0;
for (Integer value: img) {
immagine[index++] = value;
}
camera.setValore(immagine);
int ret = this.rilevaVolti();
if (ret == 0 || ret == -1) {
//New ProxyNotificationSystem
if (ret == 0) {
//ProxyNotificationSystem.inviosegnalazione();
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Europe/Rome"), Locale.ITALY);
Date today = calendar.getTime();
Date ora = calendar.getTime();
int[] array = img.stream().mapToInt(i -> i).toArray();
serra.addIntrusione(today, "Selvaggina", array, ora);
} else {
try {
waitsem.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
//proxynotsys.nviosegnalazione();
}
System.out.println("Thread: "+this.id+" bloccato");
try {
ripristinasem.acquire();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Thread: "+this.id+" Sbloccato");
}
}
}
}
public ControllerRilevaIntrusioneBL(int id, ThreadGroup group, String threadName){
super(group,threadName);
this.id = id;
valoreProssimita = new float[1];
img = new ArrayList<Integer>();
proxsem = new Semaphore(0);
camsem = new Semaphore(0);
ripristinasem = new Semaphore(0);
waitsem = new Semaphore(0);
}
public void proximityValueArrived(float value) {
valoreProssimita[0]=value;
proxsem.release();
}
public void imgArrived(ArrayList<Integer> img) {
this.img=img;
camsem.release();
}
}
ENTITYSERRA (first "addIntrusione" method catches exception and does not work, second "addIntrusione" method does not catch but does not work anyway):
public class EntitySerra {
public EntitySerra() {
}
private java.util.Set this_getSet (int key) {
if (key == vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_ENTITYSERRA_ENTITYEMPLOYERS) {
return ORM_entityEmployers;
}
else if (key == vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_ENTITYSERRA_ENTITYSENSORES) {
return ORM_entitySensores;
}
else if (key == vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_ENTITYSERRA_ENTITYINTRUSIONES) {
return ORM_entityIntrusiones;
}
else if (key == vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_ENTITYSERRA_ENTITYLETTURAS) {
return ORM_entityLetturas;
}
return null;
}
org.orm.util.ORMAdapter _ormAdapter = new org.orm.util.AbstractORMAdapter() {
public java.util.Set getSet(int key) {
return this_getSet(key);
}
};
private int id;
private java.util.Set ORM_entityEmployers = new java.util.HashSet();
private java.util.Set ORM_entitySensores = new java.util.HashSet();
private java.util.Set ORM_entityIntrusiones = new java.util.HashSet();
private java.util.Set ORM_entityLetturas = new java.util.HashSet();
private void setId(int value) {
this.id = value;
}
public int getId() {
return id;
}
public int getORMID() {
return getId();
}
public void setORM_EntityEmployers(java.util.Set value) {
this.ORM_entityEmployers = value;
}
public java.util.Set getORM_EntityEmployers() {
return ORM_entityEmployers;
}
public final vista_architetturale_gestoresmartfarm.entity2.EntityEmployerSetCollection entityEmployers = new vista_architetturale_gestoresmartfarm.entity2.EntityEmployerSetCollection(this, _ormAdapter, vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_ENTITYSERRA_ENTITYEMPLOYERS, vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_MUL_ONE_TO_MANY);
public void setORM_EntitySensores(java.util.Set value) {
this.ORM_entitySensores = value;
}
public java.util.Set getORM_EntitySensores() {
return ORM_entitySensores;
}
public final vista_architetturale_gestoresmartfarm.entity2.EntitySensoreSetCollection entitySensores = new vista_architetturale_gestoresmartfarm.entity2.EntitySensoreSetCollection(this, _ormAdapter, vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_ENTITYSERRA_ENTITYSENSORES, vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_MUL_ONE_TO_MANY);
public void setORM_EntityIntrusiones(java.util.Set value) {
this.ORM_entityIntrusiones = value;
}
public java.util.Set getORM_EntityIntrusiones() {
return ORM_entityIntrusiones;
}
public final vista_architetturale_gestoresmartfarm.entity2.EntityIntrusioneSetCollection entityIntrusiones = new vista_architetturale_gestoresmartfarm.entity2.EntityIntrusioneSetCollection(this, _ormAdapter, vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_ENTITYSERRA_ENTITYINTRUSIONES, vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_MUL_ONE_TO_MANY);
public void setORM_EntityLetturas(java.util.Set value) {
this.ORM_entityLetturas = value;
}
public java.util.Set getORM_EntityLetturas() {
return ORM_entityLetturas;
}
public final vista_architetturale_gestoresmartfarm.entity2.EntityLetturaSetCollection entityLetturas = new vista_architetturale_gestoresmartfarm.entity2.EntityLetturaSetCollection(this, _ormAdapter, vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_ENTITYSERRA_ENTITYLETTURAS, vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_MUL_ONE_TO_MANY);
public String getNotifyInformationResponsabile() {
//TODO: Implement Method
String recapito = null;
Iterator<EntityEmployer> it = ORM_entityEmployers.iterator();
boolean trovato = false;
while(trovato == false && it.hasNext()){
EntityEmployer empTemp = it.next();
if(empTemp.getTipo().equals("responsabile")){
trovato = true;
recapito = empTemp.getRecapito();
}
}
return recapito;
}
public void salvaLettura() {
//TODO: Implement Method
throw new UnsupportedOperationException();
}
public void salvaLettura2() {
//TODO: Implement Method
throw new UnsupportedOperationException();
}
public void addIntrusione(java.util.Date data, String tipo, int[] img, java.util.Date ora) {
//TODO: Implement Method
EntityIntrusione intrusione = new EntityIntrusione (data, ora, tipo, img);
//DA TESTARE IMPORTANTISSIMO
ORM_entityIntrusiones.add(intrusione);
try {
//EntitySerraDAO.save(this);
EntityIntrusioneDAO.save(intrusione);
} catch (PersistentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*public synchronized void addIntrusione(java.util.Date data, String tipo, int[] img, java.util.Date ora){
//TODO: Implement Method
EntityIntrusione intrusione = new EntityIntrusione (data,ora,tipo,img);
//DA TESTARE IMPORTANTISSIMO
this.ORM_entityIntrusiones.add(intrusione);
this.entityIntrusiones.add(intrusione);
try {
Stream<EntityIntrusione> stream = this.ORM_entityIntrusiones.stream();
// salva l'ultimo elem
EntityIntrusioneDAO.save(stream.reduce((a, b) -> b).orElse(null));
} catch (PersistentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
public EntitySerra(vista_architetturale_gestoresmartfarm.entity2.EntitySerraDAO serra) {
//TODO: Implement Method
throw new UnsupportedOperationException();
}
public String[] getNotifyInformationEmployers() {
//TODO: Implement Method
throw new UnsupportedOperationException();
}
public vista_architetturale_gestoresmartfarm.entity2.EntitySensore getSensoreProssimita() {
EntitySensore sensProssimita = null;
Iterator<EntitySensore> it = ORM_entitySensores.iterator();
boolean trovato = false;
while(trovato == false && it.hasNext()){
EntitySensore sensTemp = it.next();
if(sensTemp.getTipo().equals("prossimita")){
trovato = true;
sensProssimita = sensTemp;
}
}
return sensProssimita;
}
public vista_architetturale_gestoresmartfarm.entity2.EntitySensore getSensoreFotografico() {
EntitySensore sensFotocamera = null;
Iterator<EntitySensore> it = ORM_entitySensores.iterator();
boolean trovato = false;
while(trovato == false && it.hasNext()){
EntitySensore sensTemp = it.next();
if(sensTemp.getTipo().equals("cam")){
trovato = true;
sensFotocamera = sensTemp;
}
}
return sensFotocamera;
}
public vista_architetturale_gestoresmartfarm.entity2.EntityEmployer getResponsabile() {
//TODO: Implement Method
EntityEmployer responsabile = null;
Iterator<EntityEmployer> it = ORM_entityEmployers.iterator();
boolean trovato = false;
while(trovato == false && it.hasNext()){
EntityEmployer empTemp = it.next();
if(empTemp.getTipo().equals("responsabile")){
trovato = true;
responsabile = empTemp;
}
}
return responsabile;
}
public String toString() {
return String.valueOf(getId());
}
}
ENTITYINTRUSIONEDAO:
public class EntityIntrusioneDAO {
public static boolean save(vista_architetturale_gestoresmartfarm.entity2.EntityIntrusione entityIntrusione) throws PersistentException {
try {
vista_architetturale_gestoresmartfarm.entity2.ProgettoPSSSAgosVersionPersistentManager.instance().saveObject(entityIntrusione);
return true;
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
}
PERSISTENT MANAGER:
public class ProgettoPSSSAgosVersionPersistentManager extends PersistentManager {
private static PersistentManager _instance = null;
private static SessionType _sessionType = SessionType.THREAD_BASE;
private static int _timeToAlive = 60000;
private static JDBCConnectionSetting _connectionSetting = null;
private static Properties _extraProperties = null;
private static String _configurationFile = null;
private ProgettoPSSSAgosVersionPersistentManager() throws PersistentException {
super(_connectionSetting, _sessionType, _timeToAlive, new String[] {}, _extraProperties, _configurationFile);
setFlushMode(FlushMode.AUTO);
}
public String getProjectName() {
return PROJECT_NAME;
}
public static synchronized final PersistentManager instance() throws PersistentException {
if (_instance == null) {
_instance = new ProgettoPSSSAgosVersionPersistentManager();
}
return _instance;
}
public void disposePersistentManager() throws PersistentException {
_instance = null;
super.disposePersistentManager();
}
public static void setSessionType(SessionType sessionType) throws PersistentException {
if (_instance != null) {
throw new PersistentException("Cannot set session type after create PersistentManager instance");
}
else {
_sessionType = sessionType;
}
}
public static void setAppBaseSessionTimeToAlive(int timeInMs) throws PersistentException {
if (_instance != null) {
throw new PersistentException("Cannot set session time to alive after create PersistentManager instance");
}
else {
_timeToAlive = timeInMs;
}
}
public static void setJDBCConnectionSetting(JDBCConnectionSetting aConnectionSetting) throws PersistentException {
if (_instance != null) {
throw new PersistentException("Cannot set connection setting after create PersistentManager instance");
}
else {
_connectionSetting = aConnectionSetting;
}
}
public static void setHibernateProperties(Properties aProperties) throws PersistentException {
if (_instance != null) {
throw new PersistentException("Cannot set hibernate properties after create PersistentManager instance");
}
else {
_extraProperties = aProperties;
}
}
public static void setConfigurationFile(String aConfigurationFile) throws PersistentException {
if (_instance != null) {
throw new PersistentException("Cannot set configuration file after create PersistentManager instance");
}
else {
_configurationFile = aConfigurationFile;
}
}
public static void saveJDBCConnectionSetting() {
PersistentManager.saveJDBCConnectionSetting(PROJECT_NAME, _connectionSetting);
}
}
The exception caught is:
org.orm.PersistentException: org.hibernate.PropertyValueException: not-null property references a null or transient value : vista_architetturale_gestoresmartfarm.entity2.EntityIntrusione._vista_architetturale_gestoresmartfarm.entity2.EntitySerra.ORM_EntityIntrusionesBackref
at org.orm.PersistentSession.saveOrUpdate(PersistentSession.java:598)
at org.orm.PersistentManager.saveObject(PersistentManager.java:326)
at vista_architetturale_gestoresmartfarm.entity2.EntityIntrusioneDAO.save(EntityIntrusioneDAO.java:304)
at vista_architetturale_gestoresmartfarm.entity2.EntitySerra.addIntrusione(EntitySerra.java:146)
at vista_architetturale_gestoresmartfarm.business_logic.ControllerRilevaIntrusioneBL.run(ControllerRilevaIntrusioneBL.java:139)
Caused by: org.hibernate.PropertyValueException: not-null property references a null or transient value : vista_architetturale_gestoresmartfarm.entity2.EntityIntrusione._vista_architetturale_gestoresmartfarm.entity2.EntitySerra.ORM_EntityIntrusionesBackref
at org.hibernate.engine.internal.Nullability.checkNullability(Nullability.java:89)
at org.hibernate.action.internal.AbstractEntityInsertAction.nullifyTransientReferencesIfNotAlready(AbstractEntityInsertAction.java:115)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:69)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:625)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:279)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:260)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:305)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:318)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:275)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:182)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:113)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:97)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:655)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:647)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:642)
at org.orm.PersistentSession.saveOrUpdate(PersistentSession.java:596)
... 4 more
org.orm.PersistentException: org.orm.PersistentException: org.hibernate.PropertyValueException: not-null property references a null or transient value : vista_architetturale_gestoresmartfarm.entity2.EntityIntrusione._vista_architetturale_gestoresmartfarm.entity2.EntitySerra.ORM_EntityIntrusionesBackref
at vista_architetturale_gestoresmartfarm.entity2.EntityIntrusioneDAO.save(EntityIntrusioneDAO.java:309)
at vista_architetturale_gestoresmartfarm.entity2.EntitySerra.addIntrusione(EntitySerra.java:146)
at vista_architetturale_gestoresmartfarm.business_logic.ControllerRilevaIntrusioneBL.run(ControllerRilevaIntrusioneBL.java:139)
Caused by: org.orm.PersistentException: org.hibernate.PropertyValueException: not-null property references a null or transient value : vista_architetturale_gestoresmartfarm.entity2.EntityIntrusione._vista_architetturale_gestoresmartfarm.entity2.EntitySerra.ORM_EntityIntrusionesBackref
at org.orm.PersistentSession.saveOrUpdate(PersistentSession.java:598)
at org.orm.PersistentManager.saveObject(PersistentManager.java:326)
at vista_architetturale_gestoresmartfarm.entity2.EntityIntrusioneDAO.save(EntityIntrusioneDAO.java:304)
... 2 more
Caused by: org.hibernate.PropertyValueException: not-null property references a null or transient value : vista_architetturale_gestoresmartfarm.entity2.EntityIntrusione._vista_architetturale_gestoresmartfarm.entity2.EntitySerra.ORM_EntityIntrusionesBackref
at org.hibernate.engine.internal.Nullability.checkNullability(Nullability.java:89)
at org.hibernate.action.internal.AbstractEntityInsertAction.nullifyTransientReferencesIfNotAlready(AbstractEntityInsertAction.java:115)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:69)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:625)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:279)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:260)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:305)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:318)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:275)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:182)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:113)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:97)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:655)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:647)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:642)
at org.orm.PersistentSession.saveOrUpdate(PersistentSession.java:596)
... 4 more
You can specify the Error Handling method when generating ORM code. May I know which option you selected?

How to catch a context within a class correctly?

I'm in a paser of a Webservice. With it, I picked up the dice and already gave Set In each of them (is working agreement). However, in time to insert the same in the database it displays the following error (null):
Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory, android.database.DatabaseErrorHandler)' on a null object reference
The db needs a Context, but I can not in class because there extends an Activity or otherwise to the use of getBaseContext, getAplication among others ..
*parser:
public class WSParserSetValoresBD {
private String text;
public BDProgramacaoGetterSetter programacaoGetterSetter;
boolean tabela = false;
int contadorLinhas = 0;
private Context ctx;
public WSParserSetValoresBD(Context contextP){
this.ctx=contextP; // I've checked here and not be null, it's all right
}
BDProgramacaoBancoDao inserir = new BDProgramacaoBancoDao(ctx);
public void parse(InputStream is) {
XmlPullParserFactory factory = null;
XmlPullParser parser = null;
try {
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
parser = factory.newPullParser();
parser.setInput(is, null);
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT ) {
String tagname = parser.getName();
switch (eventType) {
case XmlPullParser.START_TAG:
if(tagname.equalsIgnoreCase("Table")){
tabela = true;
programacaoGetterSetter = new BDProgramacaoGetterSetter();
contadorLinhas++;
}
else if (tagname.equalsIgnoreCase("DATA") || tagname.equalsIgnoreCase("ROTA") || tagname.equalsIgnoreCase("IWERK")
|| tagname.equalsIgnoreCase("AUFNR")|| tagname.equalsIgnoreCase("VORNR")|| tagname.equalsIgnoreCase("POINT")
|| tagname.equalsIgnoreCase("SEQUENCIA")|| tagname.equalsIgnoreCase("STATUS_PONTO")|| tagname.equalsIgnoreCase("FREQUENCIA")
|| tagname.equalsIgnoreCase("PSORT")|| tagname.equalsIgnoreCase("PTTXT")|| tagname.equalsIgnoreCase("EQUNR")
|| tagname.equalsIgnoreCase("EQKTX")|| tagname.equalsIgnoreCase("TPLNR")|| tagname.equalsIgnoreCase("PLTXT")
|| tagname.equalsIgnoreCase("SIST_LUBRIFIC")|| tagname.equalsIgnoreCase("REF_LUBRIFIC")|| tagname.equalsIgnoreCase("COD_LUBRIFIC")
|| tagname.equalsIgnoreCase("VOL_LUBRIFICCL")|| tagname.equalsIgnoreCase("QTD_CONSUMO")|| tagname.equalsIgnoreCase("DESCR_ROTA")
|| tagname.equalsIgnoreCase("ID_PROGRAMACAO")|| tagname.equalsIgnoreCase("GRUPO")|| tagname.equalsIgnoreCase("OBSERVACAO")
|| tagname.equalsIgnoreCase("ATIVI")|| tagname.equalsIgnoreCase("ARBPL")|| tagname.equalsIgnoreCase("ITEM_INSPEC")
|| tagname.equalsIgnoreCase("VOL_LUBRIFCKG")|| tagname.equalsIgnoreCase("NRO_BOMBADAS")|| tagname.equalsIgnoreCase("LIMITE_INF")
|| tagname.equalsIgnoreCase("LIMITE_SUP")|| tagname.equalsIgnoreCase("IDATE_ITIME")|| tagname.equalsIgnoreCase("VLR_MED")
|| tagname.equalsIgnoreCase("COD_VALOR")|| tagname.equalsIgnoreCase("TEXTO_OBS")|| tagname.equalsIgnoreCase("MATRIC")
|| tagname.equalsIgnoreCase("ATIVI")|| tagname.equalsIgnoreCase("STATUS_PROC")|| tagname.equalsIgnoreCase("MENSAGEM")
|| tagname.equalsIgnoreCase("COL_NUMERIC")){
}
break;
case XmlPullParser.TEXT:
text = parser.getText();
break;
case XmlPullParser.END_TAG:
if (tagname.equalsIgnoreCase("DATA")) {
programacaoGetterSetter.setData(text);
} else if(tagname.equalsIgnoreCase("ROTA")){
programacaoGetterSetter.setRota(text);
} else if (tagname.equalsIgnoreCase("IWERK")) {
programacaoGetterSetter.setIwerk(text);
} else if (tagname.equalsIgnoreCase("AUFNR")) {
programacaoGetterSetter.setAufnr(text);
} else if (tagname.equalsIgnoreCase("VORNR")) {
programacaoGetterSetter.setVornr(text);
} else if (tagname.equalsIgnoreCase("POINT")) {
programacaoGetterSetter.setPoint(text);
} else if (tagname.equalsIgnoreCase("SEQUENCIA")) {
programacaoGetterSetter.setSequencia(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("STATUS_PONTO")) {
programacaoGetterSetter.setStatus_proc(text);
} else if (tagname.equalsIgnoreCase("FREQUENCIA")) {
programacaoGetterSetter.setFrequencia(text);
} else if (tagname.equalsIgnoreCase("PSORT")) {
programacaoGetterSetter.setPsort(text);
} else if (tagname.equalsIgnoreCase("PTTXT")) {
programacaoGetterSetter.setPttxt(text);
} else if (tagname.equalsIgnoreCase("EQUNR")) {
programacaoGetterSetter.setEqunr(text);
} else if (tagname.equalsIgnoreCase("EQKTX")) {
programacaoGetterSetter.setEqktx(text);
} else if (tagname.equalsIgnoreCase("TPLNR")) {
programacaoGetterSetter.setTplnr(text);
} else if (tagname.equalsIgnoreCase("PLTXT")) {
programacaoGetterSetter.setPltxt(text);
} else if (tagname.equalsIgnoreCase("SIST_LUBRIFIC")) {
programacaoGetterSetter.setSist_lubrific(text);
} else if (tagname.equalsIgnoreCase("REF_LUBRIFIC")) {
programacaoGetterSetter.setRef_lubrific(text);
} else if (tagname.equalsIgnoreCase("COD_LUBRIFIC")) {
programacaoGetterSetter.setCod_lubrific(text);
} else if (tagname.equalsIgnoreCase("VOL_LUBRIFICCL")) {
programacaoGetterSetter.setVol_lubrificcl(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("QTD_CONSUMO")) {
programacaoGetterSetter.setQtd_consumo(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("DESCR_ROTA")) {
programacaoGetterSetter.setDescr_rota(text);
} else if (tagname.equalsIgnoreCase("ID_PROGRAMACAO")) {
programacaoGetterSetter.setId_programacao(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("GRUPO")) {
programacaoGetterSetter.setGrupo(text);
} else if (tagname.equalsIgnoreCase("OBSERVACAO")) {
programacaoGetterSetter.setObservacao(text);
} else if (tagname.equalsIgnoreCase("ATIVI")) {
programacaoGetterSetter.setAtivi(text);
} else if (tagname.equalsIgnoreCase("ARBPL")) {
programacaoGetterSetter.setArbpl(text);
} else if (tagname.equalsIgnoreCase("ITEM_INSPEC")) {
programacaoGetterSetter.setItem_inspec(text);
} else if (tagname.equalsIgnoreCase("VOL_LUBRIFCKG")) {
programacaoGetterSetter.setVol_lubrifickg(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("NRO_BOMBADAS")) {
programacaoGetterSetter.setNro_bombadas(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("LIMITE_INF")) {
programacaoGetterSetter.setLimite_inf(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("LIMITE_SUP")) {
programacaoGetterSetter.setlimite_sup(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("IDATE_ITIME")) {
programacaoGetterSetter.setIdate_itime(text);
} else if (tagname.equalsIgnoreCase("VLR_MED")) {
programacaoGetterSetter.setVlr_med(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("COD_VALOR")) {
programacaoGetterSetter.setCod_valor(text);
} else if (tagname.equalsIgnoreCase("TEXTO_OBS")) {
programacaoGetterSetter.setTexto_obs(text);
} else if (tagname.equalsIgnoreCase("MATRIC")) {
programacaoGetterSetter.setMatric(text);
} else if (tagname.equalsIgnoreCase("ATIVI")) {
programacaoGetterSetter.setAtivi(text);
} else if (tagname.equalsIgnoreCase("STATUS_PROC")) {
programacaoGetterSetter.setStatus_proc(text);
} else if (tagname.equalsIgnoreCase("MENSAGEM")) {
programacaoGetterSetter.setMensagem(text);
} else if (tagname.equalsIgnoreCase("COL_NUMERIC")) {
programacaoGetterSetter.setCol_numeric(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("Table")){
if (programacaoGetterSetter != null && inserir != null){
inserir.open(); // HERE IS THE ERROR; database_prog is null
inserir.inserirDados(programacaoGetterSetter);
}
}
break;
default:
break;
}
eventType = parser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
*database
public class BDProgramacaoBancoDao {
private SQLiteDatabase database_prog;
public void open () throws SQLDataException{
database_prog = sqliteOpenHelper_prog.getWritableDatabase();
}
private BDProgramacaoCustomSQLiteOpenHelper sqliteOpenHelper_prog;
public BDProgramacaoBancoDao(Context context) {
sqliteOpenHelper_prog = new BDProgramacaoCustomSQLiteOpenHelper(context);
}
public String insertDados(BDProgramacaoGetterSetter dadosProg) {
ContentValues valores = new ContentValues();
long resultado;
//valores.put(sqliteOpenHelper_prog.COLUMN_ID,dadosProg.getId()); ID eh auto increment
valores.put(sqliteOpenHelper_prog.COLUMN_ARBPL, dadosProg.getArbpl());
valores.put(sqliteOpenHelper_prog.COLUMN_ATIVI, dadosProg.getAtivi());
valores.put(sqliteOpenHelper_prog.COLUMN_AUFNR, dadosProg.getAufnr());
valores.put(sqliteOpenHelper_prog.COLUMN_COD_LUBRIFIC, dadosProg.getCod_lubrific());
valores.put(sqliteOpenHelper_prog.COLUMN_COD_VALOR, dadosProg.getCod_valor());
valores.put(sqliteOpenHelper_prog.COLUMN_DATA, dadosProg.getData()); // no banco esta como integer
valores.put(sqliteOpenHelper_prog.COLUMN_COL_NUMERIC, dadosProg.getCol_numeric());
valores.put(sqliteOpenHelper_prog.COLUMN_DESCR_ROTA, dadosProg.getDescr_rota());
valores.put(sqliteOpenHelper_prog.COLUMN_EQKTX, dadosProg.getEqktx());
valores.put(sqliteOpenHelper_prog.COLUMN_EQUNR, dadosProg.getEqunr());
valores.put(sqliteOpenHelper_prog.COLUMN_FREQUENCIA, dadosProg.getFrequencia());
valores.put(sqliteOpenHelper_prog.COLUMN_GRUPO, dadosProg.getGrupo());
valores.put(sqliteOpenHelper_prog.COLUMN_IDATE_ITIME, dadosProg.getIdate_itime());
valores.put(sqliteOpenHelper_prog.COLUMN_ITEM_INSPEC, dadosProg.getIdate_itime());
valores.put(sqliteOpenHelper_prog.COLUMN_IWERK, dadosProg.getIwerk());
valores.put(sqliteOpenHelper_prog.COLUMN_LIMITE_SUP, dadosProg.getlimite_sup());
valores.put(sqliteOpenHelper_prog.COLUMN_LIMITE_INF, dadosProg.getLimite_inf());
valores.put(sqliteOpenHelper_prog.COLUMN_MATRIC, dadosProg.getMatric());
valores.put(sqliteOpenHelper_prog.COLUMN_MENSAGEM, dadosProg.getMensagem());
valores.put(sqliteOpenHelper_prog.COLUMN_NRO_BOMBADAS, dadosProg.getNro_bombadas());
valores.put(sqliteOpenHelper_prog.COLUMN_OBSERVACAO, dadosProg.getObservacao());
valores.put(sqliteOpenHelper_prog.COLUMN_PLTXT, dadosProg.getPltxt());
valores.put(sqliteOpenHelper_prog.COLUMN_POINT, dadosProg.getPoint());
valores.put(sqliteOpenHelper_prog.COLUMN_PSORT, dadosProg.getPsort());
valores.put(sqliteOpenHelper_prog.COLUMN_PTTXT, dadosProg.getPttxt());
valores.put(sqliteOpenHelper_prog.COLUMN_QTD_CONSUMO, dadosProg.getQtd_consumo());
valores.put(sqliteOpenHelper_prog.COLUMN_TEXTO_OBS, dadosProg.getTexto_obs());
valores.put(sqliteOpenHelper_prog.COLUMN_TPLNR, dadosProg.getTplnr());
valores.put(sqliteOpenHelper_prog.COLUMN_VLR_MED, dadosProg.getVlr_med());
valores.put(sqliteOpenHelper_prog.COLUMN_VOL_LUBRIFCCL, dadosProg.getVol_lubrificcl());
valores.put(sqliteOpenHelper_prog.COLUMN_VOL_LUBRIFCKG, dadosProg.getVol_lubrifickg());
valores.put(sqliteOpenHelper_prog.COLUMN_VORNR, dadosProg.getVornr());
valores.put(sqliteOpenHelper_prog.COLUMN_REF_LUBRIFIC, dadosProg.getRef_lubrific());
valores.put(sqliteOpenHelper_prog.COLUMN_ROTA, dadosProg.getRota());
valores.put(sqliteOpenHelper_prog.COLUMN_SEQUENCIA, dadosProg.getSequencia());
valores.put(sqliteOpenHelper_prog.COLUMN_SIST_LUBRIFIC, dadosProg.getSist_lubrific());
valores.put(sqliteOpenHelper_prog.COLUMN_STATUS_PONTO, dadosProg.getStatus_ponto());
valores.put(sqliteOpenHelper_prog.COLUMN_STATUS_PROC, dadosProg.getStatus_proc());
valores.put(sqliteOpenHelper_prog.COLUMN_ID_PROGRAMACAO, dadosProg.getId_programacao());
resultado = database_prog.insert(BDProgramacaoCustomSQLiteOpenHelper.TABLE_PROGRAMACAO, null, valores);
database_prog.close();
if (resultado ==-1) return "Erro ao inserir registro";
else return "Registro Inserido com sucesso";
}
}
For some reason, the database_prog is null
*WSParserSetValoresBD in activity Opcoes_BaixarRotas (button "Yes" do AlertDialog):
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// nova query para o novo WS com as variaveis
final Runnable gravandoDados = new Runnable() {
public void run() {
getTodosDados(rota, atividade, responsavel, dataSelecionada);
if (WSResultadoTodosDados != null) {
InputStream isTodosDados = new ByteArrayInputStream(WSResultadoTodosDados.getBytes());
// call class
WSParserSetValoresBD parserTodosDados = new WSParserSetValoresBD(Opcoes_BaixarRotas.this.getApplicationContext());
parserTodosDados.parse(isTodosDados);
}
};
Thread queryTodosDados = new Thread(gravandoDados);
queryTodosDados.start();
}
Member variables are initialized before the constructor is invoked. Move the new BDProgramacaoBancoDao(ctx) initialization to your constructor where ctx is non-null.

How to bind data in java?

I will read the data from an xml file and list the properties of the elements in a page.
With my code you can already read the data and store them in a list. But unfortunately, data binding does not work. Please help ..
bookHandler
public class bookHandler implements ContentHandler {
private String currentValue;
boolean tablecaption;
private boolean bookObjectCreated = false;
private boolean inbookSection = false;
bookObject currentbookObject;
private boolean inbody = false;
private boolean namebook = false;
private boolean authbook = false;
private List<bookObject> booksList = null;
public List<bookObject> getbookList() {
return booksList;
}
public void characters(char[] ch, int start, int length) throws SAXException {
currentValue = new String(ch, start, length);
}
public void startElement(String uri, String localName, String qname, Attributes atts) throws SAXException {
if ((localName.equals("TABLE-PRE")) && (atts.getValue("ID").equals("action"))) {
inbookSection = true;
}
if (inbookSection) {
if (localName.equals("BODY")) {
inbody = true;
}
}
if (inbody) {
if (localName.equals("ROW")) {
bookObjectCreated = true;
currentbookObject = new bookObject();
if (booksList == null)
booksList = new ArrayList<bookObject>();
}
if (bookObjectCreated) {
if (localName.equals("ENTRY") && (atts.getValue("COLNAME").equals("col1"))) {
namebook = true;
} else if (localName.equals("ENTRY") && (atts.getValue("COLNAME").equals("col2"))) {
authbook = true;
}
}
}
}
public void endElement(String uri, String localName, String atts) throws SAXException {
if (bookObjectCreated) {
if (namebook) {
if (atts.equals("P")) {
currentbookObject.setName(currentValue);
namebook = false;
}
}
else if (authbook) {
if (atts.equals("P")) {
currentbookObject.setAuth(currentValue);
authbook = false;
}
}
if (atts.equals("ROW")) {
bookObjectCreated = false;
booksList.add(currentbookObject);
authbook = false;
}
}
if (atts.equals("BODY")) {
inbody = false;
inbookSection = false;
}
}
bookObject.java
public class bookObject {
private String name;
private String Auth;
public bookObject() {
}
public String getName() {
return name;
}
public String getAuth() {
return Auth;
}
public void setName(String name) {
this.name = name;
}
public void setAuth(String status) {
this.Auth = status;
}
}
Main.java
public class Main {
private String m_InputPath = "bspXml.xml";
public void createBooks() {
// m_ResultGroups = new ResultGroups();
try {
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
FileReader reader = new FileReader(m_InputPath);
InputSource inputSource = new InputSource(reader);
xmlReader.setContentHandler(new bookHandler());
xmlReader.parse(inputSource);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}
}
Wizard
public Wizard(App app) {
super("wizardPage");
//books
App.createBooks();
}
public void createControl(Composite parent) {
Composite container = new Composite(parent, SWT.NULL);
setControl(container);
container.setLayout(new BorderLayout(0, 0));
checkboxTableViewer = CheckboxTableViewer.newCheckList(container, SWT.BORDER | SWT.FULL_SELECTION);
checkboxTableViewer.setAllGrayed(true);
checkboxTableViewer.setAllChecked(false);
table = checkboxTableViewer.getTable();
table.setHeaderVisible(true);
table.setLayoutData(BorderLayout.CENTER);
tableViewerColumn = new TableViewerColumn(checkboxTableViewer, SWT.NONE);
tblclmnName = tableViewerColumn.getColumn();
tblclmnName.setWidth(255);
tblclmnName.setText("Name");
tableViewerColumn_1 = new TableViewerColumn(checkboxTableViewer, SWT.NONE);
tblclmnVariant = tableViewerColumn_1.getColumn();
tblclmnVariant.setWidth(122);
tblclmnVariant.setText("Author");
m_bindingContext = iDataBindings();
}
protected DataBindingContext iDataBindings() {
DataBindingContext bindingContext = new DataBindingContext();
//
IObservableValue observeTextTblclmnNameObserveWidget = WidgetProperties.text().observe(tblclmnName);
IObservableValue namebookObjectObserveValue = PojoProperties.value("name").observe(bookObject);
bindingContext.bindValue(observeTextTblclmnNameObserveWidget, namebookObjectObserveValue, null, null);
//
IObservableValue observeTextTblclmnVariantObserveWidget = WidgetProperties.text().observe(tblclmnVariant);
IObservableValue statusbookObjectObserveValue = PojoProperties.value("author").observe(bookObject);
bindingContext.bindValue(observeTextTblclmnVariantObserveWidget, statusbookObjectObserveValue, null, null);
//
return bindingContext;
}
}
xml
<?xml version="1.0" encoding="iso-8859-1" ?>
<BOOK>
<TABLE>
<TABLE-PRE ID="sinceBook">
<NAME>sinceBook</NAME>
</TABLE-PRE>
</TABLE>
<TABLE>
<TABLE-PRE ID="actionBook">
<NAME>actionBook</NAME>
</TABLE-PRE>
<TABLEGR COLS="2">
<COLSPE COLNUM="1" COLWIDTH="4.31*" COLNAME="col1"/>
<COLSPE COLNUM="2" COLWIDTH="1.00*" COLNAME="col2"/>
<TD>
<ROW>
<ENTRY COLNAME="col1">
<P>Name</P>
</ENTRY>
<ENTRY COLNAME="col2">
<P>Author</P>
</ENTRY>
</ROW>
</TD>
<BODY>
<ROW>
<ENTRY COLNAME="col1">
<P>Harry Potter </P>
</ENTRY>
<ENTRY COLNAME="col2">
<P>Joanne K. Rowling</P>
Even without reading your code carefully I would like to mention that you are working too hard to achieve what you need. Use JAXB to map XML schema to java class. Learn the basics during 15 minutes, put appropriate annotations on your model classes, write 3-4 lines of code and you are done.
EDIT
Take a look on this tutorial first: http://www.vogella.com/tutorials/JAXB/article.html
Or alternatively search for any other JAXB tutorial on web.

XML SAXParser reformat if else Java/Android

I have the following problem:
I am using an XML SAXParser to parse an xml file and create dynamicly classes and set their properties.
I have written code that works now to make 4 classes and set the properiets of the classes but the problem is that the code is one big conditional case (if/else if/else) and that it is very difficult to read.
I would like to parse the xml so I can create 15 different classes, so the code is getting very big.
Now the exact question is how to refactor the if/elseif/else to better readable code? I've searched around for a while now and found some methods like using a map or the command pattern but I don't understand how to use this?
This is the code I'm currently using and that is working:
public class XmlParserSax extends DefaultHandler {
List<Fragment> fragments = null;
String atType = null;
String typeObject;
String currentelement = null;
String atColor = null;
RouteFragment route = null;
ChapterFragment chapter = null;
FirstFragment first = null;
ExecuteFragment execute = null;
StringBuilder textBuilder;
public XmlParserSax() {
fragments = new ArrayList<Fragment>();
try {
/**
* Create a new instance of the SAX parser
**/
SAXParserFactory saxPF = SAXParserFactory.newInstance();
SAXParser sp = saxPF.newSAXParser();
XMLReader xr = sp.getXMLReader();
/**
* Create the Handler to handle each of the XML tags.
**/
String file = "assets/test.xml";
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream(file);
xr.setContentHandler(this);
xr.parse(new InputSource(in));
} catch (Exception e) {
System.out.println(e);
}
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
atColor = attributes.getValue("color");
atType = attributes.getValue("type");
currentelement = localName;
textBuilder = new StringBuilder();
if (localName.equalsIgnoreCase("template")) {
if (atType.equalsIgnoreCase("route")) {
route = new RouteFragment();
typeObject = "route";
} else if (atType.equalsIgnoreCase("chapter")) {
chapter = new ChapterFragment();
typeObject = "chapter";
} else if (atType.equalsIgnoreCase("first")) {
first = new FirstFragment();
typeObject = "first";
} else if (atType.equalsIgnoreCase("execute")) {
execute = new ExecuteFragment();
typeObject = "execute";
}
} else if (localName.equalsIgnoreCase("number")) {
if (typeObject.equalsIgnoreCase("chapter")) {
chapter.setNumberTextcolor("#" + atColor);
}
} else if (localName.equalsIgnoreCase("maxnumber")) {
if (typeObject.equalsIgnoreCase("chapter")) {
chapter.setMaxNumberColor("#" + atColor);
}
} else if (localName.equalsIgnoreCase("title")) {
if (typeObject.equalsIgnoreCase("chapter")) {
chapter.setTitleColor("#" + atColor);
} else if (typeObject.equalsIgnoreCase("first")) {
first.setTitleColor("#" + atColor);
}
} else if (localName.equalsIgnoreCase("subtitle")) {
if (typeObject.equalsIgnoreCase("first")) {
first.setSubtitleColor("#" + atColor);
}
} else if (localName.equalsIgnoreCase("text")) {
if (typeObject.equalsIgnoreCase("execute")) {
execute.setTextColor("#" + atColor);
}
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
String text = textBuilder.toString();
if (localName.equalsIgnoreCase("template")) {
if (typeObject.equalsIgnoreCase("route")) {
fragments.add(route); // nieuw routefragment
// toevoegen aan de lijst
} else if (typeObject.equalsIgnoreCase("chapter")) {
fragments.add(chapter); // nieuw chapterfragment
// toevoegen aan de lijst
} else if (typeObject.equalsIgnoreCase("first")) {
fragments.add(first);
} else if (typeObject.equalsIgnoreCase("execute")) {
fragments.add(execute);
}
} else if (localName.equalsIgnoreCase("text")) {
if (typeObject.equalsIgnoreCase("route")) {
// route.setOmschrijving(text);
} else if (typeObject.equalsIgnoreCase("execute")) {
execute.setText(text);
}
} else if (localName.equalsIgnoreCase("background")) {
if (typeObject.equalsIgnoreCase("route")) {
// route.setKleur("#" + text);
} else if (typeObject.equalsIgnoreCase("chapter")) {
chapter.setBackgroundColor("#" + text);
} else if (typeObject.equalsIgnoreCase("first")) {
first.setBackgroundColor("#" + text);
} else if (typeObject.equalsIgnoreCase("execute")) {
execute.setBackgroundColor("#" + text);
}
} else if (localName.equalsIgnoreCase("number")) {
if (typeObject.equalsIgnoreCase("chapter")) {
chapter.setNumber(text);
}
} else if (localName.equalsIgnoreCase("maxnumber")) {
if (typeObject.equalsIgnoreCase("chapter")) {
chapter.setMaxNumber(text);
}
} else if (localName.equalsIgnoreCase("title")) {
if (typeObject.equalsIgnoreCase("chapter")) {
chapter.setTitle(text);
} else if (typeObject.equalsIgnoreCase("first")) {
first.setTitle(text);
}
} else if (localName.equalsIgnoreCase("subtitle")) {
if (typeObject.equalsIgnoreCase("first")) {
first.setSubtitle(text);
}
} else if (localName.equalsIgnoreCase("square")) {
if (typeObject.equalsIgnoreCase("execute")) {
execute.setBorderColor("#" + text);
}
}
}
public List<Fragment> getList() {
return fragments;
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
textBuilder.append(ch, start, length);
}
}
There is another way of doing this; using startElementListener and EndTextElementListeners
First define your root element:
RootElement root = new RootElement("root");
Define your child elements
Element nodeA = root.getChild("nodeA");
Element nodeB = root.getChild("nodeB");
Element nodeC = root.getChild("nodeC");
Now set the listeners
root.setStartElementListener(new StartElementListener() {
public void start(Attributes attributes) {
foundElement = true;// tells you that you are parsing the intended xml
}
});
nodeA.setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
//populate your pojo
}
});
This way you can do away with all those if-else statements and booleans, but you have to live with the N number of listeners.

Java Android : XML Parsing getting the value of a tag

I'm trying to parse an xml file but seem not to understand how it works. I have been debugging for hours but cant seem to get the correct value. I have managed to get the code working for the tracklist tag, but not for the playbacklist tag and his children tags.
I'm would like to have the values of a playback device, in the future more will be added.
this is the xml source:
<?xml version="1.0" encoding="ISO-8859-1"?>
<root>
<tracklist>
<track>track001.mp3</track>
<track>track002.mp3</track>
<track>track003.mp3</track>
<track>track004.mp3</track>
<track>track005.mp3</track>
<track>track006.mp3</track>
<track>track007.mp3</track>
<track>track008.mp3</track>
<track>track009.mp3</track>
<track>track010.mp3</track>
</tracklist>
<playbacklist>
<playback>
<name>Speaker1</name>
<ip>192.168.1.103</ip>
<room>Kitchen</room>
<options>0</options>
<state>NotPlaying</state>
</playback>
</playbacklist>
</root>
this is the java code (snippets of the code): this code is working for me
DocumentBuilder db = factory.newDocumentBuilder();
Document doc = db.parse(inStream);
NodeList nodeList = doc.getElementsByTagName("root");
for (int index = 0; index < nodeList.getLength(); index++) {
Node node = nodeList.item(index);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
NodeList nameNode = element.getChildNodes();
for (int iIndex = 0; iIndex < nameNode.getLength(); iIndex++) {
if (nameNode.item(iIndex).getNodeType() == Node.ELEMENT_NODE) {
Element nameElement = (Element) nameNode.item(iIndex);
if(nameElement.getNodeName().equals("tracklist")){
NodeList trackNodes = nameElement.getChildNodes();
for(int i=0;i<trackNodes.getLength();i++){
if (trackNodes.item(i).getNodeType() == Node.ELEMENT_NODE) {
Element trackElement = (Element) trackNodes.item(i);
playlist.add(trackElement.getFirstChild().getNodeValue());
}
}
}
this code isn't working for me:
if(nameElement.getNodeName().equals("playbacklist")){
NodeList devicesNodes = nameElement.getChildNodes();
for(int j=0;j<=devicesNodes.getLength();j++){
Node nodeDevice = devicesNodes.item(j);
NodeList childNodes = nodeDevice.getChildNodes();
I will suggest you to use SAX parser, it is easy and much efficient than others
how to parse : How to parse XML using the SAX parser
Here is your SaxParser generated by my Sax Class Generator
package sherif.java.sax;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class YourHandler extends DefaultHandler
{
//TAGS /\Sherif/\
private boolean root = false;
private boolean playbacklist = false;
private boolean playback = false;
private boolean name = false;
private boolean ip = false;
private boolean room = false;
private boolean options = false;
private boolean state = false;
private boolean tracklist = false;
private boolean track = false;
public YourHandler()
{
//TODO /\Sherif/\
}
#Override
public void startDocument() throws SAXException
{
super.startDocument();
//TODO /\Sherif/\
}
#Override
public void endDocument() throws SAXException
{
super.endDocument();
//TODO /\Sherif/\
}
#Override
public void characters(char sherifCh[], int sherifSt, int sherifle)
{
String value = (new String(sherifCh)).substring(sherifSt, sherifSt + sherifle);
if(root)
{
if(playbacklist)
{
if(playback)
{
if(name)
{
//TODO /\Sherif/\
}
else if(ip)
{
//TODO /\Sherif/\
}
else if(room)
{
//TODO /\Sherif/\
}
else if(options)
{
//TODO /\Sherif/\
}
else if(state)
{
//TODO /\Sherif/\
}
}
}
else if(tracklist)
{
if(track)
{
//TODO /\Sherif/\
}
}
}
}
#Override
public void startElement(String sherifUr, String sherifNa, String sherifQn, org.xml.sax.Attributes sherifAt) throws SAXException
{
super.startElement(sherifUr, sherifNa, sherifQn, sherifAt);
if(sherifNa.equals("root"))
{
this.root = true;
}
else if(sherifNa.equals("playbacklist"))
{
this.playbacklist = true;
}
else if(sherifNa.equals("playback"))
{
this.playback = true;
}
else if(sherifNa.equals("name"))
{
this.name = true;
}
else if(sherifNa.equals("ip"))
{
this.ip = true;
}
else if(sherifNa.equals("room"))
{
this.room = true;
}
else if(sherifNa.equals("options"))
{
this.options = true;
}
else if(sherifNa.equals("state"))
{
this.state = true;
}
else if(sherifNa.equals("tracklist"))
{
this.tracklist = true;
}
else if(sherifNa.equals("track"))
{
this.track = true;
}
}
#Override
public void endElement(String sherifUr, String sherifNa, String sherifQn) throws SAXException
{
super.endElement(sherifUr, sherifNa, sherifQn);
if(sherifNa.equals("root"))
{
this.root = false;
}
else if(sherifNa.equals("playbacklist"))
{
this.playbacklist = false;
}
else if(sherifNa.equals("playback"))
{
this.playback = false;
}
else if(sherifNa.equals("name"))
{
this.name = false;
}
else if(sherifNa.equals("ip"))
{
this.ip = false;
}
else if(sherifNa.equals("room"))
{
this.room = false;
}
else if(sherifNa.equals("options"))
{
this.options = false;
}
else if(sherifNa.equals("state"))
{
this.state = false;
}
else if(sherifNa.equals("tracklist"))
{
this.tracklist = false;
}
else if(sherifNa.equals("track"))
{
this.track = false;
}
}
}
You can use it:
String yourXmlString;
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/* Create a new instance of the class generated */
YourHandler handler = new YourHandler ();
xr.setContentHandler(handler);
InputSource inputSource = new InputSource();
inputSource.setEncoding("UTF-8");
inputSource.setCharacterStream(new StringReader(response));
/* Start Parsing */
xr.parse(inputSource);
/* Parsing Done. */

Categories

Resources