Catch all type exceptions programming Android - java

I'm developing an application for Android OS.
Since this is my first application, I think I've committed some programming mistakes cause I hardly can trace bugs back to their causes.
Thus, I was guessing, while i'm trying to fix bugs, is there a way to catch ALL types of exception in my entire activity lifecycle with one try-catch?
That would be awesome, i'm getting bored watching my galaxy S say :"Sorry the application App has stopped unexpectly" :(

I really, really don't recommend this...
try {
...
} catch (Exception e) {
// This will catch any exception, because they are all descended from Exception
}
Are you looking at your stack traces to debug your issues? It should not be hard to track them down. Look at LogCat and review the big block of red text to see which method caused your crash and what your error was.
If you catch all your errors this way, your program is not going to behave as expected, and you will not get error reports from Android Market when your users report them.
You can use an UncaughtExceptionHandler to possibly prevent some crashes. I use one, but only to print stack traces to a file, for when I'm debugging an app on a phone away from my computer. But I pass on the uncaught exception to the default Android UncaughtExceptionHandler after I've done that, because I want Android to be able to handle it correctly, and give the user the opportunity to send me a stack trace.

I'm assuming like pure java
try {
} catch(throwable t) {
}
But this is Very Bad Practice.
Also look at
Setting UncaughtException handler

