Data connection in android

Быстрый старт Data Binding в Android

Введение

Профессионально андроид-разработкой занимаюсь чуть больше года, до этого разрабатывал по Windows Phone и мне понравилась возможность связывать данные из вью модели с самим View при помощи механизма Bindings. А после изучения RX, многие задачи стали решаться более чисто, вью-модель полностью отделилась от View. Она стала оперировать только моделью, совсем не заботясь о том, как она будет отображаться.

В Android такой строгости я не заметил, Activity или Fragment как простейшие представители контроллера чаще всего имеют полный доступ как ко View, так и к модели, зачастуя решая, какой View будет видим, решая таким образом чисто вьюшные задачи. Поэтому я довольно радостно воспринял новость о появлении Data Binding в Android на прошедшем Google IO.

Пока что это только бета релиз, но уже можно протестировать функционал и увидеть направление, в котором двигаются разработчики из Google.

Начало

Я использую Android Studio 1.3. Data binding поддерживает Android 2.1 и выше (API level 7+).

Для сборки используется новый android плагин для Gradle (нужна версия 1.3.0-beta1 и старше). Так как связи отрабатываются во время компиляции, нам понадобиться ещё один плагин к Gradle ‘com.android.databinding:dataBinder:1.0-rc0’. В отличие от того же Windows Phone где механизм привязок реализован глубоко по средством DependencyProperty и в RealTime, в Android эта функция реализуется как бы поверх обычных свойств, во время компиляции и дополнительной кодогенерации, поэтому в случае ошибок будьте готовы разбирать ответ от компилятора.

Итак, заходим в файл build.gradle, который лежит в корневом каталоге проекта (в нём идут настройки Gradle для всего проекта). В блоке dependencies вставляем:

Теперь подключим плагин к конкретному модулю, откроем build.gradle файл, который лежит внутри модуля. По умолчанию app/build.gradle и добавим строчку:

Настройка Layout

Мы должны обернуть наш внешний View в тег
Уже сейчас можно начать его использовать класс Binding для доступа к элементам интерфейса, без использования findViewById. В MainActivity добавим поле и перепишем метод onCreate:

Название поля берётся из Id View, без Id в биндере поле не появиться, если изменить Id View, то поле в биндере сразу же переметнуться. Если с зажатым CTRL нажать на название поля View, то сразу перейдешь к нему в файле разметки. Как по мне так уже одного такого функционала достаточно для того чтобы начать использовать биндинги.

Привязка данных

Например у нас есть карточка пользователя имя и возраст.

Изменим Layout, заменим содержимое LinearLayout на:

И в onCreate заменим последнюю строку на:

Запускаем. Всё работает.
Наверное у всех проектах в активити или в фрагментах встречается такие строчки:

Тут то мы и начинаем использовать непосредственно привязки данных. Перепишем модель:

И добавим в Layout:

На красные выделения студии игнорируем.
Так как мы используем класс View, то его нужно импортировать, добавим в ноду
Или используем его вместе с названием пакета:

Так же возможно в ноде

Конвертеры

Импорт в свою очередь даёт возможность писать конвертеры. Добавим в модель поле с датой рождения и удалим возраст:

Читайте также:  Zenfone 5 как обновить до 5 андроида

Импортируем его в разметку:

Обратная связь и Binding

Попробуем сменить имя пользователя.
Добавим в Layout:

Запускаем и кликаем, тост всплыл, но имя не изменилось. Это случилось из-за того, что модель ни как не известила binder о своём изменении.

Можно создать новую модель и вставить её, но с точки зрения памяти это расточительно:

Или вытащить старую, заменить данные и вставить опять:

Но тогда обновятся все View, связанные с этой моделью. Лучшим вариантом будет связать модель с binder, чтобы она могла его оповестить о своём изменении. Для этого перепишем класс модели, добавив геттеры и сеттеры,

