Android FAQ highlights

Source: Internet
Author: User
Tags jcenter

Android FAQ highlights
Android FAQ highlights (Continuous updates) SVN: Commit failed (details follow): svn: xxx is scheduled for addition, but is missing
Description:After deleting the folder, Click commit to submit, but the following error is displayed: "svn: Commit failed (details follow): svn: 'xxx' is scheduled for addition, but is missing ".
Cause:Files submitted using SVN are marked as "add" and are waiting to be added to the repository. If you delete the file at this time, the SVN will still try to submit the file, although its status is "missing.
Solution:Run "svn revert xxx-depth infinity" in the command line. On the GUI, right-click-Revert and select the file or folder. In this way, SVN will be told to return the file to the previous state "unversioned", that is, it will not make any changes to the file. "Stub!" appears when the Android library is called in the Java project !" Error
Description:Console error: Exception in thread "main" java. lang. RuntimeException: Stub!
Cause:In the Java project, try to use the org. json. JSONObject class in the Android library. "Stub!" appears during execution !" Error: the main function of java cannot be executed in the Android project. There are some differences between the Android project and the Java project. They cannot mix their libraries and function entry methods.
Solution:You can run the code correctly after porting it to the Android project! Solution for generating garbled characters in Javadoc
Description:When the javadoc document is generated or packaged, the error "inable characters of GBK encoding" occurs.
Cause:This is common because the Code contains Chinese comments.
Solution:
Method 1: Generate the JavaDoc document through the Android Studio interface, open Tools> Generate JavaDoc> Other command line arguments in turn to: "-encoding UTF-8-charset UTF-8 ";
Method 2: configure the build. gradle file in the module to add the following task: tasks. withType (JavaCompile ){
Options. encoding = UTF-8"
}, This build will not appear garbled, But in view the generated document will find the display will be garbled, find the reason is to set charset is also for the UTF-8, so far did not find how to configure, if any of you know how to configure it, please comment on it. Thank you very much! Failure [INSTALL_FAILED_OLDER_SDK]
Description:The error "Failure [INSTALL_FAILED_OLDER_SDK]" is reported during compilation.
Cause:Generally, the system automatically sets compileSdkVersion for you and the version is too high.
Solution:Modify compileSdkVersion xxx under build. gradle to compileSdkVersion 19 (or your local SDK). The virtual buttons will affect full screen display.
Description:In android4.0 and later versions, there is a very embarrassing thing called the Navigation Bar. It and the Status Bar are listed on each other, affecting our full screen.
Cause:When the screen is displayed, you sometimes need to hide the navigation bar and virtual buttons, and the virtual keys are displayed based on your touch. Therefore, you need to add a listener to hide them directly when they appear.
Solution:Simply add the following code to the current Activity:

private static Handler sHandler;    private final Runnable mHideRunnable = new Runnable() {        @Override        public void run() {            int flags;            int curApiVersion = android.os.Build.VERSION.SDK_INT;            if (curApiVersion >= Build.VERSION_CODES.KITKAT) {                flags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION                        | View.SYSTEM_UI_FLAG_IMMERSIVE;            } else {                flags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;            }            getWindow().getDecorView().setSystemUiVisibility(flags);        }    };
@Override    protected void onResume() {        super.onResume();        sHandler = new Handler();        sHandler.post(mHideRunnable); // hide the navigation bar        final View decorView = getWindow().getDecorView();        decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {            @Override            public void onSystemUiVisibilityChange(int visibility) {                sHandler.post(mHideRunnable); // hide the navigation bar            }        });    }
You can use the code to modify the color attribute of a shape.
Description:Sometimes this requirement is met: the background IDs in different States are different, and the background has a specific shape style.
Cause:Generally, shape files are fixed with colors in xml, so you need to modify the color value in the shape file in the code.
Solution:You can directly use the control to obtain the background of the control and change the color in the shape file by changing the background color. The Code is as follows:
GradientDrawable gradientDrawable = (GradientDrawable)view.getBackground();gradientDrawable.setColor(color);
Error: Cause: peer not authenticated
Description:Error: Cause: peer not authenticated
Cause:This is mainly because the gradle version does not match.
Solution:Build. in the gradle file, change the gradle version corresponding to classpath in dependencies to 1.3.0, and change jcenter () in repositories to jcenter {url "http://jcenter.bintray.com/"} Popupwindow usage exception: unable to add window-token null is not valid
Description:Popupwindow must be displayed based on a view, void android.widget.PopupWindow.showAtLocation(View parent, int gravity, int x, int y)
You can call this method to display the Popupwindow, but sometimes an exception occurs: unable to add window-token null is not valid; is your activity running?
Cause:This is generally because showAtLocation is called in the onCreate () function of the Activity. Because your popupwindow is attached to an activity, the onCreate () function of the activity () A pop-up window is required before execution.
Solution:When a window pops up in Handler, it is okay to call it through the delay in onCreate. The specific code is as follows:
    private Handler popupHandler = new Handler(){        @Override        public void handleMessage(Message msg) {            switch (msg.what) {            case 0:                popupWindow.showAtLocation(findViewById(R.id.rlShowImage), Gravity.CENTER|Gravity.CENTER, 0, 0);                popupWindow.update();                break;            }        }    };
popupHandler.sendEmptyMessageDelayed(0, 1000);
The ListView click entry does not respond.
Description:A common problem in development is that the listview in a project is not just a simple text, but you often need to define your own listview, and your own Adapter will inherit the BaseAdapter and write it as needed, the problem may occur. When you click an item, the system does not respond and cannot obtain the focus.
Cause:Most of the reasons are that sub-controls such as ImageButton, Button, and CheckBox exist in your own defined items (also called the sub-Control of Button or Checkable ), at this time, these child controls will get the focus, so when you click an item, the Child control is changed, and the click of the item itself has no response.
Solution:DescendantFocusability is used to solve the problem. This attribute defines the relationship between viewGroup and its child controls when a view obtains the focus.
There are three types of attribute values:
BeforeDescendants: viewgroup takes precedence over its subclass control and obtains the focus.
AfterDescendants: viewgroup obtains the focus only when its subclass control does not need to obtain the focus.
BlocksDescendants: viewgroup overwrites the subclass control and directly obtains the focus.
We usually use the third type, that is, adding the android: descendantFocusability = "blocksDescendants" attribute to the root layout of the Item layout. When a dotted line is drawn using shape, solid lines are displayed on models above 4.0.
Description:When the shape is used to draw the dotted line, it can be normally displayed in Graphical Layout, but the model on Android4.0 is displayed as a solid line.
Cause:By default, the hardware acceleration of the Activity is enabled for more than 4.0, so we can turn it off in Manifest. xml.
Solution:Add the following attributes to the activity to be displayed: android: hardwareAccelerated = "false". You can also disable View. setLayerType (view. LAYER_TYPE_SOFTWARE, null) at the View level ). Application does not specify an API level requirement
Description:Compilation times warn: Application does not specify an API level requirement!
Cause:No API version is added to the AndroidManifest. xml or build. gradle file, which does not affect the operation.
Solution:Add the minSdkVersion and targetSdkVersion versions in the corresponding region. Installation error: INSTALL_FAILED_INSUFFICIENT_STORAGE
Description:Error: Installation error: INSTALL_FAILED_INSUFFICIENT_STORAGE.
Cause:By default, applications are installed in mobile phone buckets, and the device does not have enough storage space to install applications.
Solution:Generally, mobile phones have SD cards. You can set the property android: installLocation = "auto" in the AndroidManifest. xml file. ActivityManager: Warning: Activity not started, its current task has been brought to the front
Description:The following error occurs during mobile phone debugging: ActivityManager: Warning: Activity not started, its current task has been brought to the front.
Cause:The mobile phone has started an application with the same name.
Solution:Close the running application and try again. Failed to fetchurl https://dl-ssl.google.com/android/repository/repository.xml
Description:When you open SDK Manager, the following error occurs when updating the SDK: Failed to fetch URL https://dl-ssl.google.com/android/repository/repository.xml.
Cause:Dl-ssl.google.com has been closed in mainland China.
Solution:Modify the C: \ Windows \ System32 \ drivers \ etc \ hosts file and add a line: 74.125.237.1 dl-ssl.google.com, Save and re-Automatic SDK Manager. The connection to adb is down and a severe error has occured Solution
Description:An error is reported during compilation and running: The connection to adb is down and a severe error has occured.
Cause:Other applications occupy the adb process port. You only need to disable the process.
Solution:Enter the dos window, enter netstat-ano | findstr "5037" to view all process IDs that occupy port 5037, and then enter tasklist | findstr "process ID" to find the corresponding process name, go to the task manager and close it. Android image loading Bitmap OOM error Solution
Description:When Android loads resource images, it is easy to see OOM errors, because the Android system has a limit on memory. If the limit is exceeded, OOM occurs. To avoid this problem, when loading resources, consider how to save memory and release resources as soon as possible.
Cause:Android versions have different effects on image loading and recycling:
1. In Android 2.3 and later versions, the concurrent recovery mechanism is adopted to avoid freezing during memory recovery;
2. In Android 2.3.3 (API Level 10) and earlier versions, Bitmap's backing pixel data was stored in native memory, which is separate from Bitmap itself. Bitmap itself is stored in dalvik heap, as a result, pixel data cannot be determined whether to be used or not, and cannot be released in time, which may cause OOM errors. Since Android 3.0 (API 11), pixel data and Bitmap are stored in Dalvik heap.
Solution:When loading image resources, you can use the following methods to avoid OOM problems:
1. We recommend that you use the Bitmap. recycle () method to release resources in time before Android 2.3.3 and later;
2. You can set BitmapFactory from Android 3.0. options. the value of inBitmap (obtained from the cache) is used to reuse Bitmap. If it is set, the value of inPreferredConfig will be overwritten by the value of the reused Bitmap;
3. Set Options. inPreferredConfig to reduce memory consumption:
The default value is ARGB_8888. Each pixel is 4 bytes. A total of 32 characters.
Alpha_8: only the transparency is saved, which consists of 8 digits and 1 byte.
ARGB_4444: a total of 16 bits, 2 bytes.
RGB_565: a total of 16 bits, 2 bytes.
If no transparency is required, you can change the default value of ARGB_8888 to RGB_565 to save half of the memory.
4. Compress large images by setting Options. inSampleSize. You can first set Options. inJustDecodeBounds to obtain the peripheral data of Bitmap, in width and height. Computation the compression ratio for compression;
5. Set Options. inPurgeable and ininputretriable to enable the system to recycle memory in time.
InPurgeable: If this parameter is set to True, the Bitmap created by BitmapFactory is used to store the memory space of Pixel. When the system memory is insufficient, it can be recycled. When the application needs to access the Pixel of this Bitmap again, the system will call BitmapFactory's decode method again to regenerate Bitmap's Pixel array. If it is set to False, it indicates that the array cannot be recycled.
Inininputresumable: Specifies whether to copy data in depth. this parameter is used with inPurgeable. If inPurgeable is set to false, this parameter is meaningless. True: share a reference to the input data (inputStream, array, etc ). False: a deep copy.
6. Use decodeStream instead of other decodeResource, setImageResource, setImageBitmap, and other methods to load images.
Differences:
DecodeStream directly reads the image bytecode and calls nativeDecodeAsset/nativeDecodeStream to complete the decode. It does not need to use some additional processing procedures of Java space to save dalvik memory. However, because the bytecode is directly read and there is no processing process, it will not automatically adapt to the various resolutions of the machine. You need to configure the corresponding image resources in hdpi, mdpi, and ldpi respectively, otherwise, the machine with different resolutions is of the same size (number of pixels) and the actual size is incorrect;
After reading the image data, decodeResource will adapt the Image Based on the machine's resolution, resulting in a lot of dalvik memory consumption;
DecodeStream call process: decodeStream (InputStream, Rect, Options)-> nativeDecodeAsset/nativeDecodeStream;
DecodeResource call process: After finishDecode, call the createBitmap method of the additional Java layer to consume more dalvik memory;
DecodeResource (Resource, resId, Options)-> decodeResourceStream (set the inDensity and inTargetDensity parameters of Options)-> decodeStream () (perform the finishDecode operation after Decode is complete) finishDecode () -> Bitmap. createScaleBitmap () (calculate scale Based on inDensity and inTargetDensity)-> Bitmap. createBitmap ().
The combination of the above methods can reasonably avoid OOM errors. Solve nested GridView in ScrollView
Description:ScrollView nested GridView is used in development. Because both controls have their own scroll bars, when they come together, a problem occurs, that is, the GridView will not display completely.
Cause:Because the parent control is automatically displayed based on the size of the Child control, the Child control needs to be maximized.
Solution:Solution: Customize a GridView control. The Code is as follows:
public class MyGridView extends GridView {         public MyGridView(Context context, AttributeSet attrs) {             super(context, attrs);         }         public MyGridView(Context context) {             super(context);         }         public MyGridView(Context context, AttributeSet attrs, int defStyle) {             super(context, attrs, defStyle);         }             @Override         public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {                  int expandSpec = MeasureSpec.makeMeasureSpec(                     Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);             super.onMeasure(widthMeasureSpec, expandSpec);         } } 

