[Summary of 39 most common error and exception solutions in Android development]

  1. appcompat_v7

After updating ADT to version 22.6.0, this library appeared. appcompat_v7 is a compatibility package of Google itself, which is a support library that
allows all versions above 2.1 to use the interface of version 4.0. For example, using ActionBar, no need to use third-party support libraries

  1. appcompat_v7: application compatibility package, V7 refers to version 7, that is, android2.1, this compatibility package supports systems above version 2.1.

  2. Recently, Google officially took out the compatible jar package and some resource files to create an android project, which is actually a resource library. Right-click this project to enter the buildpath-click android, and you will find that islibrary is ticked, indicating that it is a library. In fact, this library can be shared by multiple projects. The library already contains the v7.jar package and some adaptive resources. When developing multiple projects, you can put some shared code and resources into the library for convenience. use. The lower version of ADT does not automatically generate a library when building a project, but when needed, you can create a new project and check islibrary. The higher version ADT automatically generates the library. If you don’t need it, just right click on the newly created project under Properties–android–library to select the library, and click remove to remove it.
    3. When the application is packaged or run, the library will be automatically packaged and compiled as part of the project.

  3. After updating the ADT and SDK versions, create a project and find that all configurations are correct, and the virtual machine starts normally, that is, there is an exclamation mark on the project header, you can check in the MainActivity file to see if the inherited Activity is No, you need to introduce some packages to successfully run the program, it is recommended to change to Activity

    There will be many compatibility problems when the version is improved, the best way to deal with it is to reduce the version

[So when creating an Android project, if the minimum compatible project is very low, an exception may occur, so it is recommended that the minimum version be 4.0 or above as much as possible]

[When creating a new Android project, if the minimum version is selected below 4.0, there will be an additional appcompat_v7 project, but this project will report an error, and it is also prone to other errors and exceptions, etc.]

  1. When the computer contains multiple Android development environments, there will be multiple DDMSs, and an exception of port occupancy may be thrown during startup. The solution is:

    When running the project, eclipse pops up a prompt box "Could not open Selected VM debug port (8700). Make sure you do not have another instance of DDMS
    or of the eclipse plugin running. If it's being used by something else, choose a new port number in the preferences."

     	在终端输入:netstat -ano | findstr "8700"
    
     		未找到占用端口。
    

Solution:

In eclipse, open Window -> Preferences -> Android -> DDMS in turn: as shown below

Change Base local debugger port 8600 to 8601, and check Use ADBHOST.

  1. Icon problem, hdpi- 72px 72px , mdpi-48px 48px , xhdpi-96px 96px , xxdip-144px 144px

  2. android switch(String)错误:Cannot switch on a value of type String for source level below 1.7

The judgment condition of the switch statement can accept int, byte, char, short, and cannot accept other types.
Only JDK version 1.7 or above can support String

The problem can be solved by setting as follows: (If there is no JDK1.7 version, you can download and install it)
Menu option – "project->properties->java compiler->compiler compliance level: choose 1.7

  1. When debugging an Android program: prompt problem occurred An internal error occurred during Launching New_configuration

Solution:
Step 1: Enter the Run/Debug Settings window, there are two implementation methods: 1. Project -> Properties -> Run/Debug Settings:

The Run/Debug Settings window is as follows:

Step 2: After selecting New_configuration in the above figure, click Delete to delete it.

Step 3: Clean the project again and it will be OK.

