使用以下代码,
Document doc = null;
doc = Jsoup.parse(page):
String myexample = "My example";
Elements myexamples = doc.select("div.yourOptions p");
if (myexamples != null && myexamples.first().ownText() != null) myexample = myexamples.first().ownText();
对于我的应用程序的 99.9% 的用户来说,一切似乎都很好。
但是我在第 7 行(相当于)收到了一些带有 NullPointerException 的 StackTrace。 StackTrace :
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:278)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.NullPointerException
at com.tomtom.joe.mobile.Suivi$BackgroundAsyncTask.doInBackground(Suivi.java:369)
at com.tomtom.joe.mobile.Suivi$BackgroundAsyncTask.doInBackground(Suivi.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:264)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
... 4 more
如何保护我免受 NullPointerException 的影响?“myexamples.first().ownText()”的内容因用户而异!但我猜“myexamples.first().ownText()”可能为空......
例子 :
<div class="yourOptions"><div class="cockpitContent resizeHeight1">
<h2 class="Title">Title</h2>
<p>Options</p>
<p>Options 2</p>
</div></div>