Highly recommended article: Welcome to collect Android dry goods to share

##### Read five minutes, 10 o ‘clock every day, and learn for life with you. This is Android programmer

Exception is often encountered in Android, so when we encounter exceptions, how to solve them? This article will give examples to solve some of the exceptions encountered in Android.

Here’s what you’ll learn from this article

  1. NullPointerException null pointer
  2. ClassCastException Type conversion exception
  3. Abnormal IndexOutOfBoundsException subscript crossing the line
  4. ActivityNotFoundException Activity was not found abnormal
  5. IllegalStateException The illegal state is abnormal
  6. Abnormal ArrayIndexOutOfBoundsException an array
  7. SecurityException SecurityException
  8. IllegalArgumentException: Service not registered Service unregistered anomalies

1. NullPointerException null pointer

NullPointerException is often encountered in development. For example, NullPointerException will be caused when the referenced object is empty or the array is empty. If it is not handled in time, the application Crash will be caused.

1. The array NullPointerException

Cannot assign a length to a null array element, otherwise NullPointerException is declared: Attempt to write to NULL array Attempt to get length of NULL array

Array NullPointerException code example

	public static void ArrayNullPointer() {/** * NullPointerException ** 1. * */ int[] array = null; // 1. NullPointerException: Attempt to get length of null array int length = array.length; // 2. NullPointerException: Attempt to write to null array array[0] = 1; }Copy the code

Array NullPointerException Log example

  • The Log information is as follows

A NullPointerException is generated by obtaining an empty array length:

12-27 17:17:44. 627 8839 8839 E AndroidRuntime: under Caused by: Java. Lang. NullPointerException: Attempt to Get Length of NULL array 12-27 17:17:44.627 8839 8839 E AndroidRuntime: At com. Programandroid. Exception. NullPointerException. ArrayNullPointer / / produce null pointer lines of code (NullPointerException. Java: 32)Copy the code

Log analysis is as follows

An empty array cannot fetch the subscript content, which would result in a NullPointerException

12-27 17:23:24. 168 11649 11649 E AndroidRuntime: under Caused by: Java. Lang. NullPointerException: Attempt to Write to NULL array 12-27 17:23:24.168 11649 11649 E AndroidRuntime: At com. Programandroid. Exception. NullPointerException. ArrayNullPointer (NullPointerException. Java: 34) 12-27 17:23:24. 168 11649 11649 E AndroidRuntime: at com.programandroid.Exception.ExceptionActivity.NullPointerException(ExceptionActivity.java:37)Copy the code

Log analysis is as follows

    1. ObjectobjectNullPointerException

Attempt to invoke a virtual method on a null object reference The following code may cause a null pointer exception.

Object NullPointerException code example

A simple code example is as follows:

	public static void ListNullPointer() {

		ArrayList<String> mArrayList = null;
			mArrayList.size();
	}
Copy the code

Object NullPointerException log example

  • Log information is as follows:
12-27 17:28:22. 565 12725 12725 E AndroidRuntime: under Caused by: Java. Lang. NullPointerException: Attempt to invoke a virtual method on a null object Reference 12-27 17:28:22.565 12725 12725 E AndroidRuntime: At com. Programandroid. Exception. NullPointerException. ListNullPointer (45) NullPointerException. Java: 12-27 17:28:22. 565 12725 12725 E AndroidRuntime: at com.programandroid.Exception.ExceptionActivity.NullPointerException(ExceptionActivity.java:37)Copy the code

Object NullPointerException Log analysis is as follows:

NullPointerException solution

    1. Check whether the object is null. The following is an example to avoid null Pointers:
	public static void ListNullPointer() {

		ArrayList<String> mArrayList = null;
		if (mArrayList != null) {
			mArrayList.size();
		}
	}
Copy the code

    1. usetry-catchCatch the exception thrown

A try-catch can catch a thrown exception and keep the application from crashing, but this does not solve the root of the problem and can cause some puzzling problems.

	public static void ListNullPointer() {
			try {
				ArrayList<String> mArrayList = null;
				mArrayList.size();
			} catch (Exception e) {
				// TODO: handle exception
			}
	}

Copy the code

    1. The ultimate solution, optimize the code logic, fundamentally solve the problem.

2. ClassCastException Type conversion exception

ClassCastException: This exception occurs during type conversion and is not reported by the compiler during compilation, but may cause the app to crash if it exists during runtime. For example, a ClassCastException occurs when a parent class is cast to a subclass

1. The following code causes a ClassCastException

ClassCastException code example

Do not cast a parent class to a subclass; otherwise, a ClassCastException will occur.

public void ClassCastExample() { Fruit banana = new Fruit(); /** * ClassCastException * * 1. Cast here, can lead to app compilation sure, run off, under Caused by: * Java lang. ClassCastException: * com.programandroid.Exception.ExceptionActivity$ Fruit cannot be cast * to com.programandroid.Exception.ExceptionActivity$Apple* ***/ Apple apple = (Apple) banana; } /** * ClassCastException * * 2. Strong reversal here causes app crashreturn (Apple) banana;
	 * */
	public Apple isRight() {
		Fruit banana = new Fruit();
		return (Apple) banana;
	}

	class Fruit {
		public Fruit() {
		}
	}

	class Apple extends Fruit {
		public Apple() {}}Copy the code

ClassCastException Log for

ClassCastException usually prints information similar to the following

Caused by: java.lang.ClassCastException:
com.programandroid.Exception.ExceptionActivity$
Fruit cannot be cast to com.programandroid.Exception.ExceptionActivity$Apple
Copy the code

ClassCastException Log analysis

ClassCastException solution

Use try-catch to catch exceptions, or fix the root problem from the code.

2. Android Phone Settings ClassCastException solution

Examples are used to better resolve exceptions in development. For example, when you use the Monkey to test the Settings module in development, the ClassCastException is displayed, and the Settings code is too much to read. In this case, a try-catch is also a good option. For example, when monkey tests some platform code, it raises the following exception

Settings ClassCastException Log example

  • Log information is as follows:
FATAL EXCEPTION: ApplicationsState.Loader 01-05 03:36:56.101 6304 6941 E AndroidRuntime: Process: Com. Android. Settings, PID: 6304-05 03:36:56. 01, 101, 6304, 6941 E AndroidRuntime: Java. Lang. ClassCastException: com.android.settings.datausage.AppStateDataUsageBridge$DataUsageState 
												   cannot be cast to com.android.settings.notification.NotificationBackend$AppRow01-05 03:36:56. 101 6304 6941 E AndroidRuntime: at the android. Settings. Applications. AppStateNotificationBridge$3.filterApp(AppStateNotificationBridge.java:110)
Copy the code

Settings ClassCastException Log analysis

Setting Crash ClassCastException

3. IndexOutOfBoundsException subscript cross-border anomalies

List of development is often used, then the errors of using the subscript, will lead to abnormal IndexOutOfBoundsException cross-border. The following code will cause IndexOutOfBoundsException anomalies

IndexOutOfBoundsException code, for example,

IndexOutOfBoundsException Log for

  • Log information is as follows:
12-27 17:41:24. 231 16891 16891 E AndroidRuntime: under Caused by: Java. Lang. IndexOutOfBoundsException: Index: 0, the Size: 0 12-27 17:41:24.231 16891 16891 E AndroidRuntime: At java.util. Arraylist. get(arraylist. Java :411) 12-27 17:41:24.231 16891 16891 E at com.programandroid.Exception.IndexOutOfBoundsException.isAppOnRecent(IndexOutOfBoundsException.java:40) 12-27 17:41:24.231 16891 16891 E AndroidRuntime: at com.programandroid.Exception.ExceptionActivity.IndexOutOfBoundsException(ExceptionActivity.java:80)Copy the code

Log analysis is as follows:

IndexOutOfBoundsException solution

Determine if the object content is 0 when used.

4. ActivityNotFoundException

ActivityNotFoundException common in Eclipse development of Android, Android studio has help to automatically generate the Activity, as well as the layout file. The main reason is not in AndroidMainfest. Registered in the XML file, if not registered, will cause the app crash, crash log as follows: ActivityNotFoundException: Unable to find explicit activity class

ActivityNotFoundException code, for example,

For example, the following code causes this exception

ActivityNotFoundException Log for

  • Log information is as follows:
12-27 17:46:05. 994 17893 17893 E AndroidRuntime: under Caused by: android. Content. ActivityNotFoundException: Unable to find explicit activity class {com.programandroid/com.programandroid.Test.TestActivity}; have you declared this activityin your AndroidManifest.xml?
12-27 17:46:05.994 17893 17893 E AndroidRuntime: 	at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1810)
Copy the code