Click OK to succeed.

  1. After the phone is plugged into the computer and USB debugging is turned on, an error is reported that the ADB Interface installation failed, or the Android driver installation failed.
  • 【win7】

    [Win7 system installation process prompts "the system cannot find the specified file" (13.01.23 new case)]

    Win7 system users have encountered a few times when installing the adb driver that "the system cannot find the specified file". The actual reason is that the system needs to install the winusb driver that comes with the system when installing the adb driver, and the winusb.sys required by winusb The file is copied by relying on the "windows cd" field of the inf file. Sometimes the system will not know the location of "windows cd", which will cause the lack of winusb.sys file during the installation process and the installation will stop.

    1. Solution:
      Find the source path of winusb "c:\windows\system32\DriverStore\FileRepository\winusb.inf_x86_neutral_6cb50ae9f480775b\" directory, copy the Winusb.sys file to the "c:\windows\inf" directory, and then again There is no problem with the installation.

    2. 【Solution 2】: Install the ADB driver with software such as Driver Wizard. [And when installing the driver, you must set the usb option to charge only.

       						(例如:)类型:安卓
       								名称:USB Composite Device
       								制造商:Android
       								设备描述:USB Composite Device  【Android usb 混合驱动】
      
       		 或者 直接 下载安装 对应手机型号的 adb 驱动。
      
       	【Window-->ShowView--->Device --> 就可以查看当前可用的设备了】--[尝试打开或关闭 usb选项媒体设备,可以刷新 Device]
      
       	【然后选择runConfiguration-->Always prompt to pick device(每次运行总是提示选择设备)】
      
  • [xp]
    [ADB driver cannot be installed, there are several different reasons, and the solutions are also different. Since most of the problems encountered are windows XP systems, all windows XP is used here as an example.

    1. The same WDF version already exists in the system, causing the ADB driver to fail to install

    This kind of situation is the most common. When the computer already has the same WDF version, but there is a lack of related uninstall items, this problem will occur. The performance is that the computer prompts a fatal error in the installation.

Solution:
  a. Add an uninstall item of the relevant version, take wdf1005 version as an example, import the registry uninstall item. Then reinstall the ADB driver.

	  b. 升级到一个更高版本的ADB驱动也能够解决这个问题。

2. The system lacks the Cryptographic Services service, causing the ADB driver to fail to install

On a small number of XP systems, the final installation of the driver fails due to the absence of the Cryptographic Services service. This is because the installation of the wdf driver depends on the Cryptographic Services.

Solution:
   Import the registry key value of the service, then restart the computer and then install the ADB driver.

3. There is a conflict with the U-KEY of the Agricultural Bank of China Online Banking, which leads to the failure of ADB driver installation

When the Android ADB driver is installed, there will be conflicts with the U-KEY of some online banks, which will cause the adb interface driver to fail to install, and error 10 will be displayed.

Solution:
    You can only uninstall related files and services related to online banking first, and then reinstall the ADB driver.

4. The abnormality of the ADB driver caused by insufficient power supply makes it impossible to install the ADB driver

Some desktops display a yellow exclamation mark on the adb interface due to insufficient power supply from the front USB port.

Solution:
   Connect the mobile phone data cable to the rear USB interface of the main box, keep the power sufficient and stable, and reinstall the ADB driver.

  1. estFeature() must be called before adding content

Caused by: Android.util.AndroidRuntimeException: requestFeature() must be called before adding content
Call android.hardware.Camera in android to complete the camera function, but encountered such an exception.

setContentView(R.layout.main);
requestWindowFeature(Window.FEATURE_NO_TITLE);

The solution is as follows: change the order

requestWindowFeature(Window.FEATURE_NO_TITLE);

setContentView(R.layout.main);

--------------------【Therefore: this.requestWindowFeature(); method must be written in front of this.setContentView(); method】------- --------------

Question 2:
Solve requestFeature() must be called before adding content error

Android 实现画面全屏(取消标题、取消状态栏):

  //取消标题
  this.requestWindowFeature(Window.FEATURE_NO_TITLE);
  
  this.setContentView(R.layout.logo); //Activity样式文件,一定要写在中间

  //取消状态栏
  this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN);

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:background="@color/white"
    >

    <ImageView 
    android:id="@+id/logo" 
    android:src="@drawable/logo_bg"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    
    />
    
</LinearLayout>

java.lang.RuntimeException:Unable to start activity ComponentInfo
_
这是因为:

java的执行顺序有关!目前遇到的这个问题就是因为在系统运行开始的时候就已经调用父类的构造方法,接着调用setContentView方法展示视图界面。R.layout.main是R.java资源类中的一个属性。当你在调用这个方法之后在声明Widget就会报:android.util.AndroidRuntimeException: requestFeature() must be called before adding content

所以前面的那三句中加载Activity的样式的那句代码一定要写在中间。

9. The centralized causes and solutions of java.lang.RuntimeException: Unable to start activity ComponentInfo{xxx}: java.lang.NullPointerException errors in Android development

Error message string: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.first/com.first.Game}: java.lang.NullPointerException

Generally, this error occurs in the setContentView(XXX) in the Activity onCreate() method. There are many possible reasons on the Internet, and there are probably four important possible reasons:

Reason 1: The error of xxx, if it is R.layout.main, then it should be the wrong use of tags in the main.xml file. The most common error that the compiler will not prompt is the confusion between android:name and android:id. Check carefully whether the tags of main.xml are all correct

Reason 2: The requestWindowFeature() method is used after the setContentView(view) method, and the following error will prompt that requestFeature must be used before setContentView, just put the requestWindowFeature() method before the setContentView(view) method to solve the problem

Reason 3: Outside the onCreate() method, and it does not belong to any method body, it is caused by directly giving a control findById(R.id.xx). It is necessary to perform findById(R. .id.xx) can be solved

