Struts 2 pagination,query syntax error - java

I have an error while I am getting data from database.It looks like everything is fine but i get this error?Why?
Full Error
(org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: 0 near line 1, column 47 [from com.project.Data limit 0,10] (Encoded))
DataAction.java
/**
* To list Data
*
* #return String
*/
public String listThrowException() {
try{
//Getting Total records count from database...
pagination.setPreperties(facade.getDataCount());
//Getting data list from database
listData = facade.listData(pagination);
//Setting number of records in the particular page
pagination.setPage_records(listData.size());
logger.info(Logger.EVENT_SUCCESS,
"successfully viewed data list!");
}catch (Exception e) {
logger.error(
Logger.EVENT_FAILURE,
"could not view data list, error: *"
+ e.getMessage() + "*");
}
return "success";
}
DataService.java
#Override
public List<Data> listData(Pagination pagination){
List<Data> list=new ArrayList<Data>();
Query query;
try {
String excQuery = "from Data limit ";
excQuery = pagination.getSQLQuery(excQuery);
query = em.createQuery(excQuery);
list = query.getResultList();
} catch (Exception e) {
logger.error(Logger.EVENT_FAILURE, e.getMessage());
return null;
}
return list;
}
Pagination.java
public class Pagination {
private long page_size = 0;
private int page_number = 0;
private long total_records = 0;
private int page_records = 0;
private long start = 0;
private long end = 0;
private int total_pages = 0;
public void setPreperties(long l){
total_records = l;
total_pages = (int) Math.ceil(((double)l / (double)page_size));
start = ((page_size * page_number) - page_size);
end = page_size*page_number;
if(page_size==0){
start = 0;
end = l;
total_pages = 1;
}
}
public Pagination(int page_size, int page_number) {
this.page_number = page_number;
this.page_size = page_size;
}
public String getSQLQuery(String query) {
query += getStart() + "," + getEnd();
return query;
}
///get and set methods
}
My problem is that "limit" in Hql it is not supported.I use setFirstResults() setMaxResults() and it works.My question is a good example for implementing paginaton in your page. I refer this tutorial http://prathap-puppala.blogspot.com/2011/06/struts-2-pagination-example.html I change only DateService.java** Good Luck!
DateService.java
#Override
public List<Data> listData(Pagination pagination){
List<Data> list=new ArrayList<Data>();
Query query;
try {
String excQuery = "from Data ";
query = em.createQuery(excQuery).
setFirstResult(pagination.getStart()).setMaxResults(pagination.getEnd());
query = em.createQuery(excQuery);
list = query.getResultList();
} catch (Exception e) {
logger.error(Logger.EVENT_FAILURE, e.getMessage());
return null;
}
return list;
}

Related

unable to refresh a jtable more than one time

