Jsoup: Android App crashes - java

I have this following code:
String webPage = "http://www.something.com";
String html = null;
try{
html = Jsoup.connect(webPage).get().html();
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(this, html, Toast.LENGTH_SHORT).show();
If its the Exception Exception the code does the other stuff (before this code) and does not do the code in try{}, if the Exception is IOException, the app crashes

The app crashes due to NetworkOnMainThreadException
You are not allowed to perform network operations from the main thread.
Instead, try running Jsoup from an AsyncTask

Also, you should read what kind of Exception Jsoup can throw and handle each of them as you plan to instead of catching the base jave Exception class. You can also catch multiple exceptions in one catch block if you plan to handle them the same way.
Example:
String webPage = "http://www.something.com";
String html = null;
try {
html = Jsoup.connect(webPage).get().html();
} catch (SocketTimeoutException|IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace()
}
Toast.makeText(this, html, Toast.LENGTH_SHORT).show();

Related

HtmlUnit throws ambiguous String error in Processing

I am trying to write code in Processing (basically Java) that will get the information from the table here: http://science.nasa.gov/iSat/iSAT-text-only/
I have not started writing the code specific to the table yet because I can't even get this to run. I get the error "type String is ambiguous." I cannot find any duplicate of String nor can I think of any other reason for this error.
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.*;
import java.net.*;
WebClient client = new WebClient(BrowserVersion.CHROME);
try {
java.lang.String url = "http://science.nasa.gov/iSat/iSAT-text-only/";
Page page = client.getPage(url);
println(page.getWebResponse().getContentAsString());
}
catch(IOException e) {
println("oops!");
}
UPDATE:
I modified the code slightly and got it to get the information I want using the following code in eclipse:
WebClient client = new WebClient();
String url = "http://science.nasa.gov/iSat/iSAT-text-only/";
HtmlPage page = null;
try {
page = (HtmlPage) client.getPage(url);
} catch (FailingHttpStatusCodeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
client.waitForBackgroundJavaScript(10000);
System.out.print(page.asXml());
but it still throws the ambiguous String error in Processing.
Bizarrely, manually importing java.lang.String fixed the error.

java itext catching null exception pdf text extraction

When extracting text form pdf using itext 5.3.4 using this code:
try {
reader = new PdfReader(thepdffilename);
} catch (IOException e) {
openok=false;
}
if (openok==true){
int numberOfPages = reader.getNumberOfPages();
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
for (int page = 1; page <= numberOfPages; page++){
try {
SimpleTextExtractionStrategy strategy = parser.processContent(page, new SimpleTextExtractionStrategy());
content = content + strategy.getResultantText();
} catch (Throwable t) {
crap=true;
break;
}
}
reader.close();
}
However occasionally GooglePlay crashes & ANRs reports that there has been a NP exception in itext.
java.lang.NullPointerException in com.itextpdf.text.pdf.PdfReader$PageRefs.readPages at
com.itextpdf.text.pdf.PdfReader$PageRefs.readPages(PdfReader.java:3382) at
com.itextpdf.text.pdf.PdfReader$PageRefs.<init>(PdfReader.java:3350) at com.itextpdf.text.pdf.PdfReader$PageRefs.<init>(PdfReader.java:3328) at
com.itextpdf.text.pdf.PdfReader.readPages(PdfReader.java:1003) at com.itextpdf.text.pdf.PdfReader.readPdf(PdfReader.java:530) at
com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:170) at
com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:159)
The 5.3.4 source code at line 3382 is:
http://grepcode.com/file/repo1.maven.org/maven2/com.itextpdf/itextpdf/5.3.4/com/itextpdf/text/pdf/PdfReader.java?av=f
3374 void readPages() throws IOException {
3375 if (refsn != null)
3376 return;
3377 refsp = null;
3378 refsn = new ArrayList<PRIndirectReference>();
3379 pageInh = new ArrayList<PdfDictionary>();
3380 iteratePages((PRIndirectReference)reader.catalog.get(PdfName.PAGES));
3381 pageInh = null;
3382 reader.rootPages.put(PdfName.COUNT, new PdfNumber(refsn.size()));
3383 }
3384
3385 void reReadPages() throws IOException {
3386 refsn = null;
3387 readPages();
3388 }
So something is going wrong when certain pdf files are having their text extracted and the reason why that could be happening is probably never going to be sorted as I do not have the pdfs in question.
What I require is a method of catching the NP exception so my app does not crash.
I've tried
} catch (Exception e) {
and as a last resort to try and catch any exception
} catch (Throwable t) {
Does anyone have an idea how I can get this particular itext error to be caught?
thanks
If I understand you correctly, your attempts to catch that NPE have been made in your loop through the document pages:
for (int page = 1; page <= numberOfPages; page++){
try {
SimpleTextExtractionStrategy strategy =
parser.processContent(page, new SimpleTextExtractionStrategy());
content = content + strategy.getResultantText();
} catch (Throwable t) {
crap=true;
break;
}
}
If you look closely at your Exception, though...
java.lang.NullPointerException in com.itextpdf.text.pdf.PdfReader$PageRefs.readPages at
com.itextpdf.text.pdf.PdfReader$PageRefs.readPages(PdfReader.java:3382) at
[...]
com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:159)
you see that the exception already occurs in the PdfReader construction (PdfReader.<init>). Thus, you have to catch the NPE already where you construct your PdfReader:
try {
reader = new PdfReader(thepdffilename);
} catch (IOException e) {
openok=false;
} catch (NullPointerException npe) { // !!
openok=false; // !!
}
Or if you want to take no chances
try {
reader = new PdfReader(thepdffilename);
} catch (Throwable t) { // !!
openok=false;
}
If you have other code locations, too, in which a PdfReader is constructed, you may want to harden them, too.
#BrunoLowagie This NPE had better be transformed to a tagged exeption, hadn't it?
This is ugly but if you really want to catch it , try and catch RuntimeException

