So what I want to do is when my Jsoup connection times out I want to bring up an alert dialog. Right now it does nothing. It just skips over there error and doesn't catch a timeout exception or crash. I'm new to java so I'm not sure how to catch this sockettimeoutexception and reroute it to another method. Can someone tell me how to go to another method when jsoup time out?
private void waterLevel() {
// TODO Auto-generated method stub
try {
levelDoc = Jsoup.connect("http://waterdata.usgs.gov/va/nwis/uv?site_no=02037500roop").timeout(3000).get();
} catch (SocketTimeoutException a) {
Log.e("MyAPP", "Exception----------A!", a);
a.printStackTrace();
alertdialog();
} catch (Exception e) {
Log.e("MyAPP", "Exception----------E!", e);
}
for (Element table : levelDoc.select("table[id=table_07_00065]")) {
String tableText = table.text();
depthArray = tableText.split(" ");
waterLevel = Double.parseDouble(depthArray[4]);
tvWaterLevel.setText(depthArray[4]+"FT");
if(waterLevel >= 5.0 && waterLevel < 9.0){
tvAlert.setText("LIFE JACKET REQUIRED");
}
else if (waterLevel >= 9.0){
tvAlert.setText("HIGH WATER PERMIT REQUIRED");
}
else{
tvAlert.setText("");
}
}
}
So I add changed the code to this and it gives me what i want:
private void waterLevel() {
// TODO Auto-generated method stub
try {
levelDoc = Jsoup.connect("http://waterdata.usgs.gov/va/nwis/uv?site_no=02037500").timeout(4000).get();
} catch (SocketTimeoutException a) {
Log.e("MyAPP", "Exception----------A!", a);
a.printStackTrace();
} catch (Exception e) {
Log.e("MyAPP", "Exception----------E!", e);
}
tvWaterLevel.setText("");
for (Element table : levelDoc.select("table[id=table_07_00065]")) {
String tableText = table.text();
depthArray = tableText.split(" ");
waterLevel = Double.parseDouble(depthArray[4]);
tvWaterLevel.setText(depthArray[4]+"FT");
if(waterLevel >= 5.0 && waterLevel < 9.0){
tvAlert.setText("LIFE JACKET REQUIRED");
}
else if (waterLevel >= 9.0){
tvAlert.setText("HIGH WATER PERMIT REQUIRED");
}
else{
tvAlert.setText("");
}
}
if (tvWaterLevel.length() < 1){
connectionAlarm();
}
}
Related
I written a method which will acknowledge the controller by returning true and false, I return true inside try if everything goes fine it will return true and I return false inside catch blocks, but still method shows me error "missing return statement" what is the best way to do it.
The below method written in java will send back the true or false to the controller.
Secondly I want to carry the exception message from here to controller, I think of returning string, is it good approach,
Kindly suggest me the best way to do the exception handling
public boolean pickSalayData(String yearMonth, String regionId, String circleId, Userdetail loginUser) throws MyExceptionHandler {
String tableSuffix = yearMonth.substring(4, 6) + yearMonth.substring(0, 4);
log.info("Pick Salary Data From ERP " + DateUtility.dateToStringDDMMMYYYY(new Date()));
List<SalaryDetailReport> detailReports = hRMSPickSalaryDataDAO.findAll(yearMonth, regionId, circleId);
TransactionDefinition def = new DefaultTransactionDefinition();
TransactionStatus trstatus = transactionManager.getTransaction(def);
try {
List<SalaryDetailReport> salaryDetailReport = null;
int countDetail = 0;
if (detailReports != null && detailReports.size() > 0) {
for (SalaryDetailReport salary : detailReports) {
try {
if (countDetail % COMMIT_COUNT == 0) {
if (salaryDetailReport != null) {
salaryDetailReportDAO.save(salaryDetailReport, tableSuffix);
reportHistoryDAO.save(salaryDetailReport, loginUser);
}
salaryDetailReport = new ArrayList<SalaryDetailReport>();
}
salaryDetailReport.add(salary);
countDetail++;
} catch (Exception e) {
log.error("Error on Save Salary Pay Head Details Data from ERP to Prayas .");
}
}
if (salaryDetailReport != null && salaryDetailReport.size() > 0) {
salaryDetailReportDAO.save(salaryDetailReport, tableSuffix);
reportHistoryDAO.save(salaryDetailReport, loginUser);
}
} else {
throw new MyExceptionHandler("No record for Save in Database from ERP.");
}
salaryDetailReportDAO.update(tableSuffix, regionId, circleId);
List<SalaryDetailReport> reports = salaryDetailReportDAO.findAll(tableSuffix, regionId, circleId);
if (reports != null && reports.size() > 0) {
for (SalaryDetailReport salaryDetail : reports) {
try {
SalaryDetail sd = new SalaryDetail();
sd.setDetailReport(salaryDetail);
salaryDetailDAO.save(sd, tableSuffix);
} catch (Exception e) {
log.error("Error occured", e);
e.printStackTrace();
throw new MyExceptionHandler(" Error :" + e.getMessage());
}
}
System.out.println("data found");
} else {
log.error("Salary Record Not Found.");
throw new MyExceptionHandler("No record Found.");
}
salaryDetailDAO.updateEarningDeduction(tableSuffix);
//salaryDetailDAO.updateEarningDeductionsInSDT();
transactionManager.commit(trstatus);
try {
hRMSPickSalaryDataDAO.update(regionId, circleId, yearMonth);
return true;
} catch (Exception ex) {
log.error("Some error : ", ex);
}
// // System.out.println("Completed =============================");
} catch (MyExceptionHandler ex) {
transactionManager.rollback(trstatus);
ex.printStackTrace();
log.error("Failed to Save Salary data :" + ex.getMessage());
return false;
} catch (Exception ex) {
transactionManager.rollback(trstatus);
ex.printStackTrace();
log.error("Error occured on Save Salary data.", ex);
return false;
}
}
You are missing return statement for the following catch block :
catch (Exception ex) {
log.error("Some error : ", ex);
}
Either you add return statement in this catch block or at the end of mehtod
If this code throws an Exception, then the following catch code will not be entered into and hence there is no return value
try {
hRMSPickSalaryDataDAO.update(regionId, circleId, yearMonth);
return true;
} catch (Exception ex) {
log.error("Some error : ", ex);
**edit**
return `true||false`;
}
} catch (...) {
return something;
}
I have the methods:
public void sendTroops(ArrayList<Troops> troops){
try {
output.writeObject(troops);
output.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendTowers(ArrayList<Tower> towers){
try {
output.writeObject(towers);
output.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendString(ArrayList<String> str){
try {
output.writeObject(str);
output.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
#SuppressWarnings("unchecked")
public ArrayList<Object> receiveObjects(){
try{
return (ArrayList<Object>) input.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
used here:
private void updateConnection(){
if(isClientActive()){
if(player.getType() == 0){
client.sendTowers(towers);
System.out.println("sent towers: " + towers.size());
}else{
client.sendTroops(troops);
System.out.println("sent troops: " + troops.size());
}
ArrayList<Object> obj = client.receiveObjects();
System.out.println("obj: " +obj.size());
if(obj != null && obj.size() > 0){
if (obj.get(0) instanceof Troops) {
mendTroops(obj);
}else if(obj.get(0) instanceof Troops){
mendTowers(obj);
}
}
}else if(isServerActive()){
if(player.getType() == 0){
server.sendTowers(towers);
System.out.println("sent towers: " + towers.size());
}else{
server.sendTroops(troops);
System.out.println("sent troops: " + troops.size());
}
ArrayList<Object> obj = server.receiveObjects();
System.out.println("obj: " +obj.size());
if(obj != null && obj.size() > 0){
if (obj.get(0) instanceof Troops) {
mendTroops(obj);
}else if(obj.get(0) instanceof Troops){
mendTowers(obj);
}
}
}
}
I was able to determine that the size of the object array from server/client.receiveObjects(); is always resulting in a array of size zero. I am unsure why this is the issue (as no errors are thrown). Either this is terrible coding practice (which it very well may be) or I'm over looking something.
I would appreciate any help, and if more code/ information of how this program works is needed, please let me know.
I wonder how to confirm a request of adding friends.
Smack Version 4.1.1
As I know now ,
roster = Roster.getInstanceFor(con);
roster.setSubscriptionMode(Roster.SubscriptionMode.manual);
roster.createEntry(targetUser, nickname, new String[] {"friends"});
will create a roster in the database, and send a stanza request to the targetUser.
And my stanza listener is as follows:
StanzaListener callback = new StanzaListener() {
#Override
public void processPacket(Stanza stanza) throws NotConnectedException {
// TODO Auto-generated method stub
String head = con.getUser() + " : ";
System.out.println(head + "Got the presence stanza");
if(((Presence)stanza).getType().equals(Presence.Type.subscribe)) {
Presence subscribed = new Presence(Presence.Type.subscribed);
subscribed.setTo(stanza.getFrom());
System.out.println(head + subscribed.getFrom());
subscribed.setFrom(stanza.getTo());
con.sendStanza(subscribed);
if( ! roster.contains(stanza.getFrom())) {
System.out.println(head + "Friend added.");
addFriend(stanza.getFrom(),"computer");
}
} else {
System.out.println(head + "Subscribed received from " + stanza.getFrom());
if(roster.contains(stanza.getFrom())) {
System.out.println(head + "OK");
}
}
}
};
It does not work, I wonder when the targetUser receives the stanza request , how to send a callback presence(or something else) to confirm or approve or agree?
How to add a friend?
Try this:
public void addFriend(User usuario) {
if (APDApplication.connection != null && APDApplication.connection.isConnected()) {
try {
Roster.setDefaultSubscriptionMode(Roster.SubscriptionMode.manual);
Roster roster = Roster.getInstanceFor(APDApplication.connection);
if (!roster.contains(usuario.getChatId())) {
roster.createEntry(usuario.getChatId() + "#jabber/Smack", usuario.getName(), null);
} else {
logManager.error("Contacto ya existente en la libreta de direcciones");
}
} catch (SmackException.NotLoggedInException e) {
e.printStackTrace();
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Hope this helps you!!
Please explain to me why my code throws a IllegalMonitorStateException at the wait function, as far as I know this only happens if its not done in a synchronized part?
private void deliver(int target) {
Warehouse targetW = targets[target];
targetW.deliver();
System.out.println(name + " starts to deliver too " +
targetW.getName());
int sleepTime = DELIVERY_TIME / LOADING_CAPACITY;
int counter = 0;
while (counter < LOADING_CAPACITY) {
synchronized (targetW) {
while (!targetW.fill(1)) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
counter++;
try {
sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
leaveMSG(targetW);
targetW.delivered();
}
You can only call wait() inside a synchronized block on that object.
Inside synchronized (targetW), you can call targetW.wait().
I'm currently writing a program where I have a string of methods all set up basically identical. If they're given i = 1, they'll return the price of the product times the quantity ordered. Otherwise, they simply returned the quantity ordered. Whenever I attempt to compile it, however, the compiler says that the brackets are missing return statements. I've gone through the code several times and I don't see anything overtly wrong in the syntax. Any guesses as to why this is happening?
Thank you for any help.
Relevant Source:
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == switchCard)
{
cl.show(infoPanel, (String)candyList.getSelectedValue());
}
if (e.getSource() == checkoutButton)
{
double acidPops = acidPopsTotal(1);
double bertieBotts = bertieBottsTotal(1);
double bloodPops = bloodPopsTotal(1);
double cauldronCakes = cauldronCakesTotal(1);
double charmChoc = charmChocTotal(1);
double chocoballs = chocoballsTotal(1);
double chocCauldrons = chocCauldronsTotal(1);
double chocFrogs = chocFrogsTotal(1);
double chocWands = chocWandsTotal(1);
double roachClusters = roachClustersTotal(1);
double crystalPineapple = crystalPineappleTotal(1);
double droobleGum = droobleGumTotal(1);
double explodeBonbons = explodeBonbonsTotal(1);
double fizzWhiz = fizzWhizTotal(1);
double iceMice = iceMiceTotal(1);
double jellySlugs = jellySlugsTotal(1);
double liquorWands = liquorWandsTotal(1);
double pepImpts = pepImpsTotal(1);
double pinkIce = pinkIceTotal(1);
double shockChoc = shockChocTotal(1);
double spindleSpiders = spindleSpidersTotal(1);
double quills = quillsTotal(1);
double wizochoc = wizochocTotal(1);
}
}
double acidPopsTotal(int i)
{
if (i == 1)
{
try
{
return (5.95* (Integer.parseInt(acidPopsTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(acidPopsTF.getText());
}
catch (NumberFormatException e) {}
}
}
double bertieBottsTotal(int i)
{
if (i == 1)
{
try
{
return (16.95 * (Integer.parseInt(bertieBottsTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(bertieBottsTF.getText());
}
catch (NumberFormatException e) {}
}
}
double bloodPopsTotal(int i)
{
if (i == 1)
{
try
{
return (5.95 * (Integer.parseInt(bloodPopsTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(bloodPopsTF.getText());
}
catch (NumberFormatException e) {}
}
}
double cauldronCakesTotal(int i)
{
if (i == 1)
{
try
{
return (14.95 * (Integer.parseInt(cauldronCakesTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(cauldronCakesTF.getText());
}
catch (NumberFormatException e) {}
}
}
double charmChocTotal(int i)
{
if (i == 1)
{
try
{
return (5.95 * (Integer.parseInt(charmChocTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(charmChocTF.getText());
}
catch (NumberFormatException e) {}
}
}
double chocoballsTotal(int i)
{
if (i == 1)
{
try
{
return (9.95 * (Integer.parseInt(chocoballsTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(chocoballsTF.getText());
}
catch (NumberFormatException e) {}
}
}
double chocCauldronsTotal(int i)
{
if (i == 1)
{
try
{
return (14.95 * (Integer.parseInt(chocCauldronsTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(chocCauldronsTF.getText());
}
catch (NumberFormatException e) {}
}
}
double chocFrogsTotal(int i)
{
if (i == 1)
{
try
{
return (14.95 * (Integer.parseInt(chocFrogsTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(chocFrogsTF.getText());
}
catch (NumberFormatException e) {}
}
}
double chocWandsTotal(int i)
{
if (i == 1)
{
try
{
return (9.95 * (Integer.parseInt(chocWandsTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(chocWandsTF.getText());
}
catch (NumberFormatException e) {}
}
}
double roachClustersTotal(int i)
{
if (i == 1)
{
try
{
return (5.95 * (Integer.parseInt(roachClustersTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(roachClustersTF.getText());
}
catch (NumberFormatException e) {}
}
}
double crystalPineappleTotal(int i)
{
if (i == 1)
{
try
{
return (9.95 * (Integer.parseInt(crystalPineappleTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(crystalPineappleTF.getText());
}
catch (NumberFormatException e) {}
}
}
double droobleGumTotal(int i)
{
if (i == 1)
{
try
{
return (2.95 * (Integer.parseInt(droobleGumTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(droobleGumTF.getText());
}
catch (NumberFormatException e) {}
}
}
double explodeBonbonsTotal(int i)
{
if (i == 1)
{
try
{
return (9.95 * (Integer.parseInt(explodeBonbonsTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(explodeBonbonsTF.getText());
}
catch (NumberFormatException e) {}
}
}
double fizzWhizTotal(int i)
{
if (i == 1)
{
try
{
return (9.95 * (Integer.parseInt(fizzWhizTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(fizzWhizTF.getText());
}
catch (NumberFormatException e) {}
}
}
double iceMiceTotal(int i)
{
if (i == 1)
{
try
{
return (5.95 * (Integer.parseInt(iceMiceTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(iceMiceTF.getText());
}
catch (NumberFormatException e) {}
}
}
double jellySlugsTotal(int i)
{
if (i == 1)
{
try
{
return (2.95 * (Integer.parseInt(jellySlugsTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(jellySlugsTF.getText());
}
catch (NumberFormatException e) {}
}
}
double liquorWandsTotal(int i)
{
if (i == 1)
{
try
{
return (9.95 * (Integer.parseInt(liquorWandsTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(liquorWandsTF.getText());
}
catch (NumberFormatException e) {}
}
}
double pepImpsTotal(int i)
{
if (i == 1)
{
try
{
return (4.95 * (Integer.parseInt(pepImpsTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(pepImpsTF.getText());
}
catch (NumberFormatException e) {}
}
}
double pinkIceTotal(int i)
{
if (i == 1)
{
try
{
return (4.95 * (Integer.parseInt(pinkCocoIceTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(pinkCocoIceTF.getText());
}
catch (NumberFormatException e) {}
}
}
double shockChocTotal(int i)
{
if (i == 1)
{
try
{
return (4.95 * (Integer.parseInt(shockChocTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(shockChocTF.getText());
}
catch (NumberFormatException e) {}
}
}
double spindleSpidersTotal(int i)
{
if (i == 1)
{
try
{
return (4.95 * (Integer.parseInt(spindleSpidersTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(spindleSpidersTF.getText());
}
catch (NumberFormatException e) {}
}
}
double quillsTotal(int i)
{
if (i == 1)
{
try
{
return (1.95 * (Integer.parseInt(sugarQuillsTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(sugarQuillsTF.getText());
}
catch (NumberFormatException e) {}
}
}
double wizochocTotal(int i)
{
if (i == 1)
{
try
{
return (5.95 * (Integer.parseInt(wizochocTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(wizochocTF.getText());
}
catch (NumberFormatException e) {}
}
}
}
Errors:
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:490: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:510: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:530: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:550: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:570: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:590: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:610: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:630: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:650: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:670: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:690: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:710: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:730: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:750: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:770: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:790: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:810: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:830: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:850: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:870: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:890: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:910: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:930: error: missing return statement
}
^
Note: C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
23 errors
There is no return guaranteed due to your try-catch blocks.
You might want to return a sentinel of 0 or -1 to show this.
An example that may make this more clear:
double acidPopsTotal(int i) {
if (i == 1) {
try {
return (5.95* (Integer.parseInt(acidPopsTF.getText())));
} catch (NumberFormatException e) {
//Missing return - compile error
}
} else {
try {
return Integer.parseInt(acidPopsTF.getText());
} catch (NumberFormatException e) {
//Missing return - compile error
}
}
}
In Java it is a compile-time error if there exists at least one path through a non-void function that does not contain a return or a throw. Because you catch a thrown exception and do nothing with it, nothing is returned in that path. Hence, the error.
Aside: you might want to consider a program structure in which you do throw the exception instead of eating it. (Then again, this is probably just example code.)
I believe what TheZ said is correct, there is potential for you to not return anything if an error is caught. Try something like...
double chocFrogsTotal(int i)
{
if (i == 1)
{
try
{
return (14.95 * (Integer.parseInt(chocFrogsTF.getText())));
}
catch (NumberFormatException e) {return -1.;}
}
else
{
try
{
return Integer.parseInt(chocFrogsTF.getText());
}
catch (NumberFormatException e) {return -1.;}
}
}
then whenever you return a value less than 1, you know you had a bad parse.