This article describes how to open default Android Gallery in Qt using a mixture of Android’ Java and Qt (C++) code. It is specially useful if you are working with images, for example if you want to open a Mat Image in OpenCV using imread function or if you are just writing some kind of image viewer program. Unfortunately Qt does not offer this (yet) by default so I thought I could share it with you.
I have made a few assumptions such as:
- You have successfully installed Qt (with Android) on your Computer
- You have an Android phone or an Emulator (Genymotion and so on) to run Qt Android projects on it.
What it does?
This example project allows you to open an image from Android Gallery and displays it on a QLabel widget. Following screenshot shows Qt Project called QtAndroidGallery that I have shared at the bottom of this post.
Note: This project (source code) can also be used as a working example of my previous post titled how to mix Android and Qt (C++) code.
How its done?
The idea simply consists of Qt (C++) and Android (Java) code interacting with each other through JNI (Java Native Interface)
Explained in detail:
Below I will explain parts and pieces of the source code that might seem confusing but if you have any questions or facing any issues regarding build or running of this project please start a discussion by commenting down below.
This function allows retrieving of selected file name (from Gallery) after the selection is completed. Note that it is essential to use the exact same pattern seen below in function names for JNI access. Your Domain name, Package name, Java Class and function name all must be separated with “_” as seen here.
JNIEXPORT void JNICALL
selectedFileName = QAndroidJniObject(results).toString();
This part of the code is used to call an static function in the Java code. “openAnImage” is the name of Java function that takes no parameters and returns the selected file name.
I will not go into the details of Java code but something that I have seen all over the internet that people have a hard time understanding is how to call a non static function from inside a static function. Simple! 🙂 First create an instance of the same class inside itself, like this (this already exists in the example code)
private static QtAndroidGallery m_instance;public QtAndroidGallery()
m_instance = this;
And then, inside that static function, call the non-static function using the instance of the class you created!
static void openAnImage()
I won’t go into details of “dispatchOpenGallery” function cause that is pure Android code and you can easily use Android SDK Documentation to get more information on that.
You can download the example project source code from here. It contains all required files for running the project provided that you already have a correct Qt for Android installation.