Android studio scanning files to index

Android Studio «Scanning For Files To Index»

I am trying to achieve the following project structure in Android Studio

Where projectA is an «app» module created by Android Studio which I have renamed, and projectB is a Kotlin project I wish to depend on in the app. I can get the projects to appear correctly as modules in my project however no matter what I try, as soon as I add projectB to my Android Studio project, it seems to get stuck in a loop «searching for files to index». When I look at the files it is always just looping through the same 2-3 files. They are always META-INF files but not always the same ones.

How do I successfully add a module to an Android Studio Project without hitting this error or how can I set out my project from the start to achieve this structure?

Answers

The problem seemed to be that I had a gradle/ directory under my project/projectB directory that was there because the project was originally created as a standalone project by IntelliJ. Deleting that fixed the issue.

With Android Studio 2.3(AS) the project works fine and i can able to run the App. After updating the AS to Android Studio 3.0. i too got the error as below for libraries and build types.

To Solve the issue, simply.

you have in your (app) build.gradle file, You have to include all the buildTypes < >with same names as like

in to build.gradle files of All libraries/modules included in project.

clean and rebuild the project, the issue will be fixed.

Still issue not fixed, update the gradle-wrapper.properties to

I found this question while investigating a similar problem, and I solved mine, so maybe my experience will help.

Observations

My problem was similar to yours in that the Wanted context had the javaHome as the path to the JRE embedded in the IDEA install folder, and the Actual context had it as the first version of Java on my path. I found several similar error reports online but none had the IDEA embedded JRE as the Wanted version.

The Wanted Java version happened to be a system-wide install of the JRE, and not the JDK I had configured for the project, nor the value set for JAVA_HOME , which made me very suspicious (and confused). Re-ordering my path caused it to use yet another «unwanted» version of Java, so it was clearly using the path to choose what to run, but it wasn’t clear why. I couldn’t make IntelliJ’s embedded JRE be first on my path, because I needed that to be the JDK for various reasons, so I needed another solution.

Источник

Методы лечения различных ошибок в Android Studio при разработке проекта

Сегодня хотел бы поделиться своим анализом и способами лечением разных ошибок при разработке своего продукта в Android Studio. Лично я, не раз сталкивался с различными проблемами и ошибками при компиляции и/или тестировании мобильного приложения. Данный процесс, всегда однообразный и в 99% случаев и всегда нужно тратить n-колличество времени на его устранение. Даже, когда ты уже сталкивался с данной проблемой, ты все равно идешь в поисковик и вспоминаешь, как же решить ту или иную ситуацию.

Я для себя завел файлик, в котором отметил самые частые ошибки — потратив на это несколько часов и перечислил самые популярные ошибки (в дальнейшем планирую просто их запомнить), чтоб сократить свое время в дальнейшем.

Итак, начну по порядку с самой распространенной проблемы и дальше буду перечислять их по мере появления:

1) Если подчеркивает красным код, где используются ресурсы: R. — попробовать (но вероятно не поможет): Build -> Clean Project.

В принципе на Build -> Clean Project можно не терять времени, а лучше всего — слева переключиться на Project, открыть каталог .idea, затем каталог libraries и из него удалить все содержимое. Затем нажать кнопку Sync Project. А затем (если все еще красное, но скорее всего уже будет все ок ) Build -> Clean Project.

2) После внезапного выключения компьютера, после перезапуска может быть во всех проектах весь код красным. Перед этим может быть ошибка: Unable to create Debug Bridge: Unable to start adb server: Unable to obtain result of ‘adb version’. Есть три решения — первое помогло, второе нет (но может быть для другого случая), а третье — не пробовал:

Читайте также:  Андроид один экран быстрее

а) File — Invalidate Caches/Restart — Invalidate and Restart

б) Закрыть студию. В корне папки проекта удалить файл(ы) .iml и папку .idea. Вновь запустить студию и импортировать проект.

в) Нажать Ctrl-Alt-O и запустить оптимизацию импорта.

Кстати, adb сервер можно проверить на версию (и работоспособность) и затем перезапустить:

3) Если Android Studio выдает приблизительно такую ошибку: Error:Execution failed for task ‘:app:dexDebug’.

Надо слева переключиться на опцию Project, найти и удалить папку build которая лежит в папке app, т.е. по пути app/build. Затем перестроить весь проект заново: Build -> Rebuild Project.

