- Общая информация об отладке в Android Studio
- Точки останова (Breakpoints)
- Отслеживание потребления памяти
- Android Device Monitor
- Скриншоты и видео
- Browse SQLite database in Android Studio
- Debugging SQLite Databases in Xamarin-based Android Apps
- What is SQLScout?
- Step-by-step Guide
- 1. Build and import the APK into Android Studio
- 2. Configure the project’s Android SDK
- 3. Run the application
- 4. Locate the application’s database file in the Device File Explorer
- 5. Open the selected database file
- 6. Viewing and updating database records
- Conclusion
- SQLScout for Visual Studio?
Общая информация об отладке в Android Studio
Студия позволяет отлаживать приложения на эмуляторе и на реальных устройствах. Вы можете просматривать системный журнал логов, устанавливать точки останова, проверять значения переменных и вычислять выражения во время работы, делать скриншоты и видеозаписи.
Когда вы разрабатываете приложение, то студия собирает отладочную версию программы, соединяется с устройством/эмулятором, устанавливает и запускает её.
Обычно для запуска приложения вы используете значок с зелёным треугольником Run (Shift+F10) на панели инструментов. Для отладки следует нажимать соседнюю кнопку Debug (Shift+F9) с изображением жучка .
Остальные действия будут идентичными — вам надо выбрать устройство, на котором будет происходить отладка.
Android Studio откроет окно Debug. Можно открыть его вручную через кнопку 5: Debug в нижней части среды разработки. Окно показывает потоки и переменные в вкладке Debugger, статус устройства в вкладке Console и системные логи в вкладке Logcat.
Если приложение уже запущено, то необязательно его перезапускать для работы в отладочном режиме. Вы можете нажать на кнопку Attach debugger to Android proccess , которая идёт сразу после кнопку с жучком.
В вкладке Logcat вы видите системные сообщения, включая сообщения от вашей программы, если вы использовали их своём коде. Для записи логов используется класс Log. Подробнее о нём в отдельной статье.
Логи можно просматривать также через панель Android DDMS (Dalvik Debug Monitor Server) — запускается через кнопку 5: Android в нижней части студии. В Android DDMS вы можете просматривать логи только нужного процесса, если нажмёте на кнопку Only Show Logcat from Selected Process .
Точки останова (Breakpoints)
Точки останова позволяет приостановить выполнение программы на нужной строчке кода, проверить значение переменных, запустить выражение и продолжать выполнение кода строчка за строчкой. Позволяет выявить ошибки, которые не удаётся вычислить простым просмотром кода.
Откройте свой исходник, определите строку кода, в которой хотите поставить точку останова и щёлкните по ней. Строка окрасится в жёлтый цвет. Щёлкните в левой части редактора кода в серой области. В этом месте появится красный кружок (повторный щелчок уберёт его), а строка примет розовый цвет. Точку останова можно ставить не только для исполняемого оператора, но и на комментарии.
Запустите приложение в отладочном режиме. Когда выполнение программы дойдёт до установленной точки останова, то студия прекратит дальнейшее выполнение приложения, кружок станет ещё более красным и строка будет выделена. И затем вы можете попытаться выявить причину ошибки.
Для просмотра всех точек останова и их настроек щёлкните на кнопке View Breakpoints в левой части панели Debug . Появится отдельное диалоговое окно.
После того, как вы установили точки останова, щёлкните кнопку Rerun для повторного запуска программы. Когда выполнение кода дойдёт до установленной точки останова, студия выполнит паузу и подсветить строку кода. Панель Debug позволит проверить переменную и выполнить код шаг за шагом.
Для проверки переменных раскройте список в панели Variables. Если панель не видна, то щёлкните кнопку Restore Variables
Для вычисления выражения в текущей точки щёлкните кнопку Evaluate Expression
Для перехода на следующую строку кода без выполнения щёлкните кнопку Step Over .
Для перехода на первую строку кода внутри метода щёлкните кнопку Step Into .
Для перехода на следующую строку за пределами текущего метода щёлкните кнопку Step Out .
Чтобы продолжить работу приложения в нормальном режиме, нажмите кнопку Resume Program .
Отслеживание потребления памяти
Студия позволяет также отслеживать потребления памяти объектами и показывает, какие классы и потоки используют объекты.
Запустите студия в отладочном режиме, щёлкните 6: Android, чтобы открыть панель Android DDMS. Выберите вкладку Devices | logcat, выберите ваше устройство из выпадающего списка, выберите вашу программу по имени пакета из списка запущенных программ.
Щёлкните кнопку Start Allocation Tracking . Начинайте пользоваться программой.
Повторно нажмите на предыдущую кнопку Stop Allocation Tracking. Студия покажет объекты, выделенные системой для работы.
Android Device Monitor
Для анализа потребления памяти, сетевого трафика, поведения приложения при входящих звонках можно использовать графический инструмент Android Device Monitor. Щёлкните кнопку Monitor на панели инструментов. Android Device Monitor откроется в новом окне. Опытные программисты увидят знакомое окно, когда работали с Eclipse.
Скриншоты и видео
Вы можете делать скриншоты и видео работающего приложения.
Запустите приложение и откройте панель 6: Android. Щёлкните кнопку Screen Capture в левой части панели.
По такому же принципу можно сделать видеозапись через кнопку
Источник
Browse SQLite database in Android Studio
Oct 7, 2018 · 2 min read
Have you ever wondered how to debug SQLite database created in the Android app? How to see the schema and the content of the database? Until recently, I used Stetho — a debug bridge for Android applications developed by Facebook, which enables you to debug an Android app using Chrome Dev Tools. Although it’s a little inconvenient, it does the job.
Recently, I discovered yet another way. First open Device File Explorer, which is now built-in directly into Android Studio. Then navigate to /data/data/[your.package.name]/databases folder, right-click on your database file and Save As… (The app must be compiled using a debug build variant, otherwise you won’t be able to browse its data directory.)
Now you have the SQLite database file and you can open it in a SQLite browser of your choice, e.g. http://sqlitebrowser.org. But If you don’t want to leave the IDE, you can install the Database Navigator plugin:
Android Studio— Preferences… — Plugins — Browse Repositories… — Database Navigator — Install
After restarting Android Studio, open DB Browser pane, click + button and add a new SQLite connection by choosing a path to your database file. Then you can easily browse your database schema. To view a table content, double-click on a table name and either specify a query or select No Filter.
In this way, you can easily see what is happening in the SQLite database on your device or emulator without even having to leave Android Studio. 👏
Источник
Debugging SQLite Databases in Xamarin-based Android Apps
Oct 29, 2018 · 5 min read
We recently got an email asking if it is possible to use SQLScout to debug SQLite databases in Xamarin-based Android applications. I was happy to find out that it is actually possible, and better yet, fairly straightforward.
What is SQLScout?
SQLScout is a plugin for Android Studio and IntelliJ IDEA that provides first-class support for debugging and managing SQLite databases. Its features include:
- Room support, including automatic migration to Room and ability to run queries specified in @Query annotations.
- A schema explorer for SQLite databases stored in Android devices and the file system.
- A powerful SQL editor that supports SQLite’s SQL dialect and includes code completion for SQLite-specific functions and symbol navigation.
- A data console to visualize and update database records without the use of SQL statements.
- Database diagrams!
When working with databases in Android applications, SQLScout offers 2 options:
- Download the database to your computer, for offline use. Any record changes are local to the downloaded copy, but can be easily uploaded back to the device.
- “ Live Device Connection” where you can manage and update database records directly from the Android device, without downloading any files.
Step-by-step Guide
To debug and manage databases in Xamarin-based Android application using SQLScout, we only need to follow a few steps:
1. Build and import the APK into Android Studio
We first n e ed to build the Android application and its APK in Visual Studio. Once we have the APK file, we can import it in Android Studio.
SQLScout is a plugin for Android Studio and it doesn’t work with Visual Studio (the IDE of choice when working with Xamarin). We can work around this limitation by using Android Studio’s ability to import pre-built APKs for debugging.
Importing the APK into Android Studio is as simple as clicking the “Profile or import APK” action from the IDE’s “Welcome” page, and then selecting the APK file from the file system.
Android Studio will create a project for the imported APK. The created project, like any Android project, will have a Run Configuration to run or debug the application in an Android device or emulator.
2. Configure the project’s Android SDK
Before we run the application, we will need to set the Android SDK to use in the project. This seems like a bug in Android Studio, since the APK’s manifest already specifies the platform level to use, and the IDE should be able to pick this up to automatically set up the project’s SDK.
To me, the easiest way to set up the project’s SDK is to open the file AndroidManifest.xml and select the “Open Project Structure” link on the editor’s notification header (figure 2). Then, in the “Project Structure” dialog, select an Android SDK from the drop-down or create a new one(figure 3).
3. Run the application
Now we can run our application (for debugging the app’s database we don’t need to execute the app in debug mode).
4. Locate the application’s database file in the Device File Explorer
Once the application is up and running, we will locate the application’s database file in Android Studio’s Device File Explorer. In Android applications, database files have the extension “db” and are under the path /data/data/
is the value in the “package” attribute in AndroidManifest.xml). In the case of Xamarin-based applications, the path for database files is /data/data/
/files (at least this is the path in the samples I found).
5. Open the selected database file
SQLScout’s tight integration with Android Studio allows us to connect to a database file by simply double-clicking it or selected the “Open” action in the context menu.
SQLScout will automatically download the database file to the local file system and connect to it. After the connection to the database is established, we will be able to browse the database’s schema in SQLScout’s SQLite Explorer.
6. Viewing and updating database records
From this point on, we can view and update records in the database. SQLScout provides 2 ways to do this:
- SQLite Console . The console lets us visualize all the records in a table. It also supports adding, updating and removing records through its UI, without using SQL statements (figure 6).
- SQL Editor . SQLScout’s SQL editor supports SQLite’s SQL dialect, and provides all the functionality we would expect from an IDE editor: syntax highlighting, code completion (including SQLite-specific functions) and symbol navigation. We can also execute SQL statements from the editor with a single click (figure 7).
To update our application’s database with the changes we made to the local copy, we simply need to click the “Upload” action in SQLScout’s SQLite Explorer.
Conclusion
In this article, we have explored how to easy it is to use SQLScout to debug SQLite databases in Xamarin-based Android applications:
- Build the APK using your favorite IDE/build system (Visual Studio, in the case of Xamarin).
- Import the built the APK into Android Studio using its “Profile or import APK” feature.
- Set the project’s Android SDK (hopefully future versions of Android Studio will do this automatically).
- Run the application in an Android device or emulator.
- Locate the database file in Android Studio’s Device File Explorer and open it.
- From this point you can use SQLScout to view and update the records in the database.
SQLScout for Visual Studio?
SQLScout is a plugin for Android Studio and it doesn’t work with Visual Studio. The person who asked us whether it is possible to use SQLScout to debug databases in Xamarin also mentioned that he would like to use SQLScout in Visual Studio, instead of using two IDEs to develop applications and debug databases.
Источник