NullPointerException in DOM seletor method - android

I keep getting this error
NullPointer
08-16 22:55:46.360: ERROR/AndroidRuntime(11047): Caused by: java.lang.NullPointerException
08-16 22:55:46.360: ERROR/AndroidRuntime(11047): at com.fttech.htmlParser.releaseInfo.onCreate(releaseInfo.java:62)
08-16 22:55:46.360: ERROR/AndroidRuntime(11047): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
08-16 22:55:46.360: ERROR/AndroidRuntime(11047): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1712)
Its pointing to my Element here
Element paragraph = overview.select("p").last();
i am using this to retrieve the article
try {
doc = Jsoup.connect(url).get();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(doc == null){
Toast.makeText(this, "Couldnt retrieve game info", Toast.LENGTH_SHORT);
}
else{
// Get the overview div
Element overview = doc.select("div#object-overview").last();

Everytime you look for an element with select("") your calling last() in a chain which assumes it will always find atleast 1 element, in the situation that there is no say "p" in the document, that is when you will encounter a crash.
It's just simple NullPointerExceptions, you need to learn to code defensively:
// If you believe overview could be null
if(overview != null){
ArrayList<Element> paragraphs = overview.select("p"); // Whatever type select(String) returns
Element lastParagraph = null;
if(paragraphs != null){
lastParagraph = paragraphs.last();
} else {
// Deal with not finding "p" (lastParagraph is null in this situation)
}
// Continue with lastParagraph
} else {
// Deal with overview being null
}
Number 1 Java Error (scroll down)
Also you shouldn't really wrap your code with a catch all Exception, try to catch each exception and deal with them individually.
Lookup the API for your get() method Jsoup get() (eclipse tells you this anyway) It throws IOException, so you should just catch this.
try {
doc = Jsoup.connect(url).get();
} catch (IOException e) {
Log.e("Tag", "Jsoup get didn't get a document", e);
}
Number 5 Java Error (scroll down)

Related

catch only ENOSPC on Android

This might be a basic question but I cannot find an answer. When you want to catch only FileNotFound in Android, then you write
} catch (FileNotFoundException e) {
But what do you write if you want to catch exactly ENOSPC (No space left on device) errors? I can't use "catch (Exception e)" because I want to explicitly deal with this one error.
You cannot do so directly as enospc is signaled as a java.io.IOException which will catch many other io related issues as well. But by looking up the cause and the error it's signalling you can zoom in and handle enospc exceptions but rethrow all others, like this:
} catch (IOException ex) {
boolean itsanenospcex = false;
// make sure the cause is an ErrnoException
if (ex.getCause() instanceof android.system.ErrnoException) {
// if so, we can get to the causing errno
int errno = ((android.system.ErrnoException) ex.getCause()).errno;
// and check for the appropriate value
itsanenospcex = errno == OsConstants.ENOSPC;
}
if (itsanenospcex) {
// handle it
} else {
// if it's any other ioexception, rethrow it
throw ex;
}
}
Sidenote: } catch (Exception e) { is generally considered bad practice.

How to prevent android app from crashing when a file has not been found using openFileInput

I want to react to a situation that no file has been found using FileInputStream. When i ran an app that loads a file that doesn't exist it opens an android popup with force close. I would like to react to the situation by changing a text in a text view and saying that the file has not been found. i tried changing the exceptions to change a text view and show that a file has not been found and the app still crashes.
Here is the piece of code:
FileInputStream fis = null;
String collected = null;
try {
fis = openFileInput("test");
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
collected = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
tv.setText(collected);
To ensure that an Android application does not force-close, your options are: a) do not do anything that will cause an exception, b) catch your exception with your own try/catch block, c) install an application level uncaught exception handler. Option a is not too feasible, c is not very helpful, and based on your code snippet you seem to be trying b -- however there appears to be another exception that you're not catching with this. The contents of logcat will tell you what exception, and the stack trace will lead to a point in your code which needs the try/catch.

android:String index out of bound