If you're on Eclipse, every exception that Force-Closes the app (aka the message you mention) should be logged in the "LogCat".
The easiest way to see the LogCat, is to Open the DDMS perspective and clic on the LogCat tab (or open it from the "View" menu if it's not already displayed).

import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
public class SRSDexception implements Thread.UncaughtExceptionHandler {
private Thread.UncaughtExceptionHandler defaultUEH;
private Activity app = null;
public SRSDexception(Activity app) {
this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
this.app = app;
}
public void uncaughtException(Thread t, Throwable e)
{
StackTraceElement[] arr = e.getStackTrace();
String Raghav =t.toString();
String report = e.toString()+"\n\n";
report += "--------- Stack trace ---------\n\n"+Raghav;
for (int i=0; i<arr.length; i++)
{
report += " "+arr[i].toString()+"\n";
}
report += "-------------------------------\n\n";
// If the exception was thrown in a background thread inside
// AsyncTask, then the actual exception can be found with getCause
report += "--------- Cause ---------\n\n";
Throwable cause = e.getCause();
if(cause != null) {
report += cause.toString() + "\n\n";
arr = cause.getStackTrace();
for (int i=0; i<arr.length; i++)
{
report += " "+arr[i].toString()+"\n";
}
}
report += "-------------------------------\n\n";
try {
FileOutputStream trace = app.openFileOutput(
"stack.trace", Context.MODE_PRIVATE);
trace.write(report.getBytes());
trace.close();
} catch(IOException ioe) {
// ...
}
defaultUEH.uncaughtException(t, e);
}
}

Related

What is the reason of making try catch OutOfMemoryError and printStackTrace()?

I undesrstand the try-catch statement, it means that it will try a piece of code and if it fails the catch section will be executed. What I don´t undesrtand is to use printStackTrace of an error in the catch section. I mean, why it would be useful to make the following code:
try{
}
catch (OutOfMemoryError e) {
e.printStackTrace();
}
If the code that is in the try section fails, an out of memory error will be printed according to the above code. What is the reason of making that? Won`t an error automatically be printed on the Google Play Console if the app crashes (the code of the try function)? I don´t understand the reason of printing an error if the Google Play Console is actually printing the stack trace of errors without need of using the try catch function...
Real example of code that I don't understand why the try catch is used:
public void playMediaPlayer(int id) {
try {
if (mediaPlayer != null || mediaPlayer.isPlaying()) {
mediaPlayer.release();
mediaPlayer = new MediaPlayer();
}
if (id == 1) {
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.sound1);
} else if (id == 2) {
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.sound2);
}
if (PreferenceData.getSound(getApplicationContext())) {
mediaPlayer.start();
}
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
}
Nothing will automatically go to the Google Play Console because this will never crash. The catch will prevent the exception from crashing you and continue on. Which makes this dangerous code, unless you know what you're doing. Generally something like this would only be seen in code working with caches, where a failed allocation would cause you to kick data out of a cache and retry.
As for why you may want to do this- for debugging purposes. You may want to see when it happens and information about the allocation (such as how big it was) while debugging. It will only be for your personal use, as you'll never see the logcat of other devices.

Printing the output from a Bufferedreader to a TextView

i am currently programming an app that manly works as a console for receiving and sending messages to my socket server.
I want to output the messages that the server sent me to a textview.
My problem is that i am getting the following exception when changing the textview
W/System.err: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
My code:
public class SocketListener implements Runnable {
public static BufferedReader r;
public void run() {
try {
MainActivity.ausgabe.setText("Reading socket");
String message;
Boolean run = true;
while (run) {
if(r != null) {
MainActivity.ausgabe.setText("Reading line");
message = r.readLine();
MainActivity.ausgabe.setText("Line read");
if(message != null){
MainActivity.ausgabe.setText(message);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
As far as i have tested, the problem is in this line:
message = r.readLine();
because changing the textview before this line works perfekt, but after this line doesnt work (It prints the "reading line" but runs into the error when printing "line read")
I hope you can help me cause i couldnt find anything on the internet
Undead
When implementing interaction between Thread and Activity you should use Handler (info) or runOnUiThread (info).
I think the error throw is somehow delayed (because of multithreading) so you are seeing it after the view has actually changed. Probably there is another thread that checks for correct view manipulation and throws this error when discovers validation (I was unable to find exact info in Android docs).

I want to get application crash info in Android programmatically without using 3rd party apps or jars like bugsense etc

I have a webview based android application I want to get the crash report and store it into a text file but i am unable to find any programmatic native solution anywhere. I have read this article but I am unable to use it. I have no code because I dont know where to start
The best way to handle crash logs is creating an UncaughtExceptionHandler and handling it as per your requirement. Create a BaseActivity class and extend all the Activities with that and put this code stuff in the BaseActivity class.
private Thread.UncaughtExceptionHandler handleAppCrash =
new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread thread, Throwable ex) {
Log.e("error", ex.toString());
//send email here
}
};
Then just enable is inside onCreate() method of your BaseActivity by using
Thread.setDefaultUncaughtExceptionHandler(handleAppCrash);
I am catching un-handled exceptions by using this in my activity's onCreate():
mUEHandler = new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread t, Throwable e) {
try {
PrintWriter pw = new PrintWriter(new OutputStreamWriter(
openFileOutput(DMP_FILENAME, 0)));
e.printStackTrace(pw);
pw.flush();
pw.close();
} catch (FileNotFoundException e1) {
// do nothing
}
BaseActivity.this.finish();
}
};
Thread.setDefaultUncaughtExceptionHandler(mUEHandler);
This writes every unhandled exception in your app that happened on your activity to text file. Then you can analyze it.
Why don't you log every thing like Log.e("tag","msg") or else check the logcat for the crashes

How to retrieve error message in StringTemplate?

How can I retrieve a compile time error message from StringTemplate as a String?
This code for instance:
STGroup stg = new STGroup('<', '>');
CompiledST compiledTemplate = stg.defineTemplate("receipt", "<an invalid template<>");
if (compiledTemplate == null)
System.out.println("Template is invalid");
Will simply log something like "invalid came as a complete surprise to me", but I want to display this error message in my UI.
I can access the ErrorManager with stg.errMgr. I expected a method like getErrors() here, but there isn't...
You could set an error listener for the group, which would allow you to catch the error, and then pass it to the UI from there.
This answer tells you more about implementing an STErrorListener. The example they give doesn't compile since they're throwing checked exceptions from within the ErrorListener. Perhaps a better approach would be to handle the errors directly inside the listener, or you could just throw a RuntimeException so you could catch the errors when you call stg.defineTemplate(...).
public class MySTErrorListener implements STErrorListener {
...
#Override
public void compileTimeError(STMessage msg) {
// do something useful here, or throw new RuntimeException(msg.toString())
}
...
}
If you were to throw the RuntimeException you could then catch it when you define the ST:
stg.setListener(new MySTErrorListener());
try{
CompiledST compiledTemplate = stg.defineTemplate("receipt", "<an invalid template<>");
} catch (Exception e)
{
// tell the UI about the error
}

Java Me 8 raspberry pi - java.security.AccessControlException

I have the following simple code written in java-ME embedded:
public class JavaMEApplication2 extends MIDlet {
#Override
public void startApp() {
GPIOPinConfig config1 = new GPIOPinConfig(DeviceConfig.DEFAULT, 4, GPIOPinConfig.DIR_OUTPUT_ONLY,
DeviceConfig.DEFAULT , GPIOPinConfig.TRIGGER_NONE, true);
try {
GPIOPin pin = (GPIOPin) DeviceManager.open(config1);
Thread.sleep(2000);
pin.setValue(false);
pin.setDirection(GPIOPinConfig.MODE_INPUT_PULL_UP);
} catch (IOException ex) {
Logger.getLogger(JavaMEApplication2.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException ex) {
Logger.getLogger(JavaMEApplication2.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void destroyApp(boolean unconditional) {
}
}
The previous code run just fine (My LED is turned ON and OFF) until the execution reach this statement:
pin.setDirection(GPIOPinConfig.MODE_INPUT_PULL_UP);
The following exception occurs:
TRACE: <at java.security.AccessControlException: >, startApp threw an Exception java.security.AccessControlException:
My API permissions Configuration:
Can any one please tell me why this exception occurs? and if there's another way to toggle the same pin between OUTPUT Mode and INPUT Mode in java-Me embedded?
I am running into the same problem when i try and use the ADSONG AM2302 temp and humidity sensor, What I have done to avoid that is connect another pin with a pull up resistor to the current pin that is initially input/output and set one pin to output and one to input, it gets rid of the permission problem at least. The sensor is still not responding to my start signal though so this may have cause unforeseen problems
I think it may be failing because you had this parameter in the call to the GPIOPinConfig constructor:
GPIOPinConfig.DIR_OUTPUT_ONLY
Maybe try GPIOPinConfig.DIR_BOTH_INIT_OUTPUT instead.
Look here for the different values and their meanings:
https://docs.oracle.com/javame/8.0/api/dio/api/index.html
open your jwc_properties.ini file from /home/pi/javame8/bin directory inside raspberry pi and add:
authentication.provider = com.oracle.meep.security.NullAuthenticationProvider
under [internal] section

Categories