Android Notes (exceptions, performance optimization, code specification, power saving, difference between tcp and udp, synchronous and asynchronous)

1. SQLException: Operation database exception class. Problem: This class is triggered when an error occurs when the Java application communicates with the database. At the same time, the error information of the database will be displayed to the user through this class. When the user inserts data, if the value of this field is duplicated with the existing record, violating the uniqueness constraint of the database, the database will run out an exception message. This information may not be visible to ordinary users because it occurs at the database level. At this time, the operation database exception class will capture the exception information of the database and pass the exception information to the foreground. In this case, the foreground user can analyze the cause of the error based on the exception information. Solution: Check the inserted data for duplicates.

2. ClassCastException: Data type conversion exception. Problem: In Java applications, sometimes data type conversions are required. This conversion includes explicit conversion and implicit conversion. However, no matter how it is converted, it must meet a precondition, that is, the compatibility of data types. Data type compatibility is guaranteed before the data type is converted. In this case, it is not easy to cause data type conversion exceptions. For example, in a field that only allows numeric types, you can set characters other than numeric values ​​are not allowed. Solution: Pay attention to whether the corresponding components correspond to each other when they are initialized.

3. NumberFormatException: An exception thrown when a string is converted to a numeric type. In the process of data type conversion, if there is a problem in the process of converting character type to numeric type, a separate exception is adopted in the Java program for this exception, namely NumberFormatException. For example, the character type data "123456" is now converted into Numeric data is allowed. However, if the character data contains non-numeric characters, such as 123#56, an exception will occur when converting to numeric type. The system will catch this exception and handle it. Solution: Check that the data is correct.

4. java.lang.NullPointerException (1). If the jar package of the third package is used, there is an error in the jar package (2). The component is not instantiated (3). The Adapter is not bound to the value; (4). When a component in the page is assigned null, an error will occur in the activity, and the data of other pages will be reinitialized after the program crashes (5). When the value is passed by Intent, the obtained key does not exist (6). No initial value is assigned.

5. The explanation of the java.lang.ClassNotFoundException exception is "the specified class does not exist".

6. java.lang.ArithmeticException The explanation of this exception is "mathematical operation exception", such as division by zero in the program, such an exception will occur.

7. The explanation of the java.lang.ArrayIndexOutOfBoundsException exception is "array subscript out of bounds". Now most programs have operations on arrays, so when calling arrays, you must carefully check to see if the subscript you call is out of bounds. The range of the array, generally speaking, it is not easy to make such mistakes in the display (that is, directly subscripting with constants) calls, but implicit (that is, using variables to indicate subscripts) calls often make mistakes, and there is another case, the program The length of the array defined in is determined by some specific methods, not declared in advance. At this time, it is best to check the length of the array first to avoid this exception.

8. java.lang.IllegalArgumentException The explanation of this exception is "method parameter error", such as the three values ​​in the method g.setColor(int red, int green, int blue), if there are more than 255, this will also appear Exception, so once we find this exception, what we have to do is to quickly check whether there is an error in the parameter transfer in the method call.

9. java.lang.IllegalAccessException The explanation of this exception is "no access rights". This exception occurs when the application wants to call a class, but the current method does not have access rights to the class. Pay attention to this exception when using Package in the program

10. Security exception: The reason is that the current device does not support the current program. This is due to the problem of the model. We should test with another device to detect what kind of abnormality exists in the current program; another reason is to obtain The activated network information entity class needs to add permissions, otherwise this exception will occur Solution: In the configuration file, add the permission of android_permission_Access_NetWork_State

11. RejectExecuteException: An asynchronous task can only be executed once, otherwise an exception will be reported. A thread can execute up to 5 threads. If it exceeds, it will wait, otherwise it will report an exception that refuses to execute. Solution: use child thread + handler instead of AsyncTask, or a Add fewer asynchronous operations to the thread.

12. Out of memory: memory overflow is an overflow event where too much data is stored leading to insufficient memory

13. Memory leak: Memory leak means that the resources that should be released are not fully released, and data continues to be added, resulting in a memory leak event;

ArithmeticException (divide by 0 exception),

BufferOverflowException (buffer overflow exception),

BufferUnderflowException (buffer underflow exception),

