How to build your first Android AI App: My Favorite Tutorial in The Series - Hive Programmers

avatar

Greetings to my favorite science community online, StemSocial.

It's @skyehi and I'm super excited to be back to continue my series on Android App Development Tutorials for beginners.

I consider today's tutorial as my one of my favorite and probably the best so far because we're going to be building an App related to the future of science and technology.

In today's world, Artificial Intelligence, AI is widely being used to improve services.

Polish_20231211_142558730.pngOriginal Image Source by Boskampi from Pixabay

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

AI is serving as an assistant to many through programs like Apple's Siri, Microsoft's Cortana, Amazon's Alexa and Google's Assistant to mention a few. We've also got AI programs like chat Gpt which also does a great job of assisting people with answers to questions or finding solutions to problems.

One thing that I can say for a fact is that as technology continues to advance, integrating AI into mobile applications will become increasingly prevalent.

Even big time social media platform companies like Meta and Titok employ the use of AI in creating their App algorithms to bring the right content to their users.

I could go on and on about the value of AI in our society but this is a tutorial about building an App so I'll end the discussion and start the App project tutorial.

In today's blog, I'll teach you how to build your very own Android AI App. We'll be using a very popular AI API library called TensorFlow Lite.

This is going to be lots of fun guys so let's get started.

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Prerequisites

Alright guys, before we get started with developing the AI Android App, there are a few softwares you need to get installed. This step is for the newcomers to my series who are just getting started with programming and you happened to find this particular post or series.

You would need to download Android Studio IDE. This is the platform on which we develop our Android Apps. The platform is owned and built by Google, the same company that builds each version of the Android Operating System.

I took the liberty of getting the Link to Android Studio's main download page.

Android Studio Download

The next thing you need to ensure that you have installed is the Java Development Kit, JDk. I cannot stress enough on how important it is to have JDK installed since we'll be building our AI Android App using Java language. Your computer cannot execute Java codes unless JDK is properly installed on your PC.

If you're having troubles downloading or installing both softwares on your computer, please let me know in the comments

Creating A new Android Studio Project

At this point, I'll assume you have successfully installed the necessary softwares. We'll start our work by opening Android Studio application and clicking on "Create a new Android project". You'll be sent to another page to choose an App name and package name.

I would love to call my test App, "StemSocial AI" because I love StemSocial. - Name your AI App however you want to guys.

Also please ensure that Java is the selected programming language for this project because that's the programming language we'll be coding in. As we make progress, we'll switch it up to Kotlin.

Now guys click the next button if you're satisfied with the name and you'll be sent to the Android project template page. As we usually do in this series, choose "Empty Activity" template to make it simple and easy to follow my tutorial.

When you're done, click the finish button and Android Studio will prepare your new Android App Project.

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Adding The TensorFlow Lite dependency

When your Android Studio project is ready, the first thing we would want to do is to add the AI dependency. This library will help us develop a working model of an AI App that operates on Machine Learning.

The library's dependency will be added to the app-level build.gradle file.

So guys open the gradle file and add the TensorFlow Lite dependency.

Here's how your dependency code should look like

implementation 'org.tensorflow:tensorflow-lite:2.5.0'

2dk2RRM2dZ8gKjXsrozapsD83FxL3Xbyyi5LFttAhrXxr16mCe4arfLHNDdHCBmaJroMz2VbLrf6Rxy9uPQm7Ts7EnXL4nPiXSE5vJWSfR53VcqDUrQD87CZSpt2RKZcmrYrze8KanjkfyS8XmMCcz4p33NZmfHE4S9oRo3wU2.png

Designing our User Interface

Of course guys, it's basic tutorial and that means it's certainly not time for some Chat GPT or Siri level Interface 😂. We'll be building a very simple and basic interface.

When building advanced apps, always aim at making a user-friendly interface for your users. That increases your chances of App success.

For our tutorial, we'll design a simple app with a button to trigger AI functionality.

The App interface design code will be written inside the res/layout/activity_main.xml file.

