App inspector android studio

App inspector android studio

This page is deprecated.

The Layout Inspector in Android Studio allows you to inspect your app’s view hierarchy at runtime from within the Android Studio IDE. This is particularly useful when your layout is built at runtime rather than being defined entirely in an XML layout.

The Layout Inspector available in Android Studio 2.2 is an early release. It’s a work in progress that will supersede the Hierarchy Viewer tool once it is feature complete. For now, it provides a quick solution to inspect the view properties of your layout without leaving the IDE.

To open the Layout Inspector, first launch your app on a connected device or emulator. Then open Android Monitor window, select your device and app process, and then click Layout Inspector . You can also open it by clicking Tools > Android > Layout Inspector in the menu bar.

Layout Inspector currently provides just a snapshot of the layout at the time you open the tool. The left pane shows the view hierarchy as a list, the center pane shows a screenshot of the layout, and the right pane shows all the properties for the selected view.

Clicking a view in the hierarchy list highlights the same view in the screenshot, and vice versa.

If your layout includes overlapping views, then by default, only the view in front is clickable in the screenshot. To make the view behind clickable in the screenshot: Right-click the in-front view in the view hierarchy and uncheck Show in preview .

If you’re debugging your app or simply interacting with it, you must open a new instance of the Layout Inspector to grab a new snapshot showing the layout changes. Each snapshot is saved in a separate .li file at projec

Источник

Background Task Inspector

Android Studio includes multiple inspectors, such as the Layout Inspector and Database Inspector, to help you investigate and understand the internal state of your running app. With Android Studio Arctic Fox, we are releasing a new inspector to help you monitor and debug workers your app schedules using WorkManager 2.5.0 or higher.

WorkManager is the recommended way to run asynchronous tasks in the background, even after the app is closed. Although it’s easy to configure your tasks as WorkManager workers, once a worker is queued, its execution is difficult to monitor and tricky to debug if you face issues.

With the Background Task Inspector, you can easily monitor the status of a worker, see its relationship with other chained workers, or inspect details, such as the worker output, frequency, and other timing information. Let’s see what the Background Task Inspector can do on a sample project.

To demo the Background Task Inspector, I’ll use the WorkManager sample app in architectural-components repo. If you want to give it a try, you can check out the repo and follow along as you read the article.

This app uses WorkManager to apply user selected filters on the selected photo. After running the app, users can choose a photo from the gallery or simply use a random stock photo. To see how the Background Task Inspector works, I run the app and select an image to apply some filters.

Each filter is implemented as a WorkManager worker. After a short wait, the app displays the photo with the selected filters applied. Without any further knowledge on the sample app, let’s see what else I can figure out by just using the Background Task Inspector.

To open the Background Task Inspector, select View > Tool Windows > App Inspection from the menu bar.

With the Background Task Inspector tab selected in the App Inspection window, I run the app again on a device or emulator running API level 26 or above. If it is not automatically selected, I choose the app process from the drop-down menu. After connecting to the app process, I can then go to my running app and select all filters and click apply. This time I can see a list of running jobs in the Background Task Inspector.

Читайте также:  Word 4pda android без подписки

The Background Task Inspector lists the class name, current state, start time, retries and the output data of all the running/failed or completed jobs. Clicking on a specific job from the list opens the work details panel.

This panel provides more detailed information for each worker’s description, execution, work continuation and the results. Let’s take a close look at each section.

Description section lists the Worker class name with the fully qualified package, as well as the assigned tag and the UUID of this worker.

Next, the execution section shows the worker’s constraints (if any), running frequency, it’s state and which class created and queued this worker.

WorkContinuation section displays where this worker is in the work chain. You can check the previous or the next worker, if any, or the other jobs in the work chain. You can click to another Worker UUID to navigate and see the selected worker’s details. Looking at this work chain, I can see that the app uses 5 different workers. The number of workers may differ depending on the choice of filters by the user.

This is great but imagining the work chain is not always easy if you are not familiar with the app. Another great feature of Background Task Manager Inspector is the ability to display the work chain as a graph. To do that I click the ‘Show in graph’ link in the WorkContinuation section or switch to Graph View by clicking the ‘show Graph View’ button on top of the jobs list.

This graph view can help you to understand the order of the workers, the data which is passed between workers and the current state of each worker.

The last section in the Work Details panel is the Results pane. In this section you can see the start time, retry count and the output data of the selected worker.

Let’s say I want to test what happens when a worker stops. To do that, I’ll run the app again, select the worker, wait until it changes to running state and click the ‘Cancel Selected Work’ on the top left. Once I do that, the worker I selected and the remaining workers in the chain change their status to canceled.

Graph view becomes even more useful if your app includes complex chaining relationships, such as the one here. The graph allows you to quickly see relationships between a complex set of workers and monitor their progress.

