I found the "Add Java Exception Breakpoint" menu item but it only seems to work on the exact exception type that I select. So if I ask it to break on Exception, it does not break in case of a NumberFormatException. How do I make it break for all exceptions?
My activity is exiting for no apparent reason with no LogCat output, so it would be nice to find out about any exceptions that are occurring, whether caught or uncaught and whether in my code or just in Android.
create an exception breakpoint for java.lang.Throwable (which is the most specific superclass of all exceptions - unlike Exception, it also matches instances of Error)
right-click it, choose properties, and check "subclasses of this exception"
You should be able to do this using the pattern matching it specifies in the window. Specifically, * will match any string (including the empty string) so *Exception* will match all strings which contain the substring Exception in them, including the string Exception itself and strings which have Exception at the very beginning or very end.
Related
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.
I am trying to develop an application that requires the ability to capture screen content. I'm targeting lollipop to avoid the requirement for root. When trying to get an instance of the MediaProjectionManager via a call to getSystemService() I am getting the following error reported in Android Studio:
Must be one of: Context.POWER_SERVICE, Context.WINDOW_SERVICE, Context.LAYOUT_INFLATER_SERVICE, Context.ACCOUNT_SERVICE, Context.ACTIVITY_SERVICE, Context.ALARM_SERVICE, Context.NOTIFICATION_SERVICE, Context.ACCESSIBILITY_SERVICE, Context.CAPTIONING_SERVICE, Context.KEYGUARD_SERVICE, Context.LOCATION_SERVICE, Context.SEARCH_SERVICE, Context.SENSOR_SERVICE, Context.STORAGE_SERVICE, Context.WALLPAPER_SERVICE, Context.VIBRATOR_SERVICE, Context.CONNECTIVITY_SERVICE, Context.WIFI_SERVICE, Context.WIFI_P2P_SERVICE, Context.NSD_SERVICE, Context.AUDIO_SERVICE, Context.MEDIA_ROUTER_SERVICE, Context.TELEPHONY_SERVICE, Context.CLIPBOARD_SERVICE, Context.INPUT_METHOD_SERVICE, Context.TEXT_SERVICES_MANAGER_SERVICE, Context.DROPBOX_SERVICE, Context.DEVICE_POLICY_SERVICE, Context.UI_MODE_SERVICE, Context.DOWNLOAD_SERVICE, Context.NFC_SERVICE, Context.BLUETOOTH_SERVICE, Context.USB_SERVICE, Context.INPUT_SERVICE, Context.DISPLAY_SERVICE, Context.USER_SERVICE, Context.PRINT_SERVICE less... (Ctrl+F1)
Reports two types of problems:
* Supplying the wrong type of resource identifier. For example, when calling Resources.getString(int id), you should be passing R.string.something, not R.drawable.something.
* Passing the wrong constant to a method which expects one of a specific set of constants. For example, when calling View#setLayoutDirection, the parameter must be android.view.View.LAYOUT_DIRECTION_LTR or android.view.View.LAYOUT_DIRECTION_RTL.
I am currently at a loss as to why this constant is not considered valid, it's there as an autocomplete option, so it's present, and it's shown in all sample code I have seen for screen capture in lollipop. I have verified that the project setup specifies Android SDK 21 as min and target. Is there something else obvious/stupid I might be missing that would cause this error?
UPDATE: Took the exact same code to Eclipse and it works without issue. So this is related to something in Android Studio specifically it seems.
I get this error while getting Context.BLUETOOTH_SERVICEand the error doc (Must be one of..) contains Context.BLUETOOTH_SERVICE though.
This is not the way Android Studio "1.2" should work. :#
Anyway, its an Inspection bug, Constant and Resource Type mismatch (How in the hell Bluetooth is a resource in android context).
You can suppress this for Class/Method/Statement, for statement, add #SuppressWarnings("ResourceType") above or before the statement.
Another approach:
Goto Settings>>Editor>>Inspection>>Android>>Constant and Resource Type Mismatches and make the severity to anything but Error, probably Warning or Weak Warning.
(Though it fixes the error issue, but I want this mismatch to be an error when it really happens.)
Run into the same problem, it is so strange, there are no any other threads talking about this problem.
Well, actually you can just ignore this error and still run the program, even with
the red marks on it
In the Android Open Source Project's code style, it states that we shouldn't use System.out.println() but I don't understand why. Can anyone explain? What should I use to trace my app's log?
Here's the line for reference:
System.out.println() (or printf() for native code) should never be used. System.out and System.err get redirected to /dev/null, so your print statements will have no visible effects. However, all the string building that happens for these calls still gets executed.
You should use the android.util.Log class.
Here's a description of what the Log class does:
API for sending log output.
Generally, you should use the Log.v(), Log.d(), Log.i(), Log.w(), and Log.e() methods to write logs. You can then view the logs in logcat.
The order in terms of verbosity, from least to most is ERROR, WARN, INFO, DEBUG, VERBOSE. Verbose should never be compiled into an application except during development. Debug logs are compiled in but stripped at runtime. Error, warning and info logs are always kept.
These are the available methods of the Log class:
Log.d() - Send a DEBUG log message.
Log.e() - Send an ERROR log message.
Log.i() - Send an INFO log message.
Log.v() - Send a VERBOSE log message.
Log.w() - Send a WARN log message.
Log.wtf() - What a Terrible Failure: Report an exception that should never happen.
The methods above (with the exception of Log.w and Log.wtf which have 3 possible patterns of arguments) require the following arguments:
String tag, String msg:
tag: Used to identify the source of a log message. This value may be null.
msg: The message you would like logged. This value may be null.
String tag, String msg, Throwable tr - Similar to the first pattern, but allows for an exception to be specified. This pattern should be used if you want to log an exception to the log output.
(For Log.w and Log.wtf) String tag, Throwable tr Similar to the third pattern, but does not allow for a message to be specified. Note that you can still pass a message but it should be in the second arrangement of arguments.
EDIT: Going straight to answer your question: println() of System.out and System.err will still be displayed in logcat but with limitations.
You can't log VERBOSE, ERROR, or DEBUG using System.out or System.err.
You can't define your own tag, it will display System.err or System.out with your text. For instance:
System.out.println("Hello!") is equivalent to Log.i("System.out","Hello!")
System.err.println("Hello!") is equivalent to Log.w("System.err","Hello!")
System.out.println("") in android will not run well because there is no Terminal that the app is corrected to.
You would be better off using Log.(d)(v)(e)(i)(w), because there is something actively monitoring LogCat.
System.out.println() will print to LogCat, but only after an additional set of System instuctions, making it not as efficient, however, as i said, it still works.
if we want to trace the android project
we can do it using Log class
there is some methods like
Log.e(TAG,MESSAGE)
Log.v(TAG,MESSAGE)
Log.w(TAG,MESSAGE)
Log.d(TAG,MESSAGE)
Log.i(TAG,MESSAGE)
its a static method of Utils package. put it line by line and u can watch it in the LogCat..
thats at enjoy with android
From your own link:
System.out.println() (or printf() for native code) should never be
used. System.out and System.err get redirected to /dev/null, so your
print statements will have no visible effects. However, all the string
building that happens for these calls still gets executed.
In addition, at the beginning of that page, it says:
The rules below are not guidelines or recommendations, but strict
rules. Contributions to Android generally will not be accepted if they
do not adhere to these rules.
So DON'T do it!
You can use the built in Log utility that will print right out to the LogCat.
You can use Log.e(String, String) for errors which will appear in red. There is also v, d, i, and w for verbose, debug, info, and warning respectively.
The following should do the trick to print the exception
1. Log.d("myapp", Log.getStackTraceString(new Exception()));
or
2. You can get longer stack traces by digging deeper. For example:
Log.getStackTraceString(e.getCause().getCause());
Log is the best way to trace our android project
like following code...
it will help u...
just look in DDMS logCat that how exactly project is build...
requirement... android.utils.Log; package is used..
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for(int i=0;i
{
Log.e("i = ",""+i);
Log.v("i = ",""+i);
Log.i("i = ",""+i);
Log.w("i = ",""+i);
Log.d("i = ",""+i);
}
}
i hope it will help u
I was going through following tutorial: http://www.dreamincode.net/forums/topic/190013-creating-simple-file-chooser/#viewSource
Inside the FileChooser class there is one exception beeing supressed, since there is nothing within the catch clause. So I decided to add following statement to the catch clause:
Log.e(ACTIVITY_SERVICE, e.getCause().toString());
For some reason this always causes the app to crash (NullPointerException). When I don't do any logging, except for a a simple syso print, then I don't get any exception and the app does't crash either. Then it works fine. I'm new to the whole Android Framework and just want to understand why this is happening.
Thanks to Ingo's and CommonsWare's hints I came to the conclusion, that following line caused the exception:
EDIT:
In fact it was the start of the foreach loop, which iterates over all subdirectories and files of a given directory. I didn't know, that this would cause a NPE, if the list you want to iterate on is actually null. For some reason I thought that the loop would be automatically skipped in this case.
My logcat window in Eclipse only displays the first few lines of the StackTrace for each exception. This means that I often can't see where an exception occured. Is there any way to change this setting?
If you're referring to the "...12 more lines..." part, you only see that for exceptions that were the cause of another exception. If the top part of the stack trace is the same as the earlier trace, the full set of frames is only shown for the outermost exception, and the other traces get the "..." treatment.
Put another way, the chunk of a trace that isn't shown is a duplicate of a trace that appeared earlier in the exception cause chain. For example, suppose I have code where the method main() calls one(), which calls two(), and so on. four() throws an exception. two() catches it and re-throws it. The exception will look like this:
java.lang.RuntimeException: re-throw
at Foo.two(Foo.java:14)
at Foo.one(Foo.java:7)
at Foo.main(Foo.java:3)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.RuntimeException: first
at Foo.four(Foo.java:23)
at Foo.three(Foo.java:19)
at Foo.two(Foo.java:12)
... 3 more
The "caused by" exception says "... 3 more" rather than explicitly listing one(), main(), and dalvik.system.NativeStart.main. So to get the full trace of the initial exception, you would start by reading its trace, then continue at the trace above.
Note there is no overlap -- two() appears in both, but in the "first" trace it's on the call to three(), and in the "re-throw" trace it's on the throw instruction.
you can overload all the log methods (log.d, log.i, log.e, etc) with (String tag, String msg, Throwable tr) parameters, where the third parameter is the exception. This will give you the full stacktrace in logcat
http://developer.android.com/reference/android/util/Log.html
If your code calls a method which produces too tall of stack you can (and should) handle the exception in your code and output whatever is relevant to logs.
If you have no exception handling whatsoever and you don't even know where in your code should you be putting such a handler then the problem is entirely elsewhere - you should be handling exceptions a bit better than that.