Here's how your design code should look like guys, just a simple button which shows the text "Run AI'. When the uses presses the button, the App AI functionality will be triggered.

<Button
    android:id="@+id/btnRunAI"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Run AI"
    android:onClick="runAI" />

Implementing the TensorFlow Lite for Image Classification

It's now time for the logic of our App. AI models need to be trained through programming and running tests before they can function as AI. A lot of code is required for this training.

Since this is a basic tutorial, I would not want to go too deep into the details of the AI training program. However what we can do is to implement a pre-trained (Already Trained) AI model from the TensorFlow Lite Model Zoo.

So we'll just implement image classification using a pre-trained TensorFlow Lite model.

I took the liberty of sharing the link to the pre-trained AI model below

TensorFlow Lite Model Zoo

Now guys after downloading the model file, the next thing to do is to place the file which may look something like this; model.tflite in the app/src/main/assets folder.

If you're having troubles locating the assets folder in Android Studio please let me know in the comments

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

After adding the trained AI model, we can now implement the AI functionality and this will be done inside the MainActivity.java file.

Here's how your code should look like guys

import android.content.res.AssetFileDescriptor;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.tensorflow.lite.Interpreter;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class MainActivity extends AppCompatActivity {

    private Interpreter tflite;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Load the TensorFlow Lite model
        try {
            tflite = new Interpreter(loadModelFile());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Load the TensorFlow Lite model from assets
    private MappedByteBuffer loadModelFile() throws IOException {
        AssetFileDescriptor fileDescriptor = getAssets().openFd("model.tflite");
        FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor());
        FileChannel fileChannel = inputStream.getChannel();
        long startOffset = fileDescriptor.getStartOffset();
        long declaredLength = fileDescriptor.getDeclaredLength();
        return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength);
    }

    // Example AI function for image classification
    public void runAI(View view) {
        // Mock image classification result
        String result = classifyImage(/* Provide image data here */);

        // Display result or perform further actions
        Toast.makeText(this, "AI Result: " + result, Toast.LENGTH_SHORT).show();
    }

    // Mock image classification function
    private String classifyImage(/* Add image data parameter if needed */) {
        // Process input and get AI predictions
        // Replace this with actual image classification code
        return "Cat"; // Placeholder result
    }
}

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Running your first AI App

Congratulations guys, you have been able to build your very first Basic AI Android App. We're now ready to run the app. As always, you can run your app on an emulator or a physical Android device.

When your App finally launch, click the "Run AI" button to trigger the image classification function.

Ensure the AI functionality works as expected. You should see a Toast message as proof that it works.

In future updates we'll be creating more advanced AI logic that is able to make Image generation with prompts. I didn't want to get ahead of myself because this is a tutorial for beginners so guys this is just the beginning.

You can improve your code for performance, and consider incorporating error handling and asynchronous tasks for resource-intensive operations.

Your App will definitely require Internet Permission to run so please do not forget to request permission inside AndroidManifest

Just incase you forgot how to do that from our previous tutorials, here's how the permission code should look like;

<uses-permission android:name="android.permission.INTERNET" />

2dk2RRM2dZ8gKjXsrozapsD83FxL3Xbyyi5LFttAhrXxr16mCe4arfLHNDdHCBmaJroMz2VbLrf6Rxy9uPQm7Ts7EnXL4nPiXSE5vJWSfR53VcqDUrQD87CZSpt2RKZcmrYrze8KanjkfyS8XmMCcz4p33NZmfHE4S9oRo3wU2.png

Thank you so much for taking the time to read today's blog guys. I hope you enjoyed this tutorial. We're really covering a lot of grounds with the series.

I'm very hopeful that at the end of the series, I would have been able to help lots of people improve their programing skills and become professional Android App developers.

Have a lovely day and catch you next time on StemSocial. Goodbye 👨‍💻


You Can Follow Me @skyehi For More Like This And Others



0
0
0.000
1 comments
avatar

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

Thanks for including @stemsocial as a beneficiary, which gives you stronger support. 
 

0
0
0.000