If you want to try the Background Task Inspector with a more complex graph or make some WorkManager art, you can find the code here and add the DummyWorkers to the continuation object as seen here.

Background Task Inspector will be available with Android Studio Arctic Fox release but it is already available for you to try in the Arctic Fox Preview channel and soon will be in beta! If your app uses Work Manager, please give a try and let us know what you think or simply share your WorkManager art with us!

Источник

Применение SQLiteOpenHelper и Database Inspector в Android-разработке

Автор статьи, перевод которой мы публикуем сегодня, хочет рассказать об использовании баз данных SQLite в Android-разработке. В частности — он коснётся тут двух вопросов. Во-первых — речь пойдёт о классе SQLiteOpenHelper , который применяется для работы с базами данных в коде приложений. Во-вторых — он уделит определённое внимание инструменту Database Inspector, инспектору баз данных, встроенному в Android Studio.

Что такое SQLite?

SQLite — это опенсорсная реляционная СУБД, похожая на MySQL. SQLite входит в состав стандартной библиотеки Android, где реализован движок базы данных, не нуждающийся в применении клиент-серверной архитектуры, не требующий особой настройки, поддерживающий транзакции. Для работы SQLite не нужен сервер баз данных. Всё, что нужно, хранится в обычных файлах. Полноценная БД SQLite, в которой имеется множество таблиц, триггеров, индексов и представлений, содержится в единственном, самом обыкновенном файле. Стандартная поддержка СУБД SQLite имеется во всех мобильных телефонах и в большинстве компьютеров. При этом работа с SQLite не требует решения задач по администрированию или настройке баз данных.

Android-разработчик, для выполнения CRUD-операций из своего приложения, может пользоваться пакетом android.database.sqlite.SQLiteDatabase , в котором реализованы все необходимые API.

Класс SQLiteOpenHelper

SQLiteOpenHelper — это класс, встроенный в пакет android.database.sqlite.SQLiteDatabase . Это — вспомогательный класс, который отвечает за создание баз данных SQLite и за управление их версиями. Для того чтобы воспользоваться возможностями этого класса, нужно создать его подкласс, в котором надо переопределить два метода — onCreate() и onUpgrade() . Этот класс позволяет открывать существующие базы данных, создавать новые базы данных и обновлять версии баз данных.

Читайте также:  Кран криптовалюты для андроид

▍Метод onCreate()

Метод onCreate() вызывается при создании базы данных. Он, в процессе жизненного цикла приложения, вызывается лишь один раз. А именно, его вызов производится при первом обращении к методу getReadableDatabase() или getWritableDatabase() . Эти методы принадлежат классу SQLiteOpenHelper .

В следующем примере показано создание экземпляра класса DatabaseHelper , являющегося наследником SQLiteOpenHelper :

Вот код конструктора DatabaseHelper :

Класс SQLiteOpenHelper вызывает метод onCreate() после создания базы данных и создания экземпляра класса SQLiteDatabase . Этот метод, напомним, вызывается лишь один раз, при создании базы данных:

▍Метод onUpgrade()

Метод onUpgrade() вызывается в тех случаях, когда нужно обновить версию существующей базы данных:

▍Пример

Создадим простое Android-приложение и разберём практический пример работы с классом SQLiteOpenHelper . Это приложение, применяя данный класс, позволит нам добавлять записи о работниках некоей компании в таблицу Empdata базы данных Company.db .

Приложение имеет весьма простой интерфейс, описанный в файле activity_main.xml .

Вот содержимое файла MainActivity.java :

Вот содержимое Employee.java :

Вот файл DatabaseHelper.java :

В коде DatabaseHelper.java видно, что класс DatabaseHelper является наследником класса SQLiteOpenHelper .

После того, как база данных создана, можно приступать к работе с ней. В частности — создавать и обновлять поля её таблиц. При решении этих задач можно пользоваться объектом типа ContentValues , который позволяет хранить пары ключ-значение. Именно такие объекты используются для добавления новых записей в таблицы базы данных (с помощью метода insert() объекта SQLiteDatabase ) и для обновления существующих записей (с помощью метода update() ).

Database Inspector в Android Studio

Инструмент Database Inspector позволяет исследовать базы данных, используемые в приложениях, выполнять запросы к ним, модифицировать их, делая всё это во время работы приложений. Database Inspector имеется в Android Studio начиная с версии 4.1. Этот инструмент особенно полезен при отладке механизмов программ, ответственных за работу с базами данных. Database Inspector работает и с обычной реализацией SQLite, и с библиотеками, построенными на её основе, вроде Room. Database Inspector работает лишь с библиотекой SQLite, входящей в состав операционных систем Android, уровень API которых не ниже 26.