I am making an app in which i am stuck in this exception - String index out of bound and i get error at the following line.
String netwrkk = mTelephonyMgr.getNetworkOperator();
System.out.println("hello");
if (netwrkk != null) {
System.out.println("hello2");
// int mcc = Integer.parseInt(netwrkk.substring(0, 3)); // exception at this line
System.out.println("hello3");
int mnc = Integer.parseInt(netwrkk.substring(3));// exception at this line
System.out.println("hello4");
mccc1=(TextView)findViewById(R.id.mccc1);
System.out.println("netwrk:"+netwrkk);
mccc1.setText(Integer.toString(mcc));
mncc1=(TextView)findViewById(R.id.mncc1);
System.out.println("netwrk:"+netwrkk);
mncc1.setText(Integer.toString(mnc));
System.out.println("mccc: "+mcc);
try{
System.out.println("bearing : "+locn.getBearing());
}catch (Exception e) {
System.out.println(e);
}System.out.println("mnc"+mnc);
}
You should check if netwrkk has the length of 4 or more. If not, the substring(0, 3) will fail.
Also make yourself familiar with the Log class in android. You shouldn't use System.out.println()

Android: Need help, trying to parse a HTML page using JSoup parser

Here is the code so far I am trying but it is showing me error:
URL url = null;
try {
url = new URL("http://wap.nastabuss.se/its4wap/QueryForm.aspx?hpl=Teleborg+C+(V%C3%A4xj%C3%B6)");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("1");
Document doc = null;
try {
System.out.println("2");
doc = Jsoup.parse(url, 3000);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("3");
Element table = doc.select("table[title=Avgångar:]").first();
System.out.println("4");
Iterator<Element> it = table.select("td").iterator();
//we know the third td element is where we wanna start so we call .next twice
it.next();
it.next();
while(it.hasNext()){
// do what ever you want with the td element here
System.out.println(it.next());
//iterate three times to get to the next td you want. checking after the first
// one to make sure
// we're not at the end of the table.
it.next();
if(!it.hasNext()){
break;
}
it.next();
it.next();
}
It prints System.out.println("3");
then it stops in this line
Element table = doc.select("table[title=Avgångar:]").first();
How can i solve this problem,
Thanks
It looks like the website you're trying to parse the HTML from has an error and doesn't have any tables on it. This is what's causing the null pointer exception. doc.select("table[title=Avgångar:]") isn't returning an element and then you're trying to call a method on it. To prevent this error from happening again, you could do something like this:
Elements foundTables = doc.select("table[title=Avgångar:]");
Element table = null;
if(!foundTables.isEmpty()){
table = tables.first();
}
Now, if any table was found, the table variable won't be null. You'll just have to alter the code to adapt in case no tables are found.
You're not checking the result of doc.select() before calling .first(). If there are no elements in the document that match the specified query, doc.select() could return null. Then you are calling .first() on a null pointer which, of course, will throw an exception. There is no table tag with the title you have specified in the document that you are using in your example. So, the result is not surprising.

android exception for validating file exist not working

I've been working with Eclipse ADT for about 2 months. In that time, I have a small utility that allows me to select an IP Address and Port, and then send a file to that combo. The utility works as intended, but when I type in the wrong file name, the application hangs.
#Override
public void run() {
if (data != null) {
this.send(data);
} else if (this.file != null) {
if (file.exists()) {
this.send(file);
} else {
transferError = new FileNotFoundException("The specified file could not be found");
}
}
}
I've even tried to do the following in hopes that one or the other would throw, but I am unsuccessful in both.
public void run() {
if (data != null) {
this.send(data);
} else if (this.file != null) {
if (file.exists()) {
this.send(file);
} else {
transferError = new FileNotFoundException("The specified file could not be found");
}
}try {
throw new Exception("blah blah blah");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I've jockeyed around the exception, I've added the one above, I've tried placing it in different places, and all unsuccessful. Again, I'm exceptionally new to this, and got here from basically mincing various tcp client codes. Aside of creating a way to throw the exception correctly, please help me understand why the first one isn't working and why the one you suggest is.
in your else block you aren't throwin the transferError you create.
throw transferError;
However you probably won't be able to do that because FileNotFoundException is a checked exception and the run() method doesn't declare any thrown exceptions. You probably need to find a different way to present the error to the user, like with a Toast or something.
Your second block doesn't work because you are catching the exception you throw.

Categories

Resources