Log analysis is as follows:

ActivityNotFoundException solution

Just register with AndroidMainfest.xml

5. IllegalStateException

IllegalStateException An illegal status exception is caused by an illegal code status in the software. The following code causes an IllegalStateException. This exception occurs when a Button control declares Android :onClick=”IllegalStateException” but is not used in Java code.

IllegalStateException code example

An IllegalStateException Log for

  • Log information is as follows:
12-27 16:07:41.158 1715 1715 E AndroidRuntime: FATAL EXCEPTION: main 12-27 16:07:41.158 1715 1715 E AndroidRuntime: FATAL EXCEPTION: main 12-27 16:07:41.158 1715 1715 E Process: com. Programandroid, PID: 1715-27 16:07:41. 12, 158, 1715, 1715 E AndroidRuntime: Java. Lang. An IllegalStateException: Could not find method IllegalStateException(View)in a parent 
												or ancestor Context for android:onClick attribute defined on view class 
												android.widget.Button with id 'btn_on_click'
12-27 16:07:41.158  1715  1715 E AndroidRuntime: 	at android.view.View$DeclaredOnClickListener.resolvemethod (view.java :4781) 12-27 16:07:41.158 1715 1715 E AndroidRuntime: at android.view.view$DeclaredOnClickListener.onClick(View.java:4740)
Copy the code

IllegalStateException Log analysis is as follows:

IllegalStateException solution

The IllegalStateException class has many exceptions. Different code has different solutions. The examples are as follows