In my jFrame,I created a table that contains the patients' list and a button that allows to refresh the table on action. When I click the refresh button for the firt time, the list is displayed in the table. Howerver, when I press it for a second time it doesn't work any more and the table isn't able to be refreshed.
Any idea about the problem please?
this is the code of the refresh button:
public class Interface extends javax.swing.JFrame{
private void RefreshActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel)worklisttable.getModel();
int rowCount = model.getRowCount();
for (int i = rowCount - 1; i >= 0; i--) {
model.removeRow(i);
}
model.fireTableDataChanged();
GetMwl_3.main(args);
}
public static void main(String args[]) {
......
}
}
GetMwl_3.java : allows to retrieve the patient list from the server
public class GetMwl_3 {
private String[] args;
/**
* #param args
*/
public static void main(String[] args/*,String aet, String host, Integer port*/) {
new GetMwl_3(/*aet,host,port*/);
}
private static final int[] RETURN_KEYS = {
Tag.AccessionNumber,
Tag.ReferringPhysicianName,
Tag.PatientName,
Tag.PatientID,
Tag.PatientBirthDate,
Tag.PatientSex,
Tag.PatientWeight,
Tag.MedicalAlerts,
Tag.Allergies,
Tag.PregnancyStatus,
Tag.StudyInstanceUID,
Tag.RequestingPhysician,
Tag.RequestingService,
Tag.RequestedProcedureDescription,
Tag.AdmissionID,
Tag.SpecialNeeds,
Tag.CurrentPatientLocation,
Tag.PatientState,
Tag.RequestedProcedureID,
Tag.RequestedProcedurePriority,
Tag.PatientTransportArrangements,
Tag.PlacerOrderNumberImagingServiceRequest,
Tag.FillerOrderNumberImagingServiceRequest,
Tag.ConfidentialityConstraintOnPatientDataDescription,
};
private static final int[] SPS_RETURN_KEYS = {
Tag.Modality,
Tag.RequestedContrastAgent,
Tag.ScheduledStationAETitle,
Tag.ScheduledProcedureStepStartDate,
Tag.ScheduledProcedureStepStartTime,
Tag.ScheduledPerformingPhysicianName,
Tag.ScheduledProcedureStepDescription,
Tag.ScheduledProcedureStepID,
Tag.ScheduledStationName,
Tag.ScheduledProcedureStepLocation,
Tag.PreMedication,
Tag.ScheduledProcedureStepStatus
};
private static final String[] LE_TS = {
UID.ExplicitVRLittleEndian,
UID.ImplicitVRLittleEndian };
private static final byte[] EXT_NEG_INFO_FUZZY_MATCHING = { 1, 1, 1 };
private Device device;
private final NetworkApplicationEntity remoteAE = new NetworkApplicationEntity();
private final NetworkConnection remoteConn = new NetworkConnection();
private final NetworkApplicationEntity ae = new NetworkApplicationEntity();
private final NetworkConnection conn = new NetworkConnection();
private final DicomObject keys = new BasicDicomObject();
private final DicomObject spsKeys = new BasicDicomObject();
private Association assoc;
private int priority = 0;
private int cancelAfter = Integer.MAX_VALUE;//ÐœÐ°ÐºÑ ÐºÐ¾Ð»Ð¸Ñ‡ÐµÑтво Ñтрок
private boolean fuzzySemanticPersonNameMatching;
private Component emptyLabel;
public GetMwl_3(/*String aet, String host, Integer port*/) {
String name = "DCMMWL";
device = new Device(name);
NewThreadExecutor executor = new NewThreadExecutor(name);
remoteAE.setInstalled(true);
remoteAE.setAssociationAcceptor(true);
remoteAE.setNetworkConnection(new NetworkConnection[] { remoteConn });
device.setNetworkApplicationEntity(ae);
device.setNetworkConnection(conn);
ae.setNetworkConnection(conn);
ae.setAssociationInitiator(true);
ae.setAETitle(name);
for (int i = 0; i < RETURN_KEYS.length; i++) {
keys.putNull(RETURN_KEYS[i], null);
}
keys.putNestedDicomObject(Tag.RequestedProcedureCodeSequence,
new BasicDicomObject());
keys.putNestedDicomObject(Tag.ScheduledProcedureStepSequence, spsKeys);
for (int i = 0; i < SPS_RETURN_KEYS.length; i++) {
spsKeys.putNull(SPS_RETURN_KEYS[i], null);
}
spsKeys.putNestedDicomObject(Tag.ScheduledProtocolCodeSequence,
new BasicDicomObject());
/////////
Properties pacs = new Properties();
InputStream file = null;
File thefile = new File("C:\\properties\\save.properties");
if (thefile.exists()){
try {
file = new FileInputStream("C:\\properties\\save.properties");
// load a properties file
pacs.load(file);
// get the property value and print it out
remoteAE.setAETitle( pacs.getProperty("aethl7"));
remoteConn.setHostname(pacs.getProperty("hosthl7"));
remoteConn.setPort(Integer.parseInt(pacs.getProperty("porthl7")));
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
addSpsMatchingKey(Tag.ScheduledProcedureStepStartDate,"20131030");
setTransferSyntax(LE_TS);
long t1 = System.currentTimeMillis();
try {
assoc = ae.connect(remoteAE, executor);
} catch (Exception e) {
// System.err.println("ERROR: Failed to establish association:");
//e.printStackTrace(System.err);
//jLabel7.setText("ERROR: Failed to establish association");
javax.swing.JOptionPane.showMessageDialog(null,"Liste des patients ne peut pas être retirée");
//System.exit(2);
}
long t2 = System.currentTimeMillis();
System.out.println("Connected to " + remoteAE + " in "
+ ((t2 - t1) / 1000F) + "s");
//jLabel6.setText("Connected to " + remoteAE + " in "
// + ((t2 - t1) / 1000F) + "s");
try {
List<DicomObject> result = query();
long t3 = System.currentTimeMillis();
System.out.println("Received " + result.size()
+ " matching entries in " + ((t3 - t2) / 1000F) + "s");
for(DicomObject dcm : result) {
worklist.main(args,
dcm.getString(Tag.PatientID),
dcm.getString(Tag.AccessionNumber),
dcm.getString(Tag.PatientName),
dcm.getString(Tag.PatientBirthDate),
dcm.getString(Tag.PatientSex),
dcm.getString(Tag.ReferringPhysicianName)
);
}
javax.swing.JOptionPane.showMessageDialog(null,"Liste des patients retirée avec succée");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
assoc.release(true);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Released connection to " + remoteAE);
}
}
public void setTransferSyntax(String[] ts) {
TransferCapability tc = new TransferCapability(
UID.ModalityWorklistInformationModelFIND, ts,
TransferCapability.SCU);
if (fuzzySemanticPersonNameMatching)
tc.setExtInfo(EXT_NEG_INFO_FUZZY_MATCHING);
ae.setTransferCapability(new TransferCapability[]{tc});
}
public void addSpsMatchingKey(int tag, String value) {
spsKeys.putString(tag, null, value);
}
public List<DicomObject> query() throws IOException, InterruptedException {
TransferCapability tc = assoc.getTransferCapabilityAsSCU(
UID.ModalityWorklistInformationModelFIND);
if (tc == null) {
throw new NoPresentationContextException(
"Modality Worklist not supported by "
+ remoteAE.getAETitle());
}
DimseRSP rsp = assoc.cfind(UID.ModalityWorklistInformationModelFIND,
priority, keys, tc.getTransferSyntax()[0], cancelAfter);
List<DicomObject> result = new ArrayList<DicomObject>();
while (rsp.next()) {
DicomObject cmd = rsp.getCommand();
if (CommandUtils.isPending(cmd)) {
DicomObject data = rsp.getDataset();
result.add(data);
}
}
return result;
}
}
worklist.java :
public class worklist extends Interface{
public worklist(){
}
public static void main(String[] args,
String PatientID,
String accessingNumber,
String PatientName,
String BirthDate,
String sex,
String referringPhysician
) {
DefaultTableModel modelw=(DefaultTableModel)worklisttable.getModel();
modelw.setColumnIdentifiers(new String[]{"ID Patient"," Nom Patient","Date de Naissance","Sexe"});
DefaultTableCellRenderer centerRenderer= new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(JLabel.CENTER);
worklisttable.getColumnModel().getColumn(0).setCellRenderer(centerRenderer);
for (int j = 0 ; j< worklisttable.getColumnCount(); j++)
{
worklisttable.getColumnModel().getColumn(j).setCellRenderer(centerRenderer);
}
row=new Object[4];
row[0]=PatientID;
row[1]=PatientName;
row[2]=BirthDate;
row[3]=sex;
modelw.addRow(row);
}
}

Insert record to database from a server/client GUI java

Hi i am struggling to get my database to receive a username and ip address from a client instance connecting to a server.
It is a bidding system that initially just lets multiple individual instances of the client bid on 2 items, now I need to add the name (user prompted to enter upon loading client instance) and their ip address to my database.
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null; //null pointer exception fix
Statement statement = null;
String inserSql = null;
Connection sqlLink = null;
final int PORT = 1239;
Socket client = null;
ClientHandler handler = null;
Scanner getTime;
try {
/**
* This piece of code has errors or you maybe did the error
* when copy/paste your code.
* Fixed the DriverManager connection code
*/
sqlLink = DriverManager.getConnection(
"correct info already here);
} catch (SQLException e) {
System.out.println("* Cannot connect to database! *");
System.exit(1);
}
try {
serverSocket = new ServerSocket(PORT);
} catch (IOException ioEx) {
System.out.println("Unable to set up port!");
System.exit(1);
}
System.out.println("\nUp and running\n");
String currentTime = null;
getTime = new Scanner(System.in);
System.out.println("\nSet time for Ball");
currentTime = getTime.nextLine();
Items BallItem = new Items("Ball", currentTime, "Ball");
System.out.println("\nSet time for Plate");
currentTime = getTime.nextLine();
Items PlateItem = new Items("Plate", currentTime, "Plate");
Bidder bidder = new Bidder(null);
BallItem.start();
PlateItem.start();
Users user = new Users(BallItem, PlateItem);
ArrayList<ClientHandler> userList =
new ArrayList<ClientHandler>();
//add new array for the clients details as stated
ArrayList<String> bidders = new ArrayList<String>();
do {
client = serverSocket.accept();//
System.out.println("Enter username ");//
//takes in bidders name (1.1 and 2.1)
bidders.add(getTime.nextLine());
bidders.add(client.getInetAddress().toString());
//takes in next bidder's ip address to string like in tips (2.2)
Bidder userBidding = new Bidder(bidders);
System.out.println("\nUser" + (user.getUsers() + 1));
user.addUsers(userList, client, handler);
System.out.println(userBidding.returnUsers());
bidder.insert(statement, statement);
}
while (true);
}
}
class Items extends Thread {
private String name, description, timeUp, userBidding = "";
private boolean newBid = true;
private double topBid = 0;
private Calendar start = Calendar.getInstance();
private int date = start.get(Calendar.DATE); //gets the dates
private int month = start.get(Calendar.MONTH);
private int year = start.get(Calendar.YEAR);
private Calendar deadline = Calendar.getInstance();
//time file supplied to help etc
private Calendar now = Calendar.getInstance();
public Items(String newName, String newTimeString,
String newDescription) throws IOException {
String timeString, hourString, minString;
name = newName;
description = newDescription;
timeUp = newTimeString;
timeString = newTimeString;
hourString = timeString.substring(0, 2);
int hour = Integer.parseInt(hourString);
minString = timeString.substring(3, 5);
int minute = Integer.parseInt(minString);
deadline.set(year, month, date, hour, minute, 0); //setting time
}
public void run() {
while (now.before(deadline)) {
System.out.println(name + " " + getDateTime(now));
try {
Thread.sleep(5000); //increased to check server notifications easier
} catch (InterruptedException intEx) {
}
now = Calendar.getInstance();
}
System.out.println("\nDeadline! Times up!");
newBid = false;
}
class Bidder {
private static ArrayList<String> users;
private static Users user = new Users(null, null);
public Bidder(ArrayList<String> newUserList) {
users = newUserList;
}
public ArrayList<String> returnUsers()//return users as in question
{
return users;
}
public static String returnIP()//return ip as in question
{
return users.get(user.getUsers() + 1);
}
static void insert(Statement insert, Statement statement) {
Users user = new Users(null, null);
try {
String insertSql = "INSERT INTO Usernames(id, Name, ipAddress) VALUES (1"
+ users.get(user.getUsers()) + "," + returnIP() + ")";
System.out.println(users.get(user.getUsers()));
statement.executeUpdate(insertSql);
} catch (SQLException sqlEx) {
System.out.println("* Cannot execute insert! *");
sqlEx.printStackTrace();
System.exit(1);
}
}
//remove user as stated in question
public synchronized void RemoveUser(Socket client, int clientUser) {
int index = 0;
for (final String newString : users) {
if (users.indexOf(user.getUsers()) == clientUser) {
try {
client.close();
Thread.currentThread().isInterrupted();
users.remove(index);
} catch (final IOException e) {
System.out.println("Try to leave again!");
System.exit(1);
}
}
index++;
}
}
}
class Users {
private ArrayList<ClientHandler> userList;
private Items Ball;
private Items Plate;
public Users(Items newItem1, Items newItem2) {
Ball = newItem1;
Plate = newItem2;
userList = null;
}
public synchronized int getUsers() {
int totalUsers = 0;
if (userList != null)
for (ClientHandler handler : userList)
totalUsers++;
return totalUsers;
}
}// <-- miss this close brace

paging in Java for a lookup

I am trying to implement paging in an already running application, it works like mongodb where you get a query with bunch of parameters like
searchConditions ,limit( how many docs you want), skip ( skip these many docs)
and so on
and the response is back in json my task is to generate the previous and next link to the query that means previous page and the next page as per query
I came up with a method below
public Paging generateLink(RequestFilter filter) {
int prev_skip;
int prev_limit;
String pagePrev = "";
String pageNext = "";
int next_skip;
int next_limit;
String searchCondition = JsonUtils.toSimpleJsonString(filter.getSearch());
String url = "http://isgswmdi1n1.nam.nsroot.net:7014/account-search/rest/api/v1/pmm";
//properties.getProperty("paging.link");
System.out.println(url);
Paging pagingOption = new Paging();
Result result = new Result();
int count = luceneSearchService.searchCount(filter);
try {
if (count > 1) {
if (filter.getSkip() > 0) {
prev_skip = Math.max((filter.getSkip() - 1), 0);
prev_limit = filter.getLimit();
pagePrev = url + "?search=" + searchCondition + "&skip=" + prev_skip + "$limit=" + prev_limit;
} else{
result.setPaging(null);
return null;
}
if (count > (filter.getLimit() + filter.getSkip())) {
next_skip = (filter.getSkip() + filter.getLimit());
next_limit = filter.getLimit();
pageNext = url + "?search=" + searchCondition + "&skip=" + next_skip + "$limit=" + next_limit;
} else{
result.setPaging(null);
return null;
}
pagingOption.setPagePrev(pagePrev);
pagingOption.setPageNext(pageNext);
result.setPaging(pagingOption);
}
return pagingOption;
} catch (NullPointerException n)
{
n.printStackTrace();
return pagingOption;
}
}
call to generateLink method
return Result.ok(resultRow, generateLink(filter));
the ok response method in the Result class
public static Result ok(List<ResultRow> resultRows, Paging paging) {
if (paging != null) {
return new Result(resultRows, 200, "Completed", paging);
} else
return new Result(resultRows, 200, "Completed");
}
Underlying paging class
public class Paging implements Serializable {
public String getPagePrev() {
return pagePrev;
}
public void setPagePrev(String pagePrev) {
this.pagePrev = pagePrev;
}
#JsonProperty("pagePrev")
private String pagePrev;
public String getPageNext() {
return pageNext;
}
public void setPageNext(String pageNext) {
this.pageNext = pageNext;
}
#JsonProperty("pageNext")
private String pageNext;
}
but my test method is failing
#Test
public void search_allFilterParamsAreDefined_hp() throws Exception {
// given
Map<String, Serializable> searchConditions = singletonMap("shortName", "GO");
List<String> returnFields = asList("shortname", "gfcid");
String returnFieldsStr = returnFields.stream().collect(joining(","));
RequestFilter filter = RequestFilter.create(searchConditions, returnFieldsStr, 5, 10, true);
int resultSize = 20;
List<ResultRow> searchResult = getSearchResult(resultSize);
when(luceneSearchService.search(filter)).thenReturn(searchResult);
when(luceneSearchService.searchCount(filter)).thenReturn(resultSize);
// do
Result result = searchCoordinator.search(filter);
// verify
assertEquals(searchResult, result.getRows());
assertReturnFields(returnFields, result.getRows());
assertNotNull(result.getPaging());
Map<String, String> nextParams = getQueryParams(result.getPaging().getPageNext());
assertParam(nextParams, "search", toSimpleJsonString(searchConditions));
assertParam(nextParams, "skip", "15");
assertParam(nextParams, "limit", "10");
}

Exception when saving a result

I am developping J2EE application with appfuse , i have a webform called easyVolAction that contain a method search() I need to save the result of search method in database but and an excpetion is generated when clicking in the action search :NullPointerException in object trajet .I created TrajetDaoHibernate:
public TrajetDaoHibernate() {
super(TrajetModel.class);
}
/**
* {#inheritDoc}
*/
#SuppressWarnings("unchecked")
public List<TrajetModel> getTrajet() {
Session session = getSessionFactory().getCurrentSession();
Query qry = session.createQuery("from TrajetModel u order by upper(u.id)");
return qry.list();
}
/**
* {#inheritDoc}
*/
public TrajetModel saveTrajet(TrajetModel trajet) {
if (log.isDebugEnabled()) {
log.debug("user's id: " + trajet.getId());
}
Session session = getSessionFactory().getCurrentSession();
session.saveOrUpdate(trajet);
// necessary to throw a DataIntegrityViolation and catch it in UserManager
session.flush();
return trajet;
}
#Override
public TrajetModel save(TrajetModel trajet) {
return this.saveTrajet(trajet);
}
and TrajetDao:
public interface TrajetDao extends GenericDao {
List<TrajetModel> getTrajet();
TrajetModel saveTrajet(TrajetModel trajet);
}
and trajetManager:
#Service("trajetManager")
public class TrajetModelImpl extends GenericManagerImpl<TrajetModel, Long> implements TrajetManager {
private TrajetDao trajetDao;
#Autowired
public void setTrajetModelDao(TrajetDao trajetDao) {
this.dao = trajetDao;
this.trajetDao = trajetDao;
}
/**
* {#inheritDoc}
*/
public TrajetModel getTrajet(String trajetId) {
return trajetDao.get(new Long(trajetId));
}
/**
* {#inheritDoc}
*/
public List<TrajetModel> getTrajet() {
return trajetDao.getAllDistinct();
}
/**
* {#inheritDoc}
*/
public TrajetModel saveTrajet(TrajetModel trajet) throws TrajetExistsException {
try {
return trajetDao.saveTrajet(trajet);
} catch (DataIntegrityViolationException e) {
//e.printStackTrace();
log.warn(e.getMessage());
throw new TrajetExistsException("Trajet '" + trajet.getNom() + "' already exists!");
} catch (JpaSystemException e) { // needed for JPA
//e.printStackTrace();
log.warn(e.getMessage());
throw new TrajetExistsException("Trajet '" + trajet.getNom() + "' already exists!");
}
}
}
finnaly the action where i declare the search method:
public String recherche() throws IOException, TrajetExistsException {
HttpServletRequest request = (HttpServletRequest) FacesContext
.getCurrentInstance().getExternalContext().getRequest();
// String url1 =
// FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("hidden");
String departAller = request.getParameter("easyVolRobot:villeDepart");
String arriveeAller = request.getParameter("easyVolRobot:villeArrivee");
String jourAller = request.getParameter("easyVolRobot:jourDep");
String moisAller = request.getParameter("easyVolRobot:dateDep");
String jourRetour = request.getParameter("easyVolRobot:jourDep");
String moisRetour = request.getParameter("easyVolRobot:dateArr");
String jourAllerPlus1 = jourAller + 1;
parametre = "departAller=" + departAller + "&arriveeAller="
+ arriveeAller + "&jourAller=" + jourAller + "&moisAller="
+ moisAller + "&jourRetour=" + jourRetour + "&moisRetour="
+ moisRetour;
parametre1 = "departAller=" + departAller + "&arriveeAller="
+ arriveeAller + "&jourAller=" + jourAllerPlus1 + "&moisAller="
+ moisAller + "&jourRetour=" + jourRetour + "&moisRetour="
+ moisRetour;
String response = sendGetRequest(url, parametre);
// insert();
PrintStream out = null;
try {
out = new PrintStream(new FileOutputStream(
"/data/crawl/root/siteSNCF.html"));
out.print(response);
} finally {
if (out != null)
out.close();
}
// tableau de resultats des trajets
List<TrajetModel> listTrajets = new ArrayList<TrajetModel>();
// trajet
//TrajetModel trajet = new TrajetModel();
File input = new File("/data/crawl/root/siteSNCF.html");
Document doc = Jsoup.parse(input, "UTF-8",
"http://www.easyvols.org/france-voyage");
for (Element vol : doc.select("div.vols")) {
//trajet = new TrajetModel();
for (Element allerRetour : vol.select("div.aller-retour")) {
Elements aeroport = allerRetour.select("div.aeroport");
System.out.println(aeroport.text());
Elements depart = allerRetour.select("div.depart");
Elements arrive = allerRetour.select("div.arrivee");
Elements date = allerRetour.select("div.date");
trajet.setNom(aeroport.text());
trajet.setVilleDepart(depart.text());
trajet.setVilleArrive(arrive.text());
trajet.sethArrive(12);
trajet.sethDepart(11);
trajet.sethReqt(14);
}
Elements prix2 = vol.select("div.tarif");
trajet.setPrice(prix2.text());
trajet = trajetManager.saveTrajet(trajet);
System.out.println(trajet);}
return"mainMenu";
}
why you comment this line out?
//TrajetModel trajet = new TrajetModel();
I see no other line where you create the TrajetModel.
If that object is not initiated you get the NPE here:
trajet.setNom(aeroport.text());

Java: Android: SQLite: Doing Multiple Inserts Using a For Loop

Please review the following piece of code:
try {
db.beginTransaction();
db.execSQL(DBConstants.PRAG_FOR_KEYS_ON);
db.execSQL(DBConstants._BLDG_CREATE);
db.execSQL(DBConstants._BLDG_INDEX);
for(int x = 0; x < 28; x = x+1){
db.execSQL(DBConstants._BLDG_INSERT+x);
}
db.execSQL(DBConstants.PRAG_FOR_KEYS_OFF);
db.setTransactionSuccessful();
} catch (SQLException e) {
e.printStackTrace();
}finally{
db.endTransaction();
}
Each of the insert constants (representing a row of new data) are numbered thus:
public static final String _BLDG_INSERT0 = "<SQL insert statement>"
...all the way up to 28 ("_BLDG_INSERT28").
Is there ANY way i can execute these SQL statements in a for loop? If i can, how do i concactenate the number on to the name of the constant AND have it recognized by the java interpreter in the correct way?
Thanks!
It's not clear from the question whether you are able to change the constants. If you can, it would be better if you could put the statements in an array.
String[] _BLDG_INSERT = {"<SQL insert statement>", // 0
"<SQL insert statement>", // 1
...
"<SQL insert statement>" // 28
};
And then you can just access them like this.
for(int x = 0; x < 28; x = x+1){
db.execSQL(DBConstants._BLDG_INSERT[x]);
}
Or better still:
for(String s : DBConstants._BLDG_INSERT) {
db.execSQL(s);
}
public ArrayList<String> getAllRecord()
{
ArrayList<String> total = new ArrayList<String>();
Cursor cursor1 = null;
try
{
cursor1 = getDBobject().rawQuery(
"select * from "
+ Your table name + ";", null);
if (cursor1.moveToFirst())
{
do
{
String cid = cursor1.getString(1);
total.add(cid);
}
while (cursor1.moveToNext());
}
}
catch (Exception e)
{
System.out.println("" + TAG + " :" + e);
}
finally
{
if (cursor1 != null && !cursor1.isClosed())
{
cursor1.close();
}
}
return total;
}
This will return you all the datas according to your insertion order
Try something like this:
public class testeReflection {
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException{
MyClass myClass = new MyClass();
Class aClass = MyClass.class;
for(int i = 0; i < 5; i++){
try {
Field field = aClass.getField("VAR" + i);
String s = (String)field.get(myClass);
System.out.println("myClass[" + i + "] = " + s);
} catch (NoSuchFieldException ex) {
Logger.getLogger(testeReflection.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(testeReflection.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static class MyClass{
public static final String VAR0 = "VARIAVEL 01";
public static final String VAR1 = "VARIAVEL 02";
public static final String VAR2 = "VARIAVEL 03";
public static final String VAR3 = "VARIAVEL 04";
public static final String VAR4 = "VARIAVEL 05";
}
}

Categories

Resources