App crashes when dereferencing URI with Jsoup - android

After many tries, I decided to ask the question again. In my last question, someone said I should have a look at Jsoup. I wrote some code but it won't work. It's an android app. But it totally crashes. with the error message:
Unfortunately, (appname) has stopped
See the full error message
My code for extracting text from the <div>:
public void ButtonClick(View view) throws IOException {
Document doc = dereference("here is my url");
String text = extractContent(doc);
updateUI(text);
}
private Document dereference(String uri) {
Connection connection = Jsoup.connect(uri);
return connection.get();
}
private String extractContent(Document doc) {
Elements divs = doc.select("div.onlinestatus");
return divs.text();
}
private void updateUI(String text) {
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText(text);
}
the input from the url:
<html><!-- [...] --><body>
<div class='onlinestatus'>Server ist online! <br /></div>
</body></html>
Can someone spot the mistake?
Edit: when I perform all these operations in a separate thread, I get a different error. Error log and code can be found here.

This is not a Jsoup question after all.
If you look up the error from your error log (first line) where it reads
NetworkOnMainThreadException
Googling for "android NetworkOnMainThreadException" yiedls a page from the android developer reference, which states
The exception that is thrown when an application attempts to perform a networking operation on its main thread.
This would explain your previous attempts at moving code into a separate thread, which seemed to produce different results.
Have a look at the page suggested in the android developer reference, on Designing for Responsiveness. That should give you an answer.
The next thing that can fail, is that you need to do all UI changes in the thread that created the UI. The CalledFromWrongThreadException you got here tells you exactly what went wrong. Looking up that error will lead you to a question+answer similar to this one.
If you have problems with that, I suggest you ask a new question, if your problem is not already covered on StackOverflow (but I believe it is!)

Related

When even "try-catch" fails with System.AggregateException

I am getting the above error : System.AggregateException: One or more errors occurred.
With this line of code here:
List<tblDeviceIds> installIDs = KumulosHelper.Functions.Device.GetDeviceIDsOfUser(toUser);
The Method "GetDeviceIdsOfUser" looks like this:
public static List<tblDeviceIds> GetDeviceIDsOfUser(string username)
{
IDictionary<string, string> myDict = new Dictionary<string, string>();
myDict.Add("username", username);
return KumulosGeneral.getTblDeviceIds("getDeviceIDsOfUser", myDict);
}
So, there is really nothing fancy going on.
Sometimes, but only on CERTAIN users above error. So even when the user would be "null", which by the way he never is, the list would just return nothing. BUT instead it crashes. This itself is something I didnt quite understand, so what I did was:
List<tblDeviceIds> installIDs = null;
try
{
installIDs = KumulosHelper.Functions.Device.GetDeviceIDsOfUser(toUser);
}
catch
{
installIDs = null;
}
This would be a bullet prove workaround, but yet: It goes into try, it crashes, it never goes into catch, it is dead.
Would someone care to explain?
Thanks!
O, maybe this has something todo with doing this on another thread? This is the function that calls all that:
await Task.Run(() =>
{
Intermediate.SendMessageToUser(toUsername, temp);
});
As you can see, it is inside an async task... but that should not be a problem, right?
The reason you receive an AggregateException is because the exception is originating from within a Task (that is likely running on a separate thread). To determine the cause, walk the line of InnerException(s).
Regarding the catch not catching, my suggestions would be: Ensure the latest code is being used. Add Tracing instead of relying on breakpoints. And see if the inner exception is thrown from yet another thread (is GetDeviceIDsOfUser also using async?)
See also: Why is .NET exception not caught by try/catch block?

Best practices to avoid intermittent React Native/Android crashes in the render cycle (e.g. NullPointerException in UIImplementation.java)?