Reason 4: The view is not instantiated before setContentView(view), but directly setContentView(view) is caused by the statement. Check carefully whether the view is instantiated in the method before calling setContentView(view).

Reason 5: Because of a null pointer error exception, you should check whether there is a value in something like Spinner or list

  1. Error resolution: java.lang.SecurityException: Permission Denial [permission denied]

[This error sometimes occurs when another application calls the Activity of your program]:

java.lang.SecurityException: Permission Denial: starting Intent { cmp=com.siveco.bluebee.phone.supervisor/com.siveco.bluebee.core.activity.GetServerAddressActivity } from ProcessRecord{4456781 1644:com.siveco.bluebee.project.productionfeedback/10056} (pid=1774, uid=10056) not exported from uid 1044

This error originates from the following code.

if (APPTools.checkAPP(this.getApplicationContext(), BBA_PACKAGENAME)) {
Intent intent = new Intent();
intent.setClassName(BBA_PACKAGENAME, “com.siveco.bluebee.core.activity.GetServerAddressActivity”);
startActivityForResult(intent, REQUEST_CODE);

}

Solution: You can configure the attribute exported="true" in the Activity


  1. Exception information: you must resert adb
    Solution: DDMS–>click the small inverted triangle in the Device window and select Reset adb

  2. The method onClick(View) of type new View.OnClickListener(){} must override a superclass

    mButton1.setOnClickListener(new Button.OnClickListener()
    {
    @Override
    public void onClick(View v)
    {
    // TODO Auto-generated method stub
    mTextView1.setText(“Hi, Everyone!!”);
    }
    });

The above code reports an error as follows

  • implements android.view.View.OnClickListener.onClick
  • The method onClick(View) of type new View.OnClickListener(){} must override a superclass

After searching, it is found that it is a jdk version problem. Project properties---->complier compliance level in javaCompiler can be changed from 1.5 to 1.6

Because [you can only write like this when jdk1.6, otherwise you can’t write @Override, because @Override is not supported when implementing the method in the interface below 1.6]

  1. When using SQLite database: android.database.sqlite.SQLiteException: Can't downgrade database from version 2 to 1

    Solution: This database already exists, and the version is 2. You use the version 1 to operate, so something goes wrong.

          你要是没改数据库就用2,改了就增加1,写成3.
    
  2. When running the program ----【Activity not started, its current task has been brought to the front】

运行错误:【Activity not started, its current task has been brought to the front 】。

Reason analysis: Because there are still things running in your simulator, that is, one of the activities you want to run is already running in the simulator. Don't think that nothing is running after the emulator exits to the desktop. The program that was closed abnormally when you debugged may have activity running.

Explanation: This is not a bug of the Android platform, but Android itself is such a processing mechanism.

Under the Android platform, when we end a process through the return button or the exit operation of the program itself, in fact, the Android virtual machine may not actually end the process.

In the case of memory permitting, this program will be stored in the Android virtual machine in the form of cache. Only in the case of insufficient memory, the Android system will clean up tasks that have not been activated for a long time,

Provide memory for other programs.

Android does this for you to start this program more quickly next time.

Therefore, the landlord’s situation occurs because your program has not changed in any way and the memory is sufficient, the program executed last time will be directly placed on the top of the task stack from the cached state, and your program will be executed again. You can continue to execute.

解决方法一: 退出目前执行的程序。。

解决方案二: project--->clean , 让程序重新编译一下就行
  1. When using commands such as adb, ddms, sqlite, etc. on the command line: save xxx is neither an internal command nor an executable file.

Solution: There is a platform-tools directory under the SDK installation directory, and the location is configured in the path system variable.

  1. Listen to text messages
要使自己写的android程序能够收到短信息来临的广播,则不管是在java程序中注册broadcastReceiver还是在manifest.xml中注册,在manifest.xml文件中必须添加一句代码:

And the code is at the same level as application, that is to say, it is a direct subtag of manifest. If the sentence is not changed, even if the broadcast reception is registered in the program, the SMS will not be received.

[And the permission registration statement must be written before the application tag, not after it, otherwise it will throw: Permission Denial: receiving Intent { xxx} warning]

  1. eclipse [SDK Manager] 'xcopy' is not recognized as an internal or external command, operable program.

Eclipse starts the SDK Manager and reports an error: [SDK Manager] 'xcopy' is not an internal or external command, nor is it a runnable program.
As a solution, add C:\WINDOWS\system32 to the path environment variable; or copy C:\WINDOWS\system32\xcopy.exe to the tools under the android sdk directory to run normally.

  1. Android development error: Failed to execute tools\android.bat (or: failed to run SDK Manager.exe) Solution:

The solution is:

1. Find the temp folder under the sdk directory, which is used to temporarily store data.

2. Find tools_r24.1.2-windows.zip in the temp folder, or other tools_r***-windows.zip (recommended to choose the latest one), unzip it to get a tools folder

3. Copy all the contents of the tools folder (with android.bat inside) that you just decompressed to your own tools folder, that is, sdk/tools, and you are done.


20. If you open the SDK Manager, you will find that there is no new version of the API or the display is incomplete. Then you can consider updating the Android SDK Tools: you can still update it in SDKManager

  1. If you enter adb at the Windows command line you find that neither is internal. . . . Nor is it. . . :

    Solution:
    For example: D:\Study_SoftWare\adt-bundle-windows-x86_64-20140702\sdk\platform-tools
    Just add this directory to the environment variable path

  2. When using a Java local inner class or an anonymous inner class, if the class calls a local variable of the method, the local variable must be decorated with the final keyword, otherwise a compilation error will occur.

Cannot refer to a non-final variable i inside an inner class defined in a different method

解决方案:【在外部定义一个成员变量,用来存储局部变量的值,然后在匿名内部类中直接使用成员变量即可。】      
  1. An exception is reported when updating the main thread interface in the sub-thread: android.view.ViewRoot$CalledFromWrongThreadException
    Only the original thread that created a view hierarchy can touch its views

Solution 1: Use Android's Handler mechanism to send information in the sub-thread, then receive the message in the main UI thread, and then process it

Solution 2: Use Activity.runOnUiThread(Runnable)
to create the code for updating ui in Runnable, and then pass the Runnable object to Activity.runOnUiThread(Runnable) when the ui needs to be updated. In this way, the Runnable object can be called in the ui program.

          FusionField.currentActivity.runOnUiThread(new Runnable()   
          {  
              public void run()  
              {  
                  Toast.makeText(FusionField.currentActivity, "Success",  
                          Toast.LENGTH_LONG).show();  
              }  
    
          });  
  1. [Cannot access the network in the main thread – android.os.NetworkOnMainThreadException exception]

    Solution 1: Access the network in a child thread. —If the interface needs to be updated, it can be implemented in combination with a handler. Because the main interface cannot be updated in the sub-thread]

    Solution 2: Use asynchronous mechanism
    —————————————————————————————————————————— ———————————————————————————————————————————————————— ———————

  2. Collision detection problem

在项目中使用并映入 java.awt.Rectangle类后,编译正常,但运行时抛出:

        java.lang.NoClassDefFoundError: java.awt.Rectangle


    原因:Android 底层不支持 java.awt 与,Swing,因此即使编译通过,但运行时会报错    


解决办法一:使用安卓自带的 Rect类,它直接提供了intersects方法,可以用于碰撞检测

解决办法二: 查看JDK的Rectangle源码,把构造方法与 intersects(MyRectangle r) 提取到我的 MyRectangle工具类中。
           --经检测正常可用
              
解决办法三:自己编写碰撞检测API   

————————————————————————————————————————————————————————————————————————————————————————————————

  1. : In the onCreate(); method, after obtaining the reference of the control object (findViewById), an error is found when setting the listener: Caused by: java.lang.NullPointerException

    解决方案:1.查看find控件之前,有没有为Activity设置 this.setContentView(); 如果没有设置则会抛出空指针异常.
    

————————————————————————————————————————————————————————————————————————————————————————————————————————————————————

  1. During Eclipse Android development, if it is found that some classes have no source code (Ctrl + left mouse button), the source code cannot be viewed:

    Solution: On the error page: click attach source. Then select the folder of the source code:

    Example: D:\Study_SoftWare\adt-bundle-windows-x86_64-20140702\sdk\sources\android-19 ready

  2. Encountered Bug1:-----【Using the BaseAdapter adapter, the Bean collection is normal, but all items display the same data when the data is displayed】-----

[Solution]:
First check whether the Bean object is created for each piece of data at the method of obtaining data to fill the Bean collection, instead of repeatedly adding the previous Bean object.
then in

            【getView方法中 设置子控件内容时用:beans.get(position); //来获取指定位置的Bean对象,然后设置子控件内容 】

                            且记:此处不能使用循环遍历的方式设置子控件内容