6. Abnormal ArrayIndexOutOfBoundsException array bounds

Array is often used in the code, when applicable array subscript is not at the time, will appear ArrayIndexOutOfBoundsException. For example, if the array length is 4 and you want to reference an element with index 5, you will crash.

ArrayIndexOutOfBoundsException code, for example:

	public static void ArrayIndexOutOfBounds() {

		String[] mStrings = { "a"."b"."c"."d" };
		String testsString = mStrings[5];
	}
Copy the code

ArrayIndexOutOfBoundsException Log example:

  • Log information is as follows:
12-27 17:51:15. 420 19185 19185 E AndroidRuntime: under Caused by: Java. Lang. ArrayIndexOutOfBoundsException: length = 4; Index =5 12-27 17:51:15.420 19185 19185 E AndroidRuntime: at com.programandroid.Exception.ArrayIndexOutOfBoundsException.ArrayIndexOutOfBounds(ArrayIndexOutOfBoundsException.java:20 ) 12-27 17:51:15.420 19185 19185 E AndroidRuntime: at com.programandroid.Exception.ExceptionActivity.ArrayIndexOutOfBoundsException(ExceptionActivity.java:105) 12-27 17:51:15.420 19185 19185 E AndroidRuntime:... 11 moreCopy the code

ArrayIndexOutOfBoundsException Log analysis is as follows:

ArrayIndexOutOfBoundsException solution

    1. Use array subscripts correctly
    1. If you are not sure about the length of the array, obtain the length first and then determine whether the subscript is greater than or equal to the length of the array.
    1. Try-catch traps exceptions and prevents crash, but it cannot fundamentally solve the problem.

7. SecurityException SecurityException

SecurityException is a common SecurityException on Android. It is mainly caused by the Android security mechanism. In order to manage the application’s access to sensitive information on the phone, the Android security mechanism specifies that This must be declared in the androidMainfest.xml file. Moreover, after Android 6.0, access to sensitive information of mobile phones requires dynamic permission application, and only after user authorization can access sensitive information of mobile phones.

Example SecurityException code

Obtain the sensitive information of mobile phone IMEI number

/ * * * * <! -- Device permission to read mobile IMEI --> * * <uses-permission Android :name="android.permission.READ_PHONE_STATE" />
	 * */
	public static String getIMEI(Context context) {
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		String deviceId = tm.getDeviceId();
		if (deviceId == null) {
			return "UnKnown";
		} else {
			returndeviceId; }}Copy the code

SecurityException log for

12-27 18:05:55. 663 21467 21467 E AndroidRuntime: under Caused by: Java. Lang. SecurityException: getDeviceId: 12-27 18:05:55.663 21467 21467e Neither user 10117 nor current process has android.permission.READ_PHONE_STATE AndroidRuntime: at the android OS. Parcel. ReadException (1683) Parcel. Java: 12-27 18:05:55. 663, 21467, 21467 E AndroidRuntime: . An android OS. Parcel. ReadException (1636) Parcel. Java: 12-27 18:05:55. 663, 21467, 21467 E AndroidRuntime: at com.android.internal.telephony.ITelephony$Stub$Proxy.getDeviceId(ITelephony.java:4281)
Copy the code

SecurityException log analysis

SecurityException solution

Before Android 6.0, apply for permissions in AndroidMainfest.xml. After Android 6.0, apply for permissions dynamically.

8. IllegalArgumentException: Service not registered Service unregistered anomalies

The following error message is displayed:

01-30 09:10:26. 257 23681 23681 W System. Err: Java. Lang. IllegalArgumentException: Service not registered: com.programandroid.Exception.ExceptionActivityThe $1@5f3161e 01-30 09:10:26.257 23681 23681 W System. Err: . An android app. LoadedApk. ForgetServiceDispatcher (1363) LoadedApk. Java: 01-30 09:10:26. 257, 23681, 23681 W System. Err: . An android app. ContextImpl. UnbindService (1499) ContextImpl. Java: 01-30 09:10:26. 257, 23681, 23681 W System. Err: An android. Content. ContextWrapper. UnbindService (ContextWrapper. Java: 648) 01-30 09:10:26. 257, 23681, 23681 W System. Err: at com.programandroid.Exception.ExceptionActivity.ServiceNotRegisteredCrash(ExceptionActivity.java:276) 01-30 09:10:26.257 23681 23681 W System. Err: The at Java. Lang. Reflect. Method. Invoke (Native Method) 01-30 09:10:26. 258, 23681, 23681 W System. Err: at android. View. The view$DeclaredOnClickListenerOnClick (the Java: 4744) 01-30 09:10:26. 258, 23681, 23681 W System. Err: at android. View. The View. PerformClick (5675) View. Java:Copy the code

Log analysis is as follows:

This exception usually occurs when the service is unbound incorrectly. The solution is as follows: 1. Before unbinding the service, check whether the service has been bound. An example of a try-catch catch is as follows:

At this point, this has ended, if there is wrong place, welcome your suggestion and correction. Meanwhile, I look forward to your attention. Thank you for reading. Thank you!