помечая геттеры атрибутом @Bindable, и добавив в сеттеры вызов notifyPropertyChanged(BR.lastName);

Видим новый класс BR, в котором содержатся идентификаторы полей, чьи геттеры помечены атрибутом @Bindable . В Layout оставляем android:text=»@«, меняем только isAdult на adult, c ‘is’ в названии поля возникли проблемы. Запускаем всё работает.

ObservableFields

В пакете android.databinding есть классы, которые могут упростить нотификацию binder об изменении модели:

  • Обёртки над элементарными типами
  • ObservableField
  • ObservableArrayMap
  • ObservableArrayList

Попробуем изменить модель:

По коллекциям аналогично, единственное приведу пример обращения ко ключу к Map:

Из View в Model

Теперь попробуем взять новое имя из UI, привязав EditText к некоторой модели. Так как внутри EditText крутится Editable, то и привязать будет к
Изменю MainActivity:

А в разметку добавлю:

Вот тут возникает проблема, если привязать ObservableField к EditText, то всё будет работать только в сторону View. Как я понял, проблема в том, что Editable, который лежит внутри ObservableField, отличается от того, который лежит внутри EditText.

Если у кого есть идеи — делитесь.

Очень любопытно было увидеть библиотеку для поддержки Data Binding в Android от Google. В документации тоже нет информации про обратную связь данных, но я надеюсь на скорую её реализацию. После официального выхода стабильной версии можно будет посмотреть на интеграцию с JavaRX.

[ Оффициальная документация ]
[ Ссылка на мой простенький пример ]

Источник

How to Fix Mobile Data Not Working on Android

Cellular data, mobile data, whatever you want to call it, is one of those things that only becomes a life necessity once you acquire your first smartphone. It’s only when you lose connectivity that you realize you don’t know how to get anywhere without Google Maps, don’t have anything to read without Flipboard, and don’t know how to communicate with people through any medium other than WhatsApp.

When mobile data stops working on Android, it’s world-shattering, in other words. Here are some tips on how to get it back.

Also read: How to Create Your Own Android Widget

Reset Your APNs

Access Point Names (APNs) are the means by which your mobile network provider connects your phone to the mobile Internet. It sets your phone up with all the crucial settings, like IP addresses and gateways, to (hopefully) get you connected. However, this process can sometimes go wrong and require a reset. The following shows how to do it.

Go to “Settings -> Network & internet -> Mobile network -> Advanced -> Access Point Names.”

You should see a list of APNs (potentially with only one network on them). Tap the menu icon at the top right, then “Reset to default.”

Set APN Protocol to iPv4/IPv6

This option doesn’t exist in the APN settings of all phones, but some devices (like the OnePlus 3) give you the option of leaving the APN Protocol field blank. If that’s the case in your network’s APN settings, make sure it says IPv4/IPv6 instead. Likewise, with other devices, make sure it says this rather than just one of the two.

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

Enter Your APN Settings Manually

It’s a sad but not uncommon occurrence for your APN settings to get out of whack after an Android software update, and if a standard reset doesn’t fix the problem, then you may need to enter your APN address manually.

1. Go to your APN list using the method in the previous tip, then tap the “+” icon in the top-right corner.

3. Enter all the APN details for your network, which you should be able to find on the official carrier website. Or you can check out this list of APN settings for US, UK, Indian and other national carriers.

4. Save your new APN settings, then select them from the APN list on your device.

Wipe Cache Partition from Recovery

On your phone, there’s a fair portion of your device’s memory dedicated to the cache – where data for various apps and processes is stored “on the backburner,” activating automatically so that these apps and processes boot up more quickly on your device.

But sometimes, as reported by certain Android users, errors can occur in the cache which can cause crucial processes – in this case your data connection – to stop working. To fix this, you need to clear the system cache partition, which is accessed from your phone’s recovery screen. Getting to your recovery varies slightly between phones, but on a standard stock Android device, do the following:

Switch off your phone, then when switching it back on, hold the Power and Volume Down buttons until the Android droid pops up on your screen.

Use the volume buttons to navigate to “Recovery Mode.” On the next screen, it may “No command.”

If you see this, you need to try holding different combinations of the volume buttons and the power button until you enter recovery (depending on your device).

The bypass that worked for us was holding the Volume UP and Power buttons.

Once you’re in recovery, use the volume buttons on your phone to select “wipe cache partition” or “wipe cache,” then select the option using the power button.

The process should only take a few seconds. Once it’s done, reboot your phone.

Reset Your Phone’s Network Connection

A simple and powerful fix for data not working on your Android device is to enter an SCRTN (Special Code to Reset the Network). Note that this fix will only work for phones using CDMA networks. In the U.S., these networks are T-Mobile, Verizon and US Cellular.

Assuming you’re with a CDMA network, go to your phone dial pad and enter the following code, depending on your device:

  • Google Pixel, Moto G7: *#*#72786#*#*
  • Nexus 5, Nexus 6, Moto G5: #*#*72786##
  • Other Android phones: ##72786#

Note that phone carriers are slowly trying to phase out CDMA networks, as they seek to move wholly onto the faster, more recent LTE standard, so this particular fix may not exist for much longer.

Читайте также:  Android 11 для samsung a41

Also read: How to Fix the Obtaining IP Address Error on Android

Enable the Right Network Mode

Starting with the simplest solution, it’s possible that during an update, or simply in the phone’s default settings, the network mode (3G, 4G, etc.) of your phone is set to one that doesn’t offer optimal coverage.

If you have a 4G phone, for example, you should always make sure 4G is selected in your network modes to catch those sweet 4G rays. Or if your phone isn’t 4G but you’re running on an OS that features it as a network mode (by rooting, for example), your phone may be trying to connect to 4G signals that it’s not capable of.

Changing this is simple. Go to “Settings -> Network & Internet -> Mobile network -> Preferred network type,” then switch to the one that best suits your phone. As my phone is a 4G, I go for 2G/3G/4G Auto so that it always tries to connect to the best signal available.

Also read: How to Fix Android Delayed Notifications Issue

Remove and Re-Insert Your SIM Card

Some will scoff at the very mention of suggestions like “reboot your phone” and “remove and reinsert your SIM card,” but these should always be the first port of call when trying to fix mobile data issues. Another option is to test your phone with another SIM card to see if the issue originates in the phone or the card.

There’s also an extra little trick to rebooting your phone that could help:

  • Before rebooting, turn on Airplane Mode.
  • Wait for 30 seconds, then turn Airplane Mode off.
  • If you still don’t have data, turn airplane mode back on, turn your phone off, wait for a minute, turn your phone back on, turn airplane mode off, wait for 30 seconds, then turn mobile data on.

If this fails, then try the following fixes.

Do You Have a Mobile Data Limit?

Every Android phone lets you set your own mobile data limits and warnings for when you’re about to reach your limit. These aren’t usually switched on by default, but maybe you set a limit previously, have since upgraded your tariff, and have forgotten to update your mobile data limit accordingly. To check this:

Go to “Settings -> Network & Internet -> Mobile network.”

Make sure “Mobile data” is switched on, then tap “Data warning & limit.”

Here you need to make sure that “Set data limit” is switched off, or at least that it isn’t any lower than the limit provided by your network.

There it is: the key to getting you back online just when you thought you’d have to start resorting to paper maps and pigeon mail to communicate with people.

Also read: How to Eliminate the “Unfortunately, App Has Stopped” Messages

Now that you have mobile data working again, why not put it to the test with one of these Internet speed test apps. Alternatively, check out our list of the best Firefox for Android add-ons.

Never Miss Out

Receive updates of our latest tutorials.

Content Manager at Make Tech Easier. Enjoys Android, Windows, and tinkering with retro console emulation to breaking point.

Источник

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