Users are seeing fatal crashes (generally a NullPointerException in UIImplementation.java:390) in various moments. They seem related to react-native-navigation transitions, but others have also reported them (issues #10755, #11524 at https://github.com/facebook/react-native/).
Other evidence is the existence of pull request #13994 and the following code in file ReactAndroid/src/main/java/com/facebook/react/uimanager/ShadowNodeRegistry.java:
public void addRootNode(ReactShadowNode node) {
// TODO(6242243): This should be asserted... but UIManagerModule is
// thread-unsafe and calls this on the wrong thread.
//mThreadAsserter.assertNow();
int tag = node.getReactTag();
mTagsToCSSNodes.put(tag, node);
mRootTags.put(tag, true);
}
Although it does look like a RN bug, it seems like it's a hot path and it's likely that something it's something in my code which is triggering the bug.
Are there practices which are likely to circumvent this issue, or antipatterns which usually lead to such errors (eg. failing to use immutability, etc)?

displaying runtime errors in android/ios installed app

I've been trying to get errors to display in a text field within the app for ease of error reporting from users.
I've had some success using this code I found on stackoverflow. It's used at the top level of the app but it's not working on device:
//start code
this.loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, errorHandler);
function globalErrorHandler(event:UncaughtErrorEvent):void
{
var message:String;
//check for runtime error
if (event.error is Error)
message = (event.error as Error).getStackTrace();
//handle other errors
else if (event.error is ErrorEvent)
message = (event.error as ErrorEvent).text;
else
message = event.error.toString();
//do something with message (eg display it in textfield)
myTextfield.text = message;
}
//end code
At first this wouldn't work on the device and I thought it was because upon the error, when developing on the pc, flashplayer would display the actionscript popup with the error. Which you would need to click "dismiss all" or close and then the globalErrorHandler was called after and then the error written to the textfield. I thought this is what was keeping it from showing up on the device. However, by adding event.preventDefault() I was able to suppress the actionscript popup when developing on the desktop and the error was written to the textfield successfully. This was not the case however on the andriod device. It still just hangs on the error. It's as if the default error event cannot be suppressed on android.
Thanks for your time. Any help appreciated!
EDIT 22/09/2017: I was able to see the error on device finally. It had to do with while on desktop publishing the error would be shown. However, on device the behavior was different and something was covering the textfield, by bring it to the front on error I was able to see it. However, I still see that some errors deeper in the class hierarchy are not being caught.
In our project we have it simpler (and it is working):
stage.loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, onUncaughtError);
private function onUncaughtError(e:UncaughtErrorEvent):void
{
// Console is basically a TextField for debug/diagnosis output.
if (e.error) Console.error(e.error.getStackTrace());
e.preventDefault();
}
The other thing you should probably check is whether your TextField actually displays any text at all for there might be text embedding issues, unrelated to the error handling routine.
UPD: Loading SWFs so it doesn't mix with the parent.
var request:URLRequest = new URLRequest(path);
var context:LoaderContext = new LoaderContext;
context.applicationDomain = ApplicationDomain.currentDomain;
var loader:Loader = new Loader;
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
loader.load(request, context);

Android: CalledFromWrongThreadException from WebView's shouldOverrideUrlLoading

I am developing on a library that is somehow getting a CalledFromWrongThread Exception crash on Samsung Galaxy S1 (api v7 - android 2.1). The code is something like this:
class MyWebViewClient extends WebViewClient {
#Override
public void shouldOverrideUrlLoading(WebView view, String url) {
someListener.addToUiView();
}
}
and of course, the method that is actually throwing the error (which implements a listener callback):
View v;
public void addToUiView(){
v.addView(new TextView(context)); //<-- this line is throwing the error on rare occasions
}
I'm skipping some code in between, but i'm not doing anything weird in other places. Also note: this crash only seems to have been happening a very very small % of the time. (not necessarily conclusive, as not everyone reports their data).
has anyone else come across this?? Is WebCore threading messing things up?
Now I haven't actually tested this but I am going to answer to the best of my knowledge. That said, my instinct is telling me that you are only seeing the error intermittently because web requests from a WebView (browser) happen with varying levels of asynchronicity and probably utilize a thread pool to accomplish this. Basically, sometimes it requests resources in parallel and sometimes it doesn't. Worse yet you might be seeing this error on only a single device because OEMs optimize OS level code (like the WebView internals) based on their preferences and opinions (especially Samsung). Either way the real problem is that you are doing something "UI related" in a place that is definitely not guaranteed to be "UI friendly"... That is, anywhere where you are getting a subsystem callback.
The solution to your problem is much more simpler than the explanation: just use your context (that I am assuming is an Activity)..
Activitys have a built in function called runOnUiThread(Runnable) that will guard the code inside the runnable from running on the wrong thread. Basically, your problem is really common and android has a built-in solution. runOnUiThread will only add overhead if required, in other words if your thread is the UI thread, it will just run the Runnable, if it isn't it uses the correct Handler (the one associated with the UI thread) to run the Runnable.
Here is what it should look like:
View v;
public void addToUiView() {
final Activity activity = (Activity) context;
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
v.addView(new TextView(activity));
}
});
}
i coded that up right inside the SO window so my apologies for any egregious errors, I hope that helps, and let me know if you need more info or of this doesn't solve your problem -ck