Такое же решение если ошибка типа: «не могу удалить (создать) папку или файл» и указан путь, который в ведет в app/build. Тоже удаляем папку build и ребилдим проект.

4) В сообщении об ошибке упоминается heap — виртуальная память. А ошибка обычно вызвана ее нехваткой, т.е. невозможностью получить запрашиваемый объем. Поэтому этот запрашиваемый объем надо уменьшить, т.е. переписать дефолтное значение (обычно 2048 MB которое можно изменить в настройках), на меньшее 1024 MB.

В файле проекта gradle.properties пишем:

5) Android Studio пришет примерно такую ошибку: Plugin is too old, please update to a more recent version, or set ANDROID_DAILY_OVERRIDE environment variable to «83648b99316049d63656d7276cb19cc7e95d70a5»

Возможные причины (кроме необходимости регулярного обновления SDK):

а) Загруженный проект был скомпилирован с помощью уже несовместимого старого gradle плагина. В этом случае надо найти и подключить в своем build.gradle проекта этот более старый плагин. т.е. попробовать более старые версии, например: 1.1.3 (часто именно 1.1.x и подходит).

Найти все версии можно здесь.

б) Если в build.gradle проекта используется beta-версия плагина — это означает, что срок ее истек. Посмотреть последние релизы (продакшн и бета) можно также здесь:

6) Иногда при подключении сторонних библиотек могут дублироваться некоторые файлы (обычно связанные с лицензированием). В сообщении будет что-то содержащее слова: duplicate files. Решение — надо посмотреть в сообщении об ошибке или в документации подключенной сторонней библиотеки — какие именно файлы стали избыточными, и перечислить их в build.gradle модуля для исключения (exclude) из билда.

Это делается в директиве packagingOptions (которая, в свою очередь, находится в директиве android).

Источник

Barcode Scanning API Programmer’s Guide

Overview

The aim of this guide is to familiarize the user with the Barcode Scanner SDK for Android and its functionalities. Instructions are given in detail about integrating the Barcode Scanner SDK to Android Studio Project and to work with APIs for users to develop their applications. The provided code snippets can benefit the user in implementing LED, Beeper, Firmware Updates etc. Each functionality is explained individually with screenshots where necessary for the easy understanding of the user and to make development with reduced time and effort.

Configuring Development Environment

Adding the Barcode Scanner SDK to the Android Studio Project

Add the barcode_scanner_library_vx.x.x.x (ex: barcode_scanner_library_v2.4.10.0) as a Module in your Android Studio Project by navigating to, File -> Project Structure -> Modules

Click on the ‘+» icon to add the ‘barcode_scanner_library_vx.x.x.x.aar’ file. Then select ‘import JAR/AAR Package’ and click ‘Next’.

Locate the Android SDK library package, ‘.aar’ file to add to the project.

After adding the Module successfully, select the Dependencies from the options given. In the Modules section select ‘app’. Then in ‘Declared Dependencies’ section click the ‘+’ icon.

From the dropdown select ‘Module Dependency’.

Select the added Module and click ‘OK’ to proceed.

Adding Permissions in the Manifest File

Following permissions should be added in the Manifest File in order for the app to establish a Bluetooth connection with the scanner.

Connecting the Scanner to the Device

User can make a connection between the scanner and the device using either ‘SSI BT Classic (discoverable)’ Barcode or ‘Scan-To-Connect’ Barcode.

Using the ‘SSI BT Classic (discoverable)’ barcode (This is available in the Program Reference Guide of the Zebra Scanner Product), a Bluetooth connection can be established with the scanner and the device on which the app is running. Scan the barcode and start a Bluetooth scan in your device. Once the scanner is detected, pair with it.

The noteworthy difference between the two barcodes is that, Scan-To-Connect doesn’t require setting up the connection manually with the Android device. Unlike ‘SSI BT Classic (discoverable)’, a one scan of the Scan-To-Connect barcode establishes a connection with both the device and the app in one go.

Читайте также:  Android как определить версию

SDK Installation

Inside the ‘onCreate’ method SDK must be initialized. Out of the several available operational modes (such as DCSSDK_MODE.DCSSDK_OPMODE_SNAPI, DCSSDK_MODE.DCSSDK_OPMODE_BTLE), Operational Mode of the Scanner must be set to DCSSDK_OPMODE_BT_NORMAL. Even though other operational modes are present, this guide is mainly focused on making a connection via DCSSDK_OPMODE_BT_NORMAL and carrying out the functions. Along with the initialization of the SDK an ArrayList to contain scanner information must be created.