In the code, the onMeasure () method is modified to set the size to the maximum value of the int type. To solve this problem, we need to shift the two places to the right because the first two represent values of the AT_MOST type.

Black screen for a short time on the Android startup Interface
Description:By default, the android program starts with a black screen.
Cause:The default theme background is black.
Solution:You only need to add android: theme = "@ android: style/Theme. Translucent" to the portal activity to solve the problem of black screen startup.

The distance between the first line and tail line of ListView or GridView from the edge of the screen in Android
Description:The distance between the first row and the end row of ListView or GridView is invalid.
Cause:The default row of ListView & GridView on Android is set to the top.
Solution:Set android: clipToPadding = true for ListView or GridView, and set the distance through paddingTop and paddingBottom.

Curl: (6) Couldn't resolve host 'android .git.kernel.org'
Description:When downloading the Android source code in Linux, the following error occurs: curl: (6) Couldn't resolve host 'android .git.kernel.org '.
Cause:Because the android.git.kernel.org website is hacked, you cannot download the repo and android source code from this website.
Solution:Download the android source code from the https://www.code=ra.org/website, as shown in the following figure:
Download repo and set Environment Variables

$ curl "http://php.webtutor.pl/en/wp-content/uploads/2011/09/repo"> ~/bin/repo$ chmod a+x ~/bin/repo$ PATH=~/bin:$PATH

