This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am creating an app in which i want to scrape google data with the help of jsoup and show it to text view in android studio.
But after doing some coding with the help of jsoup i am getting following error:
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.yasht.cricketapp, PID: 11929
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:325)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.jsoup.nodes.Element.text()' on a null object reference
at com.example.yasht.cricketapp.Bottomnav.score_scrape.doInBackground(score_scrape.java:30)
at com.example.yasht.cricketapp.Bottomnav.score_scrape.doInBackground(score_scrape.java:13)
at android.os.AsyncTask$2.call(AsyncTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
this is my jsoup code with async task :
public class score_scrape extends AsyncTask<Void,Void,Void> {
String words;
TextView score;
public score_scrape( TextView score){
this.score =score;
}
#Override
protected Void doInBackground(Void... voids) {
try {
Document doc = Jsoup.connect("https://www.google.com/search?q=india+vs+australia+3rd+odi+live+score").get();
Element element = doc.select("div[imspo_mh_cricket__score-major]").first();
words = element.text();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
score.setText(words);
}
}
I am using async task method which is declared i my main activity.
Comment for any further information.
In your case you don't want to use select You can simply change below line.
Change line from
Element element = doc.select("div[imspo_mh_cricket__score-major]").first();
To
Element element = doc.getElementsByClass("imspo_mh_cricket__score-major").first();
Output:
230
Related
I am recording videos using the camera X library. When i take video for 5 seconds before that (i,e)two seconds if i close the video its crashing with above error.How to handle this run time exception in android cameraX library
E/AndroidRuntime: FATAL EXCEPTION: CameraX-audio encoding thread
Process: .debug, PID: 4625
java.lang.IllegalStateException
at android.media.MediaCodec.native_dequeueOutputBuffer(Native Method)
at android.media.MediaCodec.dequeueOutputBuffer(MediaCodec.java:2698)
at androidx.camera.core.VideoCapture.audioEncode(VideoCapture.java:705)
at androidx.camera.core.VideoCapture$1.run(VideoCapture.java:340)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
at android.os.HandlerThread.run(HandlerThread.java:65)
sometimes the below issue
FATAL EXCEPTION: CameraX-video encoding thread
Process: <packagename>, PID: 10794
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.media.MediaCodec.dequeueOutputBuffer(android.media.MediaCodec$BufferInfo, long)' on a null object reference
at androidx.camera.core.VideoCapture.videoEncode(VideoCapture.java:604)
at androidx.camera.core.VideoCapture$2.run(VideoCapture.java:348)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.os.HandlerThread.run(HandlerThread.java:65)
in this samples also not fixed yet
https://github.com/android/camera-samples/issues/2#issuecomment-546812852
By adding a callback to videoCapture.startRecording(videoFile, executor, onVideoSavedCallback); you should be able to handle the exeption in the onError method.
/**
* Define callback that will be triggered after a video has been taken and saved to disk
*/
private VideoCapture.OnVideoSavedCallback onVideoSavedCallback= new VideoCapture.OnVideoSavedCallback() {
#SuppressLint("RestrictedApi")
#Override
public void onVideoSaved(#NonNull File file) {
Log.d("VIDEO_CAPTURE", "Video capture succeeded");
}
#Override
public void onError(int videoCaptureError, #NonNull String message, #Nullable Throwable cause) {
Log.e("VIDEO_CAPTURE", "Video capture failed");
if (cause != null) {
cause.printStackTrace();
Toast.makeText(context,"Video capture failed",Toast.LENGTH_LONG).show();
}
}
};
One of my methods in my custom SQLiteOpenHelper class throws an "attempt to re-open already closed object" error whenever I try to invoke it after closing the database. I close my databases in onPause on my MainActivity, and then I make sure to check if they are open before invoking a method on the database.
This is the code for the database method, it is within an AsyncTask.
public void insertData(ArrayList<SavedWifiHotspot> hotspots, ArrayList<MarkerOptions> markers) {
Log.d("insert LocationsDB", "Data inserted");
final SQLiteDatabase db = this.getWritableDatabase();
new AsyncTask<ArrayList<SavedWifiHotspot>, Void, Void>() {
#Override
protected Void doInBackground(ArrayList<SavedWifiHotspot>... hotspots) {
Log.d("insert LocationsDB", "Hotspot inserted");
ContentValues hotspotValues = new ContentValues();
for(SavedWifiHotspot hotspot : hotspots[0]) {
hotspotValues.put("Ssid", hotspot.getSsid());
hotspotValues.put("Password", hotspot.getPassword());
hotspotValues.put("LocationName", hotspot.getHotspotLoc());
hotspotValues.put("Lat", hotspot.getLatitude());
hotspotValues.put("Lng", hotspot.getLongitude());
db.insert(HOTSPOT_TABLE_NAME, null, hotspotValues);
}
return null;
}
}.execute(hotspots);
new AsyncTask<ArrayList<MarkerOptions>, Void, Void>() {
#Override
protected Void doInBackground(ArrayList<MarkerOptions>... markers) {
ContentValues markerValues = new ContentValues();
for(MarkerOptions marker: markers[0]) {
markerValues.put("LocationName", marker.getTitle());
markerValues.put("Lat", marker.getPosition().latitude);
markerValues.put("Lng", marker.getPosition().longitude);
db.insert(LOCATION_TABLE_NAME, null, markerValues);
}
return null;
}
}.execute(markers);
}
This is the code used to call the method:
public void updateLocDB() {
if(!db.isOpen()) {
db = locDB.getReadableDatabase();
}
if(!wifiHotspots.isEmpty() && !markers.isEmpty()) {
locDB.clearData();
locDB.insertData(wifiHotspots, markers);
}
}
Logcat output:
FATAL EXCEPTION: AsyncTask #1
Process: com1032.cw2.fm00232.fm00232_assignment2, PID: 368
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.IllegalStateException: attempt to re-open an
already-closed object: SQLiteDatabase:/data/data/com1032.cw2.fm00232.fm00232_assignment2/databases/locationsDB
at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:55)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1659)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
at com1032.cw2.fm00232.fm00232_assignment2.LocationsDB$1.doInBackground(LocationsDB.java:89)
at com1032.cw2.fm00232.fm00232_assignment2.LocationsDB$1.doInBackground(LocationsDB.java:75)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
I've been searching for a few hours, and can't find anything that helps me fix this problem. Any help would be appreciated.
clearData code:
public void clearData() {
Log.d("clear LocationsDB", "Tables cleared");
db = this.getReadableDatabase();
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
String dropHSTable = "DROP TABLE IF EXISTS "
+ HOTSPOT_TABLE_NAME + ";";
String dropLocTable = "DROP TABLE IF EXISTS "
+ LOCATION_TABLE_NAME + ";";
db.execSQL(dropHSTable);
db.execSQL(dropLocTable);
createTables(db);
return null;
}
}.execute();
}
As per my understanding you are executing two asynchronous task at same time. And creating/opening a SQLite DB connection in both tasks. Which creates the problem.
As, it is not possible to create two connections of SQLite DB. Because SQLite is ThreadSafe, only one thread can perform read/write operation at a single time.
You can not perform read and write operations concurrently on SQLite until you do not use WAL(Write Ahead Logging). Follow this for more info Concurrency in SQLite database
If the locDB.clearData(); is also asynchronous it can cause that error by having the connection open to the same SQLite database with the locDB.insertDatalocDB.insertData.
This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 7 years ago.
I'm trying to check for INTERNET connectivity from an Android app but just keep running in to problems.
I'm NOT looking for code that tests for an available network connection - I've got that bit working - this is to test whether I can reach an internet site or not.
(I appreciate that if I am behind a system which presents a logon screen instead of the requested site, I may not get the exact result I want, but I will handle that later)
Thanks to the following question I think I've made some progress, but when I run the app it crashes out (error info below).
The code I have so far is as follows (and I must admit that I find the try/catch stuff a bit puzzling and tedious :-/ )
static public boolean isInternetReachable() {
int statusCode = -1;
try{
URL url = new URL("http://www.google.com/humans.txt");
HttpURLConnection http = (HttpURLConnection) url.openConnection();
statusCode = http.getResponseCode();
http.disconnect();
} catch (MalformedURLException ex) {
return false;
} catch (IOException ex) {
return false;
}
if (statusCode == HttpURLConnection.HTTP_OK) {
return true;
}
else
{
//connection is not OK
return false;
}
}
I'm sure there are neater ways to do this and so any general advice is welcome.
The error that I'm getting when the app crashes is:
01-24 19:53:14.767 10617-10617/com.nooriginalthought.bluebadgeparking E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.nooriginalthought.bluebadgeparking, PID: 10617
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nooriginalthought.bluebadgeparking/com.nooriginalthought.bluebadgeparking.PreLoadChecks}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2411)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2474)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1359)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1155)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:236)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:373)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:323)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:491)
at com.nooriginalthought.bluebadgeparking.PreLoadChecks.isInternetReachable(PreLoadChecks.java:41)
at com.nooriginalthought.bluebadgeparking.PreLoadChecks.onCreate(PreLoadChecks.java:70)
at android.app.Activity.performCreate(Activity.java:5958)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1129)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2474)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1359)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
As David is mentioning in the comments, you should just Google for the Exception name and try to get a turnaround by yourself.
By looking at the StackOverflow answer that he is referring to, you need to make all network communications outside the Main thread. The most used way to do this is by creating an AsyncTask.
In your case, it would look (you can create a new InternetTask.java or just append it to your current MainActivity.java) something like:
class InternetTask extends AsyncTask<Void, Void, Boolean>{
private MainActivity activity;
InternetTask(MainActivity activity){
this.activity = activity;
}
#Override
protected Boolean doInBackground(Void... params) {
int statusCode = -1;
try{
URL url = new URL("http://www.google.com/humans.txt");
HttpURLConnection http = (HttpURLConnection) url.openConnection();
statusCode = http.getResponseCode();
http.disconnect();
} catch (MalformedURLException ex) {
return false;
} catch (IOException ex) {
return false;
}
if (statusCode == HttpURLConnection.HTTP_OK) {
return true;
}
else
{
//connection is not OK
return false;
}
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
activity.receiveMagic(aBoolean);
}
}
Then, you just need to add a new public method in your activity to receive the boolean in your MainActivity.
public void receiveMagic(Boolean isGood){
if (isGood){
Toast.makeText(MainActivity.this, "It is good", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this, "It is not connected", Toast.LENGTH_SHORT).show();
}
}
And you would need to call your new AsyncTask from your Activity with:
new InternetTask(this).execute();
Make sure you add the internet permission to your Manifest also.
I have developed an app in android to find power shut down.When i run the app ,unfortunately closed once I debug the app.Here I got the error in doInbackground
My java code is here
private static final String URL = "http://livechennai.com/powershutdown_news_chennai.asp";
//private static final String URL = "http://livechennai.com/powercut_schedule.asp";
ProgressDialog mProgressDialog;
EditText filterItems;
ArrayAdapter<String> arrayAdapter;
protected String[] doInBackground(Void... params) {
ArrayList<String> hrefs=new ArrayList<String>();
try {
// Connect to website
Document document = Jsoup.connect(URL).get();
// Get the html document title
websiteTitle = document.title();
Elements table=document.select("#table13>tbody>tr>td>a[title]");
for(Element link:table){
hrefs.add(link.attr("abs:href"));
//int arraySize=hrefs.size();
//websiteDescription=link.attr("abs:href");
}
} catch (IOException e) {
e.printStackTrace();
}
//get the array list values
for(String s:hrefs)
{
websiteDescription=hrefs.get(0);
websiteDescription1=hrefs.get(1);
websiteDescription2=hrefs.get(2);
websiteDescription3=hrefs.get(3);
}
Below is the error log
06-09 23:17:10.284 17923-17937/com.example.poweralert.app E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:838)
Caused by: java.lang.IllegalArgumentException: Must supply a valid URL
at org.jsoup.helper.Validate.notEmpty(Validate.java:102)
at org.jsoup.helper.HttpConnection.url(HttpConnection.java:60)
at org.jsoup.helper.HttpConnection.connect(HttpConnection.java:30)
at org.jsoup.Jsoup.connect(Jsoup.java:73)
at com.example.poweralert.app.PrimaryActivity$FetchWebsiteData.doInBackground(PrimaryActivity.java:144)
at com.example.poweralert.app.PrimaryActivity$FetchWebsiteData.doInBackground(PrimaryActivity.java:100)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:838)
06-09 23:17:10.
How to solve this error/issue? It shows null in website description .
Looks like there is an error in URL connection. Are you not passing valid URL?
Caused by: java.lang.IllegalArgumentException: Must supply a valid URL
I'm using the newer RX java where instead of
Observable.create(new Observable.OnSubscribeFunc<T>() {...});
this is used: (due to deprecation)
Observable.create(new Observable.OnSubscribe<T>() {...});
(This can be important as most example, tutorial, explonation uses the old one...)
Well, lets see my problem. I have a Java class, relevant parts from it:
private interface ApiManagerService {
#FormUrlEncoded
#POST("/login")
User getUser(#Field("username") String userName, #Field("password") String password);
}
private static RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(HOST)
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
private static ApiManagerService apiManager = restAdapter.create(ApiManagerService.class);
public static Subscription login(final String userName, final String password, Observer<User> observer) {
return Observable.create(new Observable.OnSubscribe<User>() {
#Override
public void call(Subscriber<? super User> subscriber) {
try {
User user = apiManager.getUser(userName, password);
subscriber.onNext(user);
subscriber.onCompleted();
} catch (RetrofitError e) {
subscriber.onError(e);
} catch (Throwable e) {
subscriber.onError(e);
}
}
}
).subscribeOn(Schedulers.io())
.retry(3)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(observer);
}
This code almost works perfectly, if everything is ok. But if I make an intentional error, like I turn off the WiFi.. than retrofit get the "UnKnownHostException"... as it should happen at the retrofit call (getUser) in the try catch block. But instead of handling the error to onError(Throwable t) --> where I could handle, it just crashes the app. So it is like if the error never gets to the catch block.
What is strange that HTTP errors (like 404, 401 etc.) is catched, got by onError(...) and everything is just fine.
Everything goes for 3 times before crash, as of .retry(3) but none gets into catch clause.
EDIT 1
LogCat Output:
01-08 16:19:31.576 15285-16162/asd.bdef.gh D/Retrofit﹕ ---- ERROR https://testapi.com/api/login
01-08 16:19:31.606 15285-16162/asd.bdef.gh D/Retrofit﹕ java.net.UnknownHostException: Unable to resolve host "testapi.com": No address associated with hostname
at java.net.InetAddress.lookupHostByName(InetAddress.java:394)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at com.squareup.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
at com.squareup.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:259)
at com.squareup.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:233)
at com.squareup.okhttp.internal.http.RouteSelector.nextUnconnected(RouteSelector.java:159)
at com.squareup.okhttp.internal.http.RouteSelector.next(RouteSelector.java:133)
at com.squareup.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:314)
at com.squareup.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:237)
at com.squareup.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:423)
at com.squareup.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:105)
at com.squareup.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:239)
at com.squareup.okhttp.internal.huc.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:218)
at com.squareup.okhttp.internal.huc.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:25)
at retrofit.client.UrlConnectionClient.prepareRequest(UrlConnectionClient.java:68)
at retrofit.client.UrlConnectionClient.execute(UrlConnectionClient.java:37)
at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:321)
at retrofit.RestAdapter$RestHandler.access$100(RestAdapter.java:220)
at retrofit.RestAdapter$RestHandler$1.invoke(RestAdapter.java:265)
at retrofit.RxSupport$2.run(RxSupport.java:55)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:390)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at retrofit.Platform$Android$2$1.run(Platform.java:142)
at java.lang.Thread.run(Thread.java:841)
01-08 16:19:31.606 15285-16162/asd.bdef.gh D/Retrofit﹕ ---- END ERROR
01-08 16:19:31.977 15285-15285/asd.bdef.gh D/AndroidRuntime﹕ Shutting down VM
01-08 16:19:31.977 15285-15285/asd.bdef.gh W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41c9d8b0)
01-08 16:19:31.977 15285-15285/asd.bdef.gh E/AndroidRuntime﹕ FATAL EXCEPTION: main
the given api address is not the real one, but the real one is reachable. I just turned off the WiFi to test error handling.
And one more use-case: If I add to the observable .onExceptionResumeNext([2nd observable]) than it goes to the 2nd observable, and it not crashes. But this is not the solution of the problem.
EDIT 2
ApiManager.login(userName, pass, new Observer<User>() {
#Override
public void onCompleted() { }
#Override
public void onError(Throwable e) {
DialogManager.showBasicErrorDialog(getApplicationContext(), e.getLocalizedMessage());
logger.showLog("Login Not ok");
e.printStackTrace();
}
#Override
public void onNext(User user) {
logger.showLog("login ok, user: " + user.getName().toString());
{...}
}
});
EDIT 3
FATAL EXCEPTION: main
rx.exceptions.OnErrorFailedException: Error occurred when trying to propagate error to Observer.onError
at rx.observers.SafeSubscriber._onError(SafeSubscriber.java:175)
at rx.observers.SafeSubscriber.onError(SafeSubscriber.java:97)
at rx.internal.operators.NotificationLite.accept(NotificationLite.java:144)
{...}
Caused by: java.lang.NullPointerException: Attempt to read from field 'rx.functions.Action0 rx.schedulers.TrampolineScheduler$TimedAction.action' on a null object reference
at rx.schedulers.TrampolineScheduler$InnerCurrentThreadScheduler.enqueue(TrampolineScheduler.java:85)
Thanks in advance for helping.
You don't have to build your own Observable with Retrofit, as Retrofit can directly return Observable:
http://square.github.io/retrofit/
Retrofit also integrates RxJava to support methods with a return type
of rx.Observable
#GET("/user/{id}/photo") Observable getUserPhoto(#Path("id")
int id);
(You won't have to handle errors by yourself)
Can you post the stacktrace of your crash ? As I think like you, that your application shouldn't crash.
It looks like you may be running into an issue has been fixed as of RxJava 1.0:
TrampolineScheduler NullPointerException