Catching Exception in java to make application continue its execution

This is what i have right now, this method open's a connection with http url,
public static void setCameraList(String list) {
URL calculator;
try {
String url = "http://example.com/index.php?cameraList=" +URLEncoder.encode(list, "ISO-8859-1");
calculator = new URL(url);
URLConnection calcConnection = calculator.openConnection();
BufferedReader streamReader = new BufferedReader(new InputStreamReader(calcConnection.getInputStream()));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
This work's fine, but sometimes when url is unreachable or return's some error code this method seem's to crash full app.
What i am curious about is, Why this method fails to catch Exception ?
Also, If i add this :
catch(Throwable th){
}
Will this method catch every possible error/exception related to what operation's i perform inside it ?
I'm not a Java expert, but you should consider that there is a difference between exception and error.
Did you have a look here?
May you post the stacktrace?
Thank you
If you add this : catch(Throwable th){ } every single exception your method throws will be catch. In order to resolve your problem properly, you must pay atention about what type of exception is thrown when the problem you are describing happens!

google docs api folder

I'm trying to develop one java function to retrieve the id of one specific folder over Google Docs, but the documentation over this language is poor and have problems to develop it. Until now I've can make this, but don't work, it never show my the document id of my folder
public void findfolder(String folderName) throws MalformedURLException,IOException,ServiceException{
URL feedUrla=new URL("https://docs.google.com/feeds/default/private/full/-/folder");
DocumentQuery query = new DocumentQuery(feedUrl);
query.setTitleQuery(folderName);
query.setTitleExact(true);
DocumentListFeed feed=null;
try {
feed = client.getFeed(query, DocumentListFeed.class);
} catch (IOException e) {
e.printStackTrace();
} catch (ServiceException e) {
e.printStackTrace();
}
for (DocumentListEntry entry : feed.getEntries()) {
System.out.println(entry.getDocId());
}
}`

Best practice for handling multiple exceptions in similar ways in Java

Is there a canonical best-way-to-do-this for the following situation?
I have a block of code that can generate a number of different exceptions, each of which is handled by hiding a dialog, displaying an error message and running an onDisconnect() method. The catch is that, for each exception, the error message needs to be different. As I see it, there are two choices. The first is to catch Exception, then handle the various exceptions inside the catch block using instanceof, like so:
} catch (Exception e) {
dialog.dismiss();
String errorMessage = getString(R.string.default_error);
if (e instanceof ArrayIndexOutOfBoundsException)
errorMessage = getString(R.string.bad_host);
else if (e instanceof UnknownHostException)
errorMessage = getString(R.string.unknown_host);
else if (e instanceof NumberFormatException)
errorMessage = getString(R.string.bad_port);
else if (e instanceof IOException)
errorMessage = getString(R.string.no_connection);
showError(errorMessage);
onDisconnect();
}
The other option is to catch all of them separately, like so:
} catch (ArrayIndexOutOfBoundsException e) {
dialog.dismiss();
showError(getString(R.string.bad_host));
onDisconnect();
} catch (UnknownHostException e)
dialog.dismiss();
showError(getString(R.string.unknown_host));
onDisconnect();
} // ...etc.
Is there a preferred way to do this? I opted for the first case (at least for now) because it minimizes duplicated code, but I've also heard that instanceof and catch (Exception) are the works of Satan.
My preference is to have a separate method like this:
void handleException(String msg) {
dialog.dismiss();
showError(getString(msg));
onDisconnect();
}
and then in your code that throws the exception just like this:
} catch (ArrayIndexOutOfBoundsException e) {
handleException(getString(R.string.bad_host));
} catch (UnknownHostException e)
handleException(getString(R.string.unknown_host));
} // ...etc.
You want to catch them separately. If you catch the generic Exception, you might end up catching Exceptions that you're not expecting (that could be pushed up from somewhere else in the stack for example) and you're stopping them from propagating up to wherever they were actually meant to be handled.
(Later edit): You may also want to look into using finally to avoid some of the code repetition problem.
make a (private void) method for handling the error. You may be required to pass it in some parameters about what's going on, but the behavior will be consistent. When you make a change to the method it changes all places where it's used, so you get to reduce your boilerplate code.
try {
// stuff
} catch(OneException) {
handleSimilarExceptions();
} catch(TwoException) {
handleSimilarExceptions();
} catch(DifferentException) {
log.write("Something wierd happened, handling it");
somethingDifferent();
}
What if you do smth like modified second version:
catch (ArrayIndexOutOfBoundsException e) {
handleException(R.string.bad_host);
} catch (UnknownHostException e)
handleException(R.string.unknown_host);
} // ...etc.
void handleException(String s) {
dialog.dismiss();
showError(getString(s));
onDisconnect();
}
And I agree, instanceof usage like this is a work of Satan...

Categories

Resources