Establishing a Connection with the Scanner

For the ease of explaining, two buttons have been used in the UI to establish the connection with the connected scanner and to make the scanner beep. With the press of the button used for connecting, the following ‘connectToScanner’ method gets called. If the ‘sdkHandler’ is not null, ‘scannerInfoList’ will get filled with all the Scanners that are connected to the device. Here inside the try catch block the ‘scanner ID’ of the first connected scanner in the ‘scannerInfoList’ is taken and then ‘connectScanner’ AsyncTask gets executed. Here an AsyncTask is used to prevent the main thread from being blocked while the scanner connection task is taking place.

With ‘dcssdkEstablishCommunicationSession’ the app makes a connection with the Scanner.

Making the Scanner Beep

Here the ‘BeepScanner’ AsyncTask gets called and then the ‘executeCommand’ method gets executed. One has the option to replace 1 in the ‘inXml’ with any integer between 0 and 26 as there are 27 beep combinations available.

Given below is a code snippet detailing the 27 combinations available for the scanner.

Inside the ‘BeepScanner’ AsyncTask, parameters such as ‘scannerId’, ‘opcode’, ‘outXml’ get passed on to the ‘executeCommand’ method which finally gives out the corresponding beep.

LED On/Off

The following UI is used to explain the LED ON/OFF states of the scanner. Code snippets for establishing a Bluetooth connection with the scanner are given above.

The method ‘redLedOnClicked’ gets called with the press of the ‘LED ON’ button. Similarly, ‘redLedOffClicked’ gets called with the press of the button ‘LED OFF’.

Using the following code, ‘inXml’ is created based on the ‘RMD attribute value’ passed on to it by ‘redLedOnClicked’ and ‘redLedOffClicked’ methods.

LED ON/OFF takes place when the ‘Scanner ID’ and the ‘opcode’ parameters are sent to the ‘executeCommand’ method.

Firmware Update

Firmware can be updated using ‘.SCNPLG’ files. These plugins can be obtained using the 123Scan Configuration Utility. Once 123Scan is installed, Plugin files for supported scanners can be found in ‘C:\ProgramData\123Scan2\Plug-ins’.

First of all, permissions have to be included in the Manifest file for the device to access firmware files in the storage.

Secondly, the class ‘IDcsSdkApiDelegate’ must be implemented. Then the declaration of the String ‘inXml’ must take place.

The object ‘sdkHandler’ should be notified of the implemented class. Then it is necessary to subscribe to events in order to be updated when the scanner gets reconnected, especially after a firmware update. The following code snippet takes care of that.

With the implementation of ‘IDcsSdkApiDelegate’ interface the following methods will be implemented as well.

Once the ‘Update Firmware’ button of the given UI is clicked, the following ‘updateFirmware’ method gets called. Note that the location of the firmware file is given in the ‘inXml’ String. The ‘UpdatingFirmware’ ‘AsyncTask’ gets executed as the next statement fulfilling requested task.

Finally, ‘executeCommand’ is called when the ‘scannerId’,’opcode’ and ‘outXml’ are all set.

Once a firmware update has started, user can be notified of the firmware update events. This is achieved by declaring a ‘handler’ inside ‘dcssdkEventFirmwareUpdate(FirmwareUpdateEvent firmwareUpdateEvent)’ method. Integer ‘FW_UPDATE_EVENT’ must be defined at the beginning of the class.

It is required to use handlers so as not to block the Event thread. With the use of a handler, the main thread will not be halted for the current process to execute. Multiple threads can run parallelly without interrupting each other.

Inside the handler, ‘firmwareUpdateEvent’ parameter gets passed on to the method ‘processFirmwareUpdateEvents’.

Several types of Firmware Update events are available. Namely SCANNER_UF_SESS_START, SCANNER_UF_SESS_END, SCANNER_UF_DL_PROGRESS, SCANNER_UF_STATUS, SCANNER_UF_DL_START and SCANNER_UF_DL_END. SCANNER_UF_STATUS event will only take place in the event of a firmware update error.

Once the firmware update process is finished, it is required for the firmware to be launched on to the scanner and be rebooted. This is achieved by the code inside the event ‘SCANNER_UF_SESS_END’. It is important for the working thread to sleep for a second before rebooting takes place.

Читайте также:  Камера с эффектами для android