IndexOutOfBoundsException (out of bounds exception),

NullPointerException (null pointer exception),

EmptyStackException (empty stack exception),

IllegalArgumentException,

NegativeArraySizeException,

NoSuchElementException,

SecurityException,

SystemException,

UndeclaredThrowableException (the above are illegal parameter exceptions)

The difference between asset and res The same point between res/raw and assets: The files in the two directories will be stored in the apk package intact after being packaged, and will not be compiled into binary. The difference between res/raw and assets:

1) The files in res/raw will be mapped to the R.java file, and the resource ID, namely R.raw.filename, will be used directly when accessing; the files in the assets folder will not be mapped to R.java, and the accessed When you need the AssetManager class.

2) res/raw cannot have a directory structure, while assets can have a directory structure, that is, a folder can be created under the assets directory 3) An example of reading file resources: To read file resources under res/raw, use the following methods Obtain the input stream for writing InputStream is = getResources().openRawResource(R.raw.filename); Read the file resources under assets, and obtain the input stream for writing in the following ways AssetManager am = null; am = getAssets( ); InputStream is = am.open("filename");

What is the difference between Http and Https? Http and HTTPS use completely different connection methods and use different ports. The former is 80 and the latter is 443. The connection of http is very simple and stateless. The HTTPS protocol is a network protocol constructed by the SSL+HTTP protocol that can perform encrypted transmission and authentication, and is more secure than the http protocol.

 

.Performance optimization UI aspects:

1. Reduce multi-level nesting (drawing process)

2. ListView GridView reuse components

3. ViewPager cache page is preferably 3 and load data when each pager is displayed to reduce preloading and avoid waste.

4. The image display is slow to improve the download speed (InputStream wraps another layer of buffered stream will be faster (such as BufferedInputStream)) The third-level cache subsampling uses open source library caching aspects:

  1. Reasonable use of lrucache, disklrucache uses algorithms to balance memory and hard disk cache 2. Network + database for incremental loading network aspects:

    1. Use a suitable data format such as json

    2. Combine multiple requests into one, try not to redirect

    3. Reasonable cache, control the maximum number of concurrent requests, cancel invalid requests in time, filter repeated requests, timeout time settings, request priority settings, etc.

Code specification:

  1. Do not declare temporary variables in the for loop, and do not write try catch in it unless you have to.

  2. Avoid frequent GC, memory leaks, OOM (have a chance to say specifically)

  3. Reasonable use of data types, such as StringBuilder instead of String, (the most common written test question is str+="str" ​​with several objects), less use of enumeration enum, less use of parent class declaration (List, Map)

  4. Use thread pools reasonably to reduce thread creation overhead.

  5. Use a singleton

  6. Use more constants, less explicit "action_key", and maintain a constant class, don't repeat these constants.

Power saving:

  1. Reasonable use of service

  2. Use Alarm instead of Timer for background timing tasks (such as heartbeat package) Note: Alarm is invalid within five minutes of Xiaomi mobile phone

  3. Reduce network usage Compress data (upload files) Differentiate between wifi and non-wifi (download large files, watch videos, etc.)

  4. The foreground and background of the application are treated differently when the screen is off and on.

 

Difference between tcp and udp.

  TCP---(long link) (transmitting and receiving, data security) transmission control protocol, which provides connection-oriented and reliable byte stream services. Before transmitting data, a connection is established through a "three-way handshake" to ensure reliable data transmission. , but the efficiency is relatively low. It is generally used in occasions with high security for data transmission.

  UDP---(Short connection, just send, no matter what, if you want to chat is UDK, it doesn't matter if you lose a few chat records) User Datagram Protocol is a simple datagram-oriented transport layer protocol for connectionless. UDP does not provide reliability, and data transmission may be out of sequence and packet loss, but it is more efficient. It is generally used in occasions with high real-time requirements.

 

The difference between synchronous and asynchronous:

  When a function call is issued, the call does not return until the result is obtained. That is to say, one thing must be done one by one, and the next thing can be done after the previous one is completed.

  When an asynchronous procedure call is issued, the caller cannot get the result immediately. The component that actually handles the call notifies the caller with status, notification, and callback when it's done.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325259768&siteId=291194637