Download android source code

$ mkdir WORKING_DIRECTORY$cd WORKING_DIRECTORY$ repo init -u git://codeaurora.org/platform/manifest.git -b gingerbread$ repo sync
SVN cannot read current repair method
Description:Can't read file: End of file found appears when SVN submits the record. file: repository/db/txn_current, repository/db/current, where current records the latest version number, txn_current records the folder where version number files are stored in the version library.
Cause:When a file is submitted, the svn server is forcibly disabled, causing the version information file to fail to be written, and the version record file txn_current and current become garbled.
Solution:Re-write the correct version information to the current and txn-current files. Generally, the latest version is incorrect and can only be rolled back to the previous version. Find the latest version, which is generally the version with an error. if the error is 9010, it can be obtained from (\ Repositories \ ProjectName \ db \ revprops \ X ), X is the folder name. Almost all version numbers can find the corresponding file name in these directories and find the maximum version number 9010. If the file is opened in a record book with garbled characters, if an error occurs, delete the file. Accordingly, the version number of the previous version is 9009, and the corresponding X is usually the folder of 9. Update txn-current with the X folder name "9" written in it, and press enter to wrap the text and save it. Update current, write 9009 in it, and press enter to wrap and save. Android You may want to manually restart adb from the Devices view.
Description:An error occurred while compiling and running: You may be want to manually restart adb from the Devices view.
Cause:If a problem occurs with the adb service, restart the service.
Solution:Enter the following command in the Command window:
adb kill-serveradb start-server
After connecting to the mobile phone through Eclipse, DDMS always displays the problem of connect attempts.
Description:After connecting to the mobile phone of Eclipse, DDMS always displays connect attempts and reports Adb connection Error: An existing connection was forcibly closed by the remote host Error.
Cause:Eclipse connection problems.
Solution:Add system environment variable: Enter computer properties, click Advanced Settings environment variable, add the new variable ANDROID_SDK_HOME = D: \ android \ sdk (D: \ android \ sdk is the location of android-sdk-windows), and Path appends % ANDROID_SDK_HOME % \ tools. Aborting commit: 'xxxxxx' remains in conflict
Description:An error occurred while submitting SVN code: Aborting commit: 'xxxx' remains in conflict!
Cause:Code conflicts are inevitable when SVN is used. If the local file has been deleted when the code is updated, but the code has been modified on SVN, the update may fail to conflict and commit the code.
Solution:The Eclipse solution is as follows:
1. Right-click the project directory;
2. Select a Team;
3. Select Show Tree Conflict (Conflict Tree );
4. view the conflict list and right-click the conflict file;
5. Mark as solution.
The Android stuio solution is as follows:
1. Right-click the project directory;
2. Select Sunversion;
3. select Commit Files;
4. The file submission list is displayed. Check the file to be submitted. If the red box of the file flag is selected, the file conflict occurs. Double-click the file to proceed to the next step;
5. There are two options: one is SVN-based and the other is local-based. If the file needs to be deleted and deleted locally, select "Accept Yours" as the local master, so that no conflict will occur after the submission. Compile an error: com. android. dex. DexIndexOverflowException: method ID not in [0, 0 xffff]: 65536
Description:The following error is reported during compilation: com. android. dex. dexIndexOverflowException: method ID not in [0, 0 xffff]: 65536, or fails to be installed, and an error is returned: dexopt failed on '/data/dalvik-cache/data @ app package name @ classes. dex 'res = 65280 (number of methods ).
Cause:This is because the number of methods during compilation exceeds the limit and the dexopt buffer size during installation is insufficient to store the number of methods.
Solution:Set Android SDK build Tools 21.1 and later versions in the Build File of Gradle, set multiDexEnabled true in defaultConfig, and add the multidex dependency: compile 'com. android. support: multidex: 1.0.0 '. Finally, you need to add the support for multidex in the Code. The final configuration file is as follows:
Apply plugin: 'com. android. application 'android {Listen 22 buildToolsVersion "22.0.1" // Step 1 defaconfig config {minSdkVersion 15 targetSdkVersion 22 versionCode 1 versionName "1.0" multiDexEnabled true // Step 2} lintOptions {abortOnError false} dependencies {compile fileTree (dir: 'libs', include :['*. jar ']) compile com. android. support: multidex: 1.0.0 // step 3}

The comments section in the code is required for this setting. There are three methods to add multidex support to the Code:
Method 1: Specify the Application as MultiDexApplication in the manifest file;
Method 2: Let the Custom Application inherit from MultiDexApplication;
Method 3: implement the attachBaseContext method in the custom Application, and add the following code in it:MultiDex.install(this)This method is executed first than the onCreate method.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.