I have created a thread in java that does some processing passes the data to legacy C++ using JNI. The C++ code performs some tasks on a separate thread and then returns, at this point I want to callback from JNI into the Java thread rather then the main interface thread. The code seems to build and run without errors, but when CallVoidMethod is called to call back into Java nothing happens, no exceptions or errors, it does seem to invoke the Java code.
I am calling AttachCurrentThread which seems to work and detach at the end, the calls to find the method all seem to succeed. Has anyone got any ideas or have I got the wrong idea?
There is no silver bullet to fix such problem; you could have any of the miriad little things go wrong. I would suggest to start counterintuitively with some code that does not work. Set the method ID deliberatly wrong; see how the system behaves differently. Set the object reference (or class reference, if it is a static method) to an unexpected object, or a non-existing object; see what happens when the object reference is not globalized... You've got the idea.
Related
I am developing an Android app (It doesn't matter though) using RxJava2, and in some singleton there are some PublishProcessors.
And there are a lot of .onNext() calls on these PublishProcessors all over the project.
Now in order to debug, I need to know, on every .onNext() called, which line in my project invoked this .onNext().
Is there a way in RxJava(2) that I can achieve this?
I think you can use Frames tab in Debug menu.
For example, in this case, MainActivity line 18 trigger onNext
Ah, thanks to #PhanVanLinh, I found a solution that worked for me.
(Actually it has pretty much nothing to do with RxJava...)
You just need to print the stacktrace using Thread.currentThread.stackTrace and print it to your own string inside doOnNext(), but remember to do it before .observeOn() so that the thread won't switch, it must stay at the original thread that called .onNext(), otherwise you won't get meaningful information.
Then you will know which line that called .onNext().
I am new to android development. In the overriden onCreate() method of my activity, I perform some operations. For ex. check if SharedPreference is already available and then route to other activity. How do I perform exception handling on this onCreate() method. Is it the right way to wrap the contents in a try catch and display the error dialog on exception?
If the exceptions are not handled properly, in my case the onCreate() method, the app crashes with message:
Unfortunately your application stopped working
On searching in the internet, I found that UncaughtExceptionHandler could be used to handle it. Any sample implementation and how to call it from all my activities would be helpful.
THat's the wrong way to go about it. Instead, go into your logcat. Read the stack trace of the exception. Figure out what you did wrong. Fix it. Just catching exceptions is a horrible practice unless you're catching a specific exception for a specific reason- its very unlikely your app is in a state where it can continue correctly. Don't be lazy, track down your bug and fix it.
With something like this you can catch a generic Exception in your onCreate() method:
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
try {
// do whatever you need
} catch (Exception e) {
e.printStackTrace();
}
}
Exception catching can be used with many goals. An interesting one is to catch particular expected exceptions to fix some problems (for example setting a generic value into a variable otherwise null after occurring an error).
The general purpose however is to avoid that an error causes a problem or in the worst case a crash of your application. Depending oh what kind of software you are developing, a crash may represents a little problem (like in an Android app), a very big one (like in airplane's softwares or power plants' softwares).
We can identify two kind of exceptions.
The first type are those exceptions specific to definite problems. They have to be declared into methods signature, so you are encouraged or obbligated to manage these exceptions and their relative problems. These exceptions represent an error that should probably occur during particular code execution, like a parsing error, or an input output error. For this type of problems we have particular exceptions, to catch and easily manage them (for example as previously said to init a variable with a default value after an error).
The second type of those exception represents instead some generic problems that can occur during program execution. They are a big and generic set and generally their probability of occurring is low. For this reason you are not obbligated to manage them. The main example of this type is the general Exception class.
So an catching an Exception is not the right approach to solve a bug, as suggested by Gabe Sechan.
Catching a generic Exception in the main() Java method can be a way, for example, to show a default human readable error to the user if nothing else is available.
Or could be a way to keep the failing of the current operation reducing crash probability.
Now, in Android we can't act directly on the main() method. onCreate() method is executed and exited so catching here a generic Exception has no much sense. Obviously it depends also on what you do in your onCreate() method and what you want to do if an error occurs. You could do some strange stuff (is very defined what you should do in the onCreate() method) and you could need to manage a big set of problems only showing an error, so it has more sense catch only a generic Exception than a lot of particular exceptions to make the same thing in each catch block.
If you want to achieve this goal (a message showed for all the errors occurred during onCreate() execution, made Activity by Activity) this is the right approach.
If instead what you want to achieve is to intercept all of the errors that are generated during all of your app execution, a good approach could be the UncaughtExceptionHandler, that act similarly to catch a generic Excepetion into a Java main() method. At this level an interesting approach is described here.
For more infos about exceptions you can read this and this.
Here is the link of the Minesweeper project on codeproject.com.
I just wanted to ask one thing here. I completely understood the logic and algorithm this guy used, but when he called the showMineField() method inside startNewGame() method , he called it after createMineField(). I am really confused! Shouldn't the layout be set before setting up mines and handling the user click events? But the code seems to work fine. If I just call showMineField() inside startNewGame() , it gives me NullPointerException.
This is because you cannot show a mine field before creating all the objects.
It is like trying to run without legs. If you call showMineField() that is using objects that have not been initialized. Thats why you are recieving a NUllPointerException. Nullpointer is throws when a method is trying to be call on an object that has not been created yet. createminefield() initialzes everything so that nullpointer is not thrown
I have a question about accessing objects on the main thread from another thread. There seems to be a lot of information about it online with techniques to do that but everything I found applies to accessing Views on the UI thread. It may be that all those techniques also apply for objects other than View but I would just like to make sure.
For my concrete example I have a custom BluetoothDeviceConection class I wrote and contains functions like connect, closeConnection, write and so on. So functions for managing a connection to a specific BluetoothDevice which is passed as a parameter to BluetoothDeviceConection's constructor. On my main thread I create three BluetoothDeviceConection objects for three devices. Now I want to connect to all three devices.
My idea is to send the BluetoothDeviceConection object of a device to a new thread, let it connect to that device and write data to it, thereby manipulating / modifying / accessing the passed BluetoothDeviceConection object. To make this thread safe everyBluetoothDeviceConection object would be created with the volatile keyword.
Is that the correct way to go?
I am doing a similar thing with a TimerTask in which I call an "outside" function marked as synchronized and everything works fine.
Thank you in advance for all your help.
Cheers!
No, volatile does not guarantee thread safeness by itself. volatile only tells compiler this value can be changed from multiple threads so it doesn't apply optimizations based on static code analysis. If you want it to be thread-safe, you need to use synchronized as you said for TimerTask or other methods (locks, semaphores, mutexes...) to make sure only one thread is accessing it at any given time.
I also suggest that instead of passing the BluetoothDeviceConection as a parameter to other classes, you wrap this object inside another class and write thread-safe methods for manipulating it.
Same as with TimerTask your own class will work fine
I have an implementation of WallpaperService.Engine that uses JNI to create a C++ renderer:
Engine (Java) -> Renderer (C++)
If the renderer was Java code I could simply state
private Renderer renderer = new Renderer();
to make sure the renderer was created with my Engine and destroyed automatically when it's not needed any more. So what is the cleanest way to do this?
P.S.: I was thinking:
int rendererId = createNativeRenderer();
...
draw(rendererId); // call all native renderer methods specifying the object id
...
deleteNativeRenderer(rendererId);
But it's not very elegant since it requires explicit deletion, which is easy to forget.
Yes it's not very elegant, but it's by far the most reliable way. Java tries to be a hammer for every nail, so there is this thing called finalizer - an Object method called upon garbage collecting your instance. So it ideally does exactly what you need but practically better be avoided. If you read the related Javadoc carefully, you'll find out that:
Your precious renderer deleting code will be called not when you or your code thinks it's appropriate, but when the reference counting engine decides. And even worse, not at that specific point, but at any time later.
You can't know and you can't influence, which thread will call the finalizer. A double barrel shot in the foot if the code is related to UI operations (i understand that your code is).
Though, you can use finalizer for a safety check.
wrap the renderer lifecycle (create/use/delete) in an object with public method for deleting
upon explicit deleting, set an internal flag
override finalize() and check the flag state there. If not marked as deleted, log nasty error