[In short]: 1. First ensure that a piece of data corresponds to a Bean object (instead of repeatedly adding the previous Bean object)
2. Then ensure that the beans.get(position) method must be used to obtain the Bean when setting the content of the sub-control object, (instead of looping through the beans container)

  1. Call when refreshing the data of ListView(AdapterView): adapter.notifyDataSetChanged(); [found refresh failure]

    Solution: The list point passed to AdapterView cannot be changed, it needs to point to the same memory from beginning to end, otherwise refresh failure may occur

  2. java.lang.RuntimeException: setOnItemClickListener cannot be used with a spinner.

    It means that spinner does not support OnItemClickListener, because its implementation is rewritten in AdapterView.

    [Can be replaced by setOnItemSelectedListener]

  3. If the queried data information is displayed in the cmd command line window, there are garbled characters?

    First of all, Android's SQLiteDataBase uses UTF-8 by default, and if the encoding method used in the command line window is not UTF-8, garbled characters may appear.

    Solution: Change the encoding method of the command line window (current code page) to make it consistent with the encoding method of the data in the database

            使用命令:chcp   936         -----修改成GBK
                             950         -----修改成繁体中文(Big5) 
                             932         -----修改成日文
                             437         -----修改成英文
                             65001       -----修改成UTF-8
    
  4. Found when using ContentProvider: java.lang.SecurityException: Permission Denial: opening provider

Solution: Add android:exported="true" to the definition of ContentProvider in AndroidManifest.xml

  1. Found when using ContentProvider:
    java.lang.IllegalStateException: Cannot perform this operation because the connection pool has been closed.

    Solution: Check the exposed methods in ContentProvider, such as: query(…); Before returning to Cursor, is the database or cursor object closed?

        如果关闭了,则取消关闭即可。【因为要返回cursor对象给调用者使用,因此不能调用 db.close(),或cursor.close() 】             
    
  2. Mediaplayer Should have subtitle controller already set An exception occurs when using MediaPlayer+SurfaceView to play video, there is sound but no picture.

Solution: 1: Do not use android4.4 kitkat to run this program, after testing android5.1 runs normally

  1. After using the SVN client to associate the workspace folder with the SVN server, it is found that the workspace folder does not have a small green checkmark:

    Solution: [Enter the task manager to kill the explorer process first, and then start the explorer process]

  2. ADB fails to start and throws an error log (and using the reset adb function is useless):

    'ADB server didn’t ACK
    [2017-02-09 14:29:14 - adb] * failed to start daemon *
    [2017-02-09 14:29:14 - ddms] ‘…\sdk\platform-tools\adb.exe,start-server’ failed – run manually if necessary

    Solution: Go directly to the task manager of the computer, kill all adb processes, and then restart adb.

  3. Gradle “manifest requires a placeholder substitution” error but manifestPlaceholders supplies a value

The details are as follows:

  AndroidManifest.xml:89:16 Error:
    Attribute uses-library#com.company.platform.${encoding}@name at AndroidManifest.xml:89:16 requires a placeholder substitution but no value for <encoding> is provided.
/Users/Company/Desktop/Checkout/android/Project/app/src/main/AndroidManifest.xml:0:0 Error:
    Validation failed, exiting

This problem usually occurs when we add mate-data to the AndroidManifest.xml file, and compile errors!

solution:

进入 app.gradle 

    然后在 app.gradle 文件中: 为 mate-data 注入值!
      productFlavors{
        productFlavors.all{
                  flavor->
                      Map<String,Object> map=new HashMap<String,Object>()
       
                      map.put("encoding",encoding)
          
                      flavor.manifestPlaceholders.putAll(map)
          }
        }

  You need to just add to the array. You are replacing it. Do this:

  manifestPlaceholders = [encoding: "some value", version: cityVersion]
  By declaring manifestPlaceholders twice for the same flavor/build type, your are replacing the previous one. After the previous one got replaced, your build failed because the property no longer exists.
  1. BaseApplication is packaged, but actually returns null when calling BaseApplication.getAppContext()
public class BaseApplication extends Application {
    
    

    private static Context mContext;

    @Override
    public void onCreate() {
    
    
        super.onCreate();
        mContext = this;
    }

    public static Context getAppContext() {
    
    
        return mContext;
    }

    @Override
    public void onTerminate() {
    
    
        super.onTerminate();
        mContext = null;
    }
}

Solution:
Check whether android:name=".base.BaseApplication" is configured at the node in the AndroidManifest.xml file!

  1. Solve strings.xml formatting placeholder error: Multiple substitutions specified in non-positional format

Example: Game %s, Author: %s

After checking, it is found that the %s in string.xml causes the compilation to fail, and the %s should be changed to the form of %position$s.

That is, change to: game %1 s, author: s, author: %2s , author: s can

Guess you like

Origin blog.csdn.net/UserFrank/article/details/129298070
Recommended