Для того чтобы открыть базу данных в Database Inspector нужно выполнить следующие действия:

  1. Запустите приложение в эмуляторе или на устройстве, подключённом к компьютеру. На эмуляторе или на устройстве должно присутствовать API не ниже 26 уровня.
  2. Выполните команду меню View > Tool Windows > Database Inspector .
  3. Выберите процесс выполняющегося приложения из выпадающего меню.
  4. В панели Databases появятся записи о базах данных, которые имеются в выбранном приложении. Теперь можно работать с этими базами данных.

Исследование базы данных с помощью Database Inspector

Обратите внимание на то, что есть одна проблема, связанная с аварийным завершением работы программ на эмуляторе Android 11 при подключении к Database Inspector. Если вы с этой проблемой столкнётесь — здесь вы можете найти сведения о том, как с ней справиться.

Применяете ли вы SQLite в Android-разработке?

Источник

Layout Inspector

Debugging UI hierarchies in Android Studio 4.0+

Debugging UI issues can be tricky. Android Studio 4.0 comes with an updated Layout Inspector that lets you debug your Android app UI (user interface) in a way that’s similar to Chrome dev tools. You can read along or if you prefer you can watch the video.

The Layout Inspector works with your device or the Android Emulator and displays the current view hierarchy. This helps pinpoint issues and discover the root causes. Unlike the previous version, the updated Layout Inspector can show the view hierarchy in a 3D perspective which lets you visually see how views are laid out. With this, you can inspect the view hierarchy in layers. It also shows all the view’s attributes including those inherited from its parents.

Let’s see how the latest version of the Layout Inspector works. To open the Layout Inspector click View and select Layout Inspector under the Tool Windows menu. This opens the Layout Inspector window.

The Layout Inspector only displays a UI hierarchy from a running process. This means you need to connect to a debuggable running app on a device or on an emulator. There are two ways to do this:

  • If you don’t have a running process, connect to a device or start an Android Emulator instance and click run to start the app.
  • If you have a running app process, click on select process, select your running device, and select your running app from the list under the selected running device.
Читайте также:  Лаунчер для сампа для андроид

After you select your app process, the Layout Inspector creates a snapshot of the current UI hierarchy. If you select the Live updates option, the snapshot is dynamically updated as you interact with the app on the device.

This version of the Layout Inspector resembles the previous version, but offers much more capability. To start with, the Layout Inspector can display the UI hierarchy two ways: in the usual 2D outline format, or in a 3D view called rotation mode.

Clicking the rotation button switches between the 2D and 3D view of the UI hierarchy. Clicking the rotation button switches between the two modes. When you are in rotation mode you can rotate the image of the UI hierarchy. Rotation helps you see how views are laid out. Note that rotation is only available on devices API level 29 and above.

You can also select a view and right-click to display only its children.

Similarly, you can display the parents of a selected view.

The pane on the right displays all of the declared and inherited attributes of the selected view. You can navigate to the layout’s corresponding xml file by clicking the link below any declared property. Like the rotation feature, this only works on devices running API level 29 or higher.

With the Layout Inspector, you can also load a new design and compare it to your current UI.

To load a design, click Load Overlay and select a design. After the image loads, you can change the alpha value of the overlay to see the difference between the current layout and the design.

Layout Inspector in Action

So far, we’ve seen how the Layout Inspector works, Now let’s see how it can help solve app issues. Here we have a simple sample app which consists of a fragment with some static content of text and an image.

If you want to try along while reading the post, follow the steps below first.

  1. Open Android Studio 4.0 and select New Project from File menu.
  2. Select Bottom Navigation Activity, click Next and click Finish.
  3. Replace contents of activity_main.xml and fragment_home.xml.
  4. Replace contents of HomeFragment.kt.

When you run the app, you’ll see a cute android — but there is something missing: the bottom navigation tabs. Looking at the layout file, we can verify that the bottom navigation view is present, but somehow it does not appear on the screen.

This looks like a good opportunity to try out the Layout Inspector! Let’s run the app and inspect this issue. Switching to rotation view after connecting to the app process reveals that there are problems with the app UI.

What we see first is that the toolbar is laid out inside the LinearLayout, which is followed by the navigation host. Below that, you see the navigation tabs at the very bottom. It looks like the bottom bar is pushed off the screen.

Maybe the size of the navigation host is wrong. Try setting the navigation host’s height to ‘wrap_content’:

Switching back to Layout Inspector, you can see that the linear layout has the correct size, but the bottom navigation tabs are not placed at the correct position:

There are different ways to fix this. We can add layout weights to the navigation host and the bottom navigation tabs, or we can switch to using constraint layout instead of linear layout but switching layouts is beyond the scope of this post. So let’s add layout weights:

And here is the result:

Voila! Now when we run the app, everything is in the right place.

Try out the new features of the Layout Inspector and let us know what you think! We are always looking to hear what you like, as well as issues you have or features that you would like to see.

Источник

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