As a final step, a call to ‘executeCommand’ method is made for the launching of the firmware on to the scanner to be completed. This can be verified with the rebooting beep of the scanner.

After rebooting of the scanner, it will be automatically reconnected to the app if Scan-To-Connect barcode had been used initially to connect the scanner to the app. If the connection had been made with the SSI BT Classic (Discoverable), scanner must be reconnected to the app manually. This can be achieved by pressing the ‘connect’ button in the UI. Once rebooting is completed and if the ‘connect’ button of the UI is pressed, the user can be notified of this reconnection by the ‘dcssdkEventCommunicationSessionEstablished’ event.

Connect Scanner Using Scan-To-Connect (STC) Barcode

Preliminary environment setting has been described in previous sections. First it is ensured that the ACCESS_COARSE_LOCATION permission is given, if not, permission is set inside the ‘onCreate’ method along with the execution of the ‘initializeDcsSdk’ method where initializations take place.

Inside the ‘initializeDcsSdk’ method, Bluetooth operational mode is set and a call is made to ‘generatePairingBarcode’.

Inside the ‘generatePairingBarcode’, value of ‘barCodeView’ is checked. For devices with Android versions 6.xxx and below, the method ‘updateBarcodeView’ is called directly and the Bluetooth Address of the device is retrieved automatically rendering the STC barcode across the screen.

The code snippet given below explains how the SDK manages to obtain the Bluetooth Address of Android 6.xxx and below versions. Please note that this snippet of code is already present in the SDK and doesn’t need to be included in any custom application development.

For Android versions 7.0 and above value of ‘barCodeView’ will be null and displaying the STC barcode will require the user to manually enter the Bluetooth address of the android device. The following explanation of the UI screenshot is for the easy understanding of users with Android 7 or higher version devices. An EditText is provided in the dialog box for the user to enter the Bluetooth address. Once the Bluetooth Address is entered and the ‘OK’ button is pressed, the ‘displayStc’ method gets called after which the STC barcode gets displayed on the screen.

Here the barcode is generated based on the Bluetooth Address, Bluetooth Protocol and the Scanner Configuration provided to the method dcssdkGetPairingBarcode(DCSSDKDefs.DCSSDK_BT_PROTOCOL.SSI_BT_LE, DCSSDKDefs.DCSSDK_BT_SCANNER_CONFIG.SET_FACTORY_DEFAULTS, bluetoothAddress).

Given below is the set of available Bluetooth protocols in the Barcode Scanner SDK.

Provided below is the set of supported Bluetooth scanner configurations in Barcode Scanner SDK.

Code snippets extracted from Barcode Scanner SDK are for information purpose only and need not be included in the Java file.

Note that the operational mode set using the method, ‘sdkHandler.dcssdkSetOperationalMode(DCSSDK_OPMODE_BT_LE)’ should be compatible with the Bluetooth protocol used. For instance, if ‘DCSSDK_OPMODE_BT_NORMAL’ is used as the operational mode, then the Bluetooth protocol to be used is the ‘SSI_BT_CRADLE_HOST’.

Scanner Connect Event

Once the STC barcode is available on the screen, the connection can be established by scanning the barcode with the Bluetooth scanner. The beep tone of the scanner confirms that the scanner has paired with the device as well as with the App.

Scanner Connect Event

If the user wishes to disconnect the scanner from the App as well as from the device, it can be achieved by pressing the ‘Disconnect’ button in the UI. Here the ‘scannerId’ is obtained from the ‘scannerInfoList’ and the method, ‘dcssdkTerminateCommunicationSession(scannerId)’ is provided with the obtained ‘scannerId’ to terminate the connection.

Scanner Enable/Disable

When the connection between the device and the scanner has been established, enabling and disabling the scanner can be achieved using the following two methods.

With the press of the ‘ENABLE’ button the following method gets called. When the OPCODE is given as ‘DCSSDK_DEVICE_SCAN_ENABLE’ along with the corresponding inXml, the scanner can be used for barcode scanning purpose.

With the press of the button ‘DISABLE’ barcode scanning functionality of the scanner will be disabled.

Get Currently Connected Scanner and Paired Devices

All the paired Bluetooth devices can be obtained using the API call ‘dcssdkGetAvailableScannersList’.

First the array list must be initialized inside the class.

With the API call ‘dcssdkGetActiveScannersList’, information about the scanner that is paired with the device as well as connected to the app can be obtained. This is accomplished by the ‘getActiveScanners’ method.

Источник

Оцените статью