Error calling method on NPObject! in Android 2.2

I'm using addJavascriptInterface within my Android application to allow JavaScript to invoke functions I've created in my native Java application.
This worked well in Android 2.1, however in Android 2.2 I receive the error message "Error calling method on NPObject!"
When I instrument the method call the internals of the native method are getting called, however the exception is being throw in JavaScript.
I was getting this exact error:
Uncaught Error: Error calling method on NPObject!
Turns out I was attempting to invoke a JavascriptInterface function from a webview like so:
AndroidJS.populateField(field);
and on the Java side, the function didn't accept a parameter:
public void populateField() {}
Simply allowing the Java function to accept a parameter solved this error for me.
E.g.,
public void populateField(String field) {}
This may not be, and probably is not, the only reason this error could be thrown. This is simply how I resolved my specific scenario. Hope this helps! :)
OK, I have same problem as well, just in today.
What I did is putting code in UI Thread, like code below :
/**
* 給網頁Javascript呼叫的method
* Method for Javascript in HTML
* #param java.lang.String - Playlist ID
*/
public int callListByPID(final String pId)
{
Log.i(Constants.TAG, "PAD Playlist ID from HTML: "+pId);
runOnUiThread(new Runnable()
{
public void run()
{
// Put your code here...
}
});
return 1;
}
This solved my problem, and hope it can help some body... :-)
In my experience this problem is caused by Javascript interfaces bringing back objects that Javascript doesn't automatically identify.
In Android this is caused by wrappers like Boolean or Long in comparison to their native versions boolean and long.
//This will fail
public Long getmyLongVal() {
return 123456789;
}
//This will work
public long getMyNativeLongVal() {
return 123456789;
}
So remove your wrapper classes to any methods being used by Javascript if you want to avoid NPObject errors.
Here's a twist I found on this problem that could be useful for some of the folks running into this problem (and it likely explains intermittent failures that seem to defy explanation)...
If any exceptions are thrown (and not caught) in the return handler code prior to allowing the javascript interface callback to return clean, it will propagate back as a failed call and you will also get this error - and it would have nothing to do with missing functions or parameters.
The easiest way to find this case (whether or not you use this in your final implementation) is to push whatever handler code you have back onto the UI thread (the callback will not be on the UI thread) - this will allow the callback to return clean and any subsequent exceptions that occur will propagate properly up until you catch them or until the app crashes. Either way you will see exactly what is really happening. Otherwise the uncaught exception passes back to javascript where it will not be handled or reported in any way (unless you specifically built error trapping code into the JS you were executing).
Good Luck All.
bh
I had the same problem with Javascript-to-Java interface (WebView.addJavascriptInterface).
In Android 2.1 everything worked just fine but in Android 2.2 Javascript failed to call methods from this interface. It returned an error: Uncaught Error: Error calling method on NPObject!
It seems that on Android 2.2, the WebView has problem with Boolean data type returned from interface functions.
Changing:
public Boolean test_func() { return true; }
... to:
public int test_func() { return 1; }
... solved the problem.
This I believe is no longer supported anymore ( Always game NPObject error ) .
Please refer to the answer in this thread
Visit open an activity from a CordovaPlugin

Categories

Resources