Mobile App Development is the process of building an application for mobile devices, such as smartphones and tablets. Generally, mobile apps are harder to develop than web apps, because they must be designed from scratch for each platform, while web development shares common codes across different devices.
Each operating system has its own language used for coding a native app (one created with technology dedicated to a specific platform). For instance, Android uses Java, while iOS uses Swift. Usually, it’s better to use the dedicated tech for apps that require high performance, like gaming or heavy animations. On the contrary, hybrid apps use cross-platform languages (i.e. Python) that can be run on multiple operating systems.
Mobile App Development is highly relevant for AI as it enables the integration of new technologies into people daily life. LLMs are so popular now because they have been deployed into user-friendly apps on your phone, easily accessible anytime and anywhere.
Through this tutorial, I will explain how to build a cross-platform mobile app with Python, using my Memorizer App as an example (link to full code at the end of the article).
Setup
I’m going to use the Kivy framework, which is the most used for mobile development in the Python community. Kivy is an open-source package for mobile apps, while KivyMD is the library that leverages Google’s Material Design and makes the usage of this framework much easier (similar to Bootstrap for web dev).
## for development
pip install kivy==2.0.0
pip install kivymd==0.104.2
## for deployment
pip install Cython==0.29.27
pip install kivy-ios==1.2.1
The first thing to do is to create 2 files:
- main.py (the name must be this) which shall contain the Python code of the app, basically the back-end
- components.kv (you can call it differently) which shall contain all the Kivy code used for the app layout, you can see it as the front-end
Then, in the main.py file we import the package to initialize an empty app:
from kivymd.app import MDApp
class App(MDApp):
def build(self):
self.theme_cls.theme_style = "Light"
return 0
if __name__ == "__main__":
App().run()
Before we start, I shall briefly describe the application I’m building. It’s a simple app that helps to memorize stuff: the user inserts pair of words (i.e. something in English and the equivalent in another language, or a date and the historical event linked to that). Then, the user can play the game by trying to remember shuffled information. As a matter of fact, I’m using it to memorize Chinese vocabulary.
As you can see from the image, I’m going to include:
- an intro screen to display the logo
- a home screen that can redirect to the other screens
- a screen to save words
- a screen to view and delete stored information
- a screen to play the game.
So, we can write them all down in the components.kv file:
In order to include Kivy file in the app, we need to load it from the main.py with the builder class, while the screen class links the screens between the two files.
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen
class App(MDApp):
def build(self):
self.theme_cls.theme_style = "Light"
return Builder.load_file("components.kv")
class IntroScreen(Screen):
pass
class HomeScreen(Screen):
pass
class PlayScreen(Screen):
pass
class SaveScreen(Screen):
pass
class EditScreen(Screen):
pass
if __name__ == "__main__":
App().run()
Please note that even if the app itself is basic, there is a pretty tricky feature: db management via mobile. That’s why we are going to use also the native Python package for databases:
import sqlite3
Development — basics
We’re gonna warm up with the Intro Screen: it simply contains an image logo, some text labels, and a button to move to another screen.
I consider that easy because it doesn’t require any Python code, it can be handled by the components.kv file. The change of screen triggered by the button must be linked to the root like this:
The same goes for the Home Screen: since it’s just a redirect, it can be all managed with Kivy code. You just have to specify that the screen must have 1 icon and 3 buttons.
You may have noticed that on top of the screen there is a “home” icon. Please note that there is a difference between a simple icon and an icon button: the latter is pushable. On this screen it’s just a simple icon, but on the other screens it will be an icon button used to bring you back to the Home Screen from any other screen of the app.
When we use an icon, we have to provide the tag (i.e. “home” displays a little house). I find this code very useful, just run it and it’ll show all the available icons.
Development — advanced
Let’s step up our game and deal with the DB through the Save Screen. It must allow the user to save different words for different categories (i.e. to study multiple languages). That implies:
- choosing an existing category (i.e. Chinese), so querying the existing ones
- creating a new category (i.e. French)
- two text inputs (i.e. a word and its translation)
- a button to save the form, so writing a new row in the DB.
When you run the app for the first time, the DB must be created. We can do that in the main function of the app. For convenience, I’m going to add also another function that queries the DB with any SQL you pass on.
class App(MDApp):
def query_db(self, q, data=False):
conn = sqlite3.connect("db.db")
db = conn.cursor()
db.execute(q)
if data is True:
lst_tuples_rows = db.fetchall()
conn.commit()
conn.close()
return lst_tuples_rows if data is True else None
def build(self):
self.theme_cls.theme_style = "Light"
q = "CREATE TABLE if not exists SAVED (category text, left
text, right text, unique (category,left,right))"
self.query_db(q)
return Builder.load_file("components.kv")
The tricky part is the DB icon that, when pushed, shows all the existing categories and allows the selection of one. In the components.kv file, under the Save Screen (named “save”), we add an icon button (named “category_dropdown_save”) that, if pressed, launches the Python dropdown_save() function from the main app.
That function is defined in the main.py file and returns a dropdown menu such that, when an item is pressed it gets assigned to a variable named “category”.
That last line of code links the category variable with the label that appears in the front-end. The screen manager calls the screen with get_screen() and identifies the item by id:
When the user enters the Save Screen, the category variable should be null until one is selected. We can specify the properties of the screen when one enters and when one leaves. So I’m going to add a function in the screen class that empties the App variable.
class SaveScreen(Screen):
def on_enter(self):
App.category = ''
Once the category is chosen, the user can insert the other text inputs, which are required to save the form (by pushing the button).
In order to make sure that the function doesn’t save if one of the inputs is empty, I’ll use a dialog box.
from kivymd.uix.dialog import MDDialog
class App(MDApp):
dialog = None
def alert_dialog(self, txt):
if not self.dialog:
self.dialog = MDDialog(text=txt)
self.dialog.open()
self.dialog = None
def save(self):
self.category = self.root.get_screen('save').ids.category.text
if self.category == '' else self.category
left = self.root.get_screen('save').ids.left_input.text
right = self.root.get_screen('save').ids.right_input.text
if "" in [self.category.strip(), left.strip(), right.strip()]:
self.alert_dialog("Fields are required")
else:
q = f"INSERT INTO SAVED VALUES('{self.category}',
'{left}','{right}')"
self.query_db(q)
self.alert_dialog("Saved")
self.root.get_screen('save').ids.left_input.text = ''
self.root.get_screen('save').ids.right_input.text = ''
self.category = ''
After reading so far, I’m confident that you’re able to go through the full code and understand what’s going on. The logic of the other screens is pretty similar.
Test
You can test the app on the iOS simulator on MacBook, that replicates an iPhone environment without needing a physical iOS device.
Xcode needs to be installed. Start by opening the terminal and running the following commands (the last one will take about 30 minutes):
brew install autoconf automake libtool pkg-config
brew link libtool
toolchain build kivy
Now decide your app name and use it to create the repository, then open the .xcodeproj file:
toolchain create yourappname ~/some/path/directory
open yourappname-ios/yourappname.xcodeproj
Finally, if you are working with iOS and you want to test an app on your phone and then publish it on the App Store, Apple requires you to pay for a developer account.
Conclusion
This article has been a tutorial to demonstrate how to design and build a cross-platform mobile app with Python. I used Kivy to design the user interface and I showed how to make it available for iOS devices. Now you can make your own mobile apps with Python and Kivy.
Full code for this article: GitHub
I hope you enjoyed it! Feel free to contact me for questions and feedback or just to share your interesting projects.
👉 Let’s Connect 👈
(All images, unless otherwise noted, are by the author)
Source link
#Mobile #App #Development #withPython #Data #Science