Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to Build a SOS Mobile Application in Android Studio?
Next article icon

How to Build a TODO Android Application with AWS DynamoDB as Database?

Last Updated : 20 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

This is a TODO application made on android studio IDE, code is written in JAVA, and data store in AWS DynamoDB and fetch to the home screen. The connection established between the application and AWS through Amplify CLI and the data is successful gets stored by creating a TODO Table in DynamoDB, a Schema is also created which shows the structure of data. The data fetched successfully and displayed on the home page of the application. The aim of this project is to show how to connect your android applications with AWS and use the AWS resources(DynamoDB). A sample video is given below to get an idea about what we are going to do in this article.

https://media.geeksforgeeks.org/wp-content/uploads/20210116081234/WhatsApp-Video-2021-01-15-at-11.55.29-PM.mp4

Before jumping to the implementation have a look at the following terms.

  • Amplify CLI: Amplify Command Line Interface (CLI)  is a combined toolchain to create, integrate, and manage the AWS cloud services/resources for your application. 
  • DynamoDB: It is a fast and flexible NoSQL database. It is a fully managed database that helps you with both document and key-value data models.

Prerequisite: Install Node.js (version 10.x) install NPM (version 6.x), create an AWS account if you don’t have one, install android studio (version 4.0 or higher), android SDK API level 29(android 10), install amplify CLI (write following on the command prompt).

npm install -g @aws-amplify/cli

Step by Step Implementation

1. Configuring Amplify CLI

Step 1: Write the following on the command prompt

amplify configure

Install Amplify

Step 2: If you have already created an IAM user then write “Do you want to use an AWS profile? Yes” and then write below its accessKeyId and secretAccessKey otherwise write “Do you want to use an AWS profile? No” create an IAM user and use its accessKeyId and secretAccessKey.

Configure Amplify

Give permissions

User created

Step 3: Write the following in order to initialize the new Amplify project

amplify init

Initialize Amplify

Step 4: Create backend API by using GraphQL query language then use “amplify publish” to deploy it

amplify add api

amplify push

amplify publish

Add API to your backend

2. Integrate AWS to the android studio with the help of  amplify

Step 1: Add the following in the dependencies of build.gradle (Project: Todo) in Gradle Scripts

buildscript {    repositories {        google()        jcenter()    }     dependencies {        classpath 'com.android.tools.build:gradle:4.1.1'         // Add this line into `dependencies` in `buildscript`        classpath 'com.amplifyframework:amplify-tools-gradle-plugin:1.0.2'    } }  allprojects {    repositories {        google()        jcenter()    } }  // Add this line at the end of the file apply plugin: 'com.amplifyframework.amplifytools'

Step 2: Add the following in the dependencies of build.gradle (Module: app) in Gradle Scripts. Run Gradle Sync

dependencies {     implementation 'com.amplifyframework:aws-api:1.6.9'     implementation 'com.amplifyframework:aws-datastore:1.6.9' }

Step 3: In android studio go to Project -> amplify -> app -> backend -> api -> schema.graphql

type Todo @model {   id: ID!   name: String!   description: String }

Step 4: Add the following code in MainActivity & MainActivity2 in the onCreate() method to initialize Amplify

 try {      Amplify.addPlugin(new AWSDataStorePlugin());      Amplify.configure(getApplicationContext());       Log.i("Tutorial", "Initialized Amplify");  } catch (AmplifyException e) {      Log.e("Tutorial", "Could not initialize Amplify", e);  }

Step 5:  Add the following code in MainActivity2 in the onCreate() method to creates a Todo item with two properties: a name and a description

 Todo todo = Todo.builder()                         .name(name1)                         .description(name2)                         .build();

Step 6: Add the following code in MainActivity2 in the onCreate() method to save items using mutate

 Amplify.API.mutate(                      ModelMutation.create(todo),                      response -> Log.i("MyAmplifyApp", "Added Todo with id: " + response.getData().getId()),                      error -> Log.e("MyAmplifyApp", "Create failed", error)                 );

Go to your AWS management console -> AppSync -> Select your API -> Data Sources -> select todo table -> items

Data successfully stored

Step 7:  Add the following code in MainActivity in the onCreate() method to fetch data/run queries to retrieve the stored data

 Amplify.API.query(                 ModelQuery.list(Todo.class),                 response -> {                     for (Todo todo : response.getData()) {                         ls.add(todo.getName());                         Log.i("MyAmplifyApp", todo.getName());                     }                 },                 error -> Log.e("MyAmplifyApp", "Query failure", error)         );

Below are the complete codes for:

MainActivity file(Home page of App)

XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <ListView
        android:id="@+id/lt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">
    </ListView>
   
    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="221dp"
        android:layout_height="53dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_marginEnd="25dp"
        android:layout_marginRight="25dp"
        android:layout_marginBottom="70dp"
        android:clickable="true"
        app:srcCompat="@android:drawable/ic_input_add" />
   
</RelativeLayout>
                      
                       

Java

package com.example.shreyaawsapp;
 
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.amplifyframework.AmplifyException;
import com.amplifyframework.api.aws.AWSApiPlugin;
import com.amplifyframework.api.graphql.model.ModelQuery;
import com.amplifyframework.core.Amplify;
import com.amplifyframework.datastore.generated.model.Todo;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.List;
 
public class MainActivity extends AppCompatActivity {
     
      // declaration
    public FloatingActionButton btn;
    public ListView lv;
    public String[] st;
    int i = 0;
    Handler handler;
     
      // the array adapter converts an ArrayList of objects
    // into View items filled into the ListView container
    ArrayAdapter<String> arrayAdapter;
     
      // list to store data
    public static List<String> ls;
 
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         
          // provide id to the layout items
        btn = findViewById(R.id.fab);
        st = new String[100];
 
        lv = findViewById(R.id.lt);
         
          // set listener to the floating button which takes
        // you to the next activity where you add and sore
        // your data
        btn.setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v)
            {
                Intent intent = new Intent(MainActivity.this, MainActivity2.class);
                startActivity(intent);
            }
        });
        ls = new ArrayList<String>();
        
          // add the code below to initialize Amplpify
        try {
            // Add these lines to add the AWSApiPlugin plugins
            Amplify.addPlugin(new AWSApiPlugin());
            Amplify.configure(getApplicationContext());
            Log.i("MyAmplifyApp", "Initialized Amplify");
        }
        catch (AmplifyException error) {
            Log.e("MyAmplifyApp", "Could not initialize Amplify", error);
        }
        
          // add the code below to fetch
          // data/run queries to
        // retrieve the stored data
        Amplify.API.query(ModelQuery.list(Todo.class), response -> {
                for (Todo todo : response.getData()) {
                    ls.add(todo.getName());
                    Log.i("MyAmplifyApp", todo.getName());
                }
            },
            error -> Log.e("MyAmplifyApp", "Query failure", error));
       
        handler = new Handler();
        final Runnable r = new Runnable() {
            public void run()
            {
                handler.postDelayed(this, 2000);
                arrayAdapter = new ArrayAdapter<String>(
                    getApplicationContext(),
                    android.R.layout.simple_list_item_1,
                    ls);
                lv.setAdapter(arrayAdapter);
                arrayAdapter.notifyDataSetChanged();
            }
        };
        handler.postDelayed(r, 1000);
    }
}
                      
                       

MainActivity2 file(Write notes page)

XML

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity2">
 
    <EditText
        android:id="@+id/edname"
        android:layout_width="347dp"
        android:layout_height="54dp"
        android:layout_marginTop="110dp"
        android:ems="10"
        android:hint="Title"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
    <EditText
        android:id="@+id/eddes"
        android:layout_width="347dp"
        android:layout_height="54dp"
        android:layout_marginTop="216dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:hint="Description"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
    <Button
        android:id="@+id/button2"
        android:layout_width="134dp"
        android:layout_height="53dp"
        android:layout_marginStart="138dp"
        android:layout_marginTop="69dp"
        android:layout_marginEnd="138dp"
        android:text="Store in data"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/eddes" />
 
</androidx.constraintlayout.widget.ConstraintLayout>
                      
                       

Java

package com.example.shreyaawsapp;
 
import android.content.Intent;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.amplifyframework.AmplifyException;
import com.amplifyframework.api.aws.AWSApiPlugin;
import com.amplifyframework.api.graphql.model.ModelMutation;
import com.amplifyframework.api.graphql.model.ModelQuery;
import com.amplifyframework.core.Amplify;
import com.amplifyframework.datastore.generated.model.Todo;
import java.util.ArrayList;
import java.util.List;
 
public class MainActivity2 extends AppCompatActivity {
   
    // declaration
    public EditText name, desc;
    public Button btn;
 
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        // give id to the items
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        name = findViewById(R.id.edname);
        desc = findViewById(R.id.eddes);
        btn = findViewById(R.id.button2);
       
        // add the code below to initialize Amplify
        try {
            // Add these lines to add the AWSApiPlugin plugins
            Amplify.addPlugin(new AWSApiPlugin());
            Amplify.configure(getApplicationContext());
            Log.i("MyAmplifyApp", "Initialized Amplify");
        }
        catch (AmplifyException error) {
            Log.e("MyAmplifyApp", "Could not initialize Amplify", error);
        }
        // set listener on the store data button to store
        // data in dynamoDB
        btn.setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v)
            {
                String name1 = name.getText().toString();
                String name2 = desc.getText().toString();
                // add the code below to create a todo item
                // with two properties a name and a
                // description
                Todo todo = Todo.builder()
                                .name(name1)
                                .description(name2)
                                .build();
                // add the code below  to save item using mutate
                Amplify.API.mutate(ModelMutation.create(todo), response -> Log.i(
                        "MyAmplifyApp", "Added Todo with id: " + response.getData().getId()),
                    error
                    -> Log.e("MyAmplifyApp", "Create failed", error));
            }
        });
    }
    // move to the next activity
    @Override public void onBackPressed()
    {
        super.onBackPressed();
        startActivity(new Intent(MainActivity2.this, MainActivity.class));
    }
}
                      
                       

Output: 

https://media.geeksforgeeks.org/wp-content/uploads/20210116081234/WhatsApp-Video-2021-01-15-at-11.55.29-PM.mp4

Source Code: https://github.com/shreya593/Shreyaawsapp.git



Next Article
How to Build a SOS Mobile Application in Android Studio?

S

shreyajaiswal3
Improve
Article Tags :
  • Android
  • Java
  • Technical Scripter
  • Android Projects
  • Technical Scripter 2020
Practice Tags :
  • Java

Similar Reads

  • How to Build Android Applications with Gradle?
    There are several contemporary build automation technologies available nowadays that may be utilized to create a quicker build when creating a project. Gradle is one of these modern-day automation technologies. Gradle is now used by Android to automate and control the build process while also defini
    8 min read
  • How to Build a SOS Mobile Application in Android Studio?
    The SOS applications are basically advanced emergency apps that can rescue you and/or your loved ones if you and/or they find themselves in a life-threatening emergency situation and need immediate assistance. When you need some personal assistance, you can actually turn on your phone and can call o
    15+ min read
  • How to Build a Grocery Android App using MVVM and Room Database?
    In this article, we are going to build a grocery application in android using android studio. Many times we forget to purchase things that we want to buy, after all, we can’t remember all the items, so with the help of this app, you can note down your grocery items that you are going to purchase, by
    13 min read
  • How to Build a Simple Android App with Flask Backend?
    Flask is an API of Python that allows us to build up web applications. It was developed by Armin Ronacher. Flask’s framework is more explicit than Django’s framework and is also easier to learn because it has less base code to implement a simple web-Application. A Web-Application Framework or Web Fr
    8 min read
  • How to Create a Dynamic Audio Player in Android with Firebase Realtime Database?
    Many online music player apps require so many songs, audio files inside their apps. So to handle so many files we have to either use any type of database and manage all these files. Storing files inside your application will not be a better approach. So in this article, we will take a look at implem
    7 min read
  • How to Add Data to Back4App Database in Android?
    Prerequisite: How to Connect Android App with Back4App? Back4App is an online database providing platform that provides us services with which we can manage the data of our app inside the database. This is a series of 4 articles in which we are going to perform the basic CRUD (Create, Read, Update,
    4 min read
  • How to Build a Simple Note Android App using MVVM and Room Database?
    Android provides us a feature with which we can store users' data inside their mobile itself with different storage options such as Shared Preferences, SQLite database, and the Room Database. All the data storing techniques are having different use cases. In this article, we will specifically take a
    15+ min read
  • Testing an Android Application with Example
    Testing is an essential part of the Android app development process. It helps to ensure that the app works as expected, is bug-free, and provides a seamless user experience. Android offers various testing tools and frameworks that can be used to write and execute different types of tests, including
    5 min read
  • How to Create and Add Data to SQLite Database in Android?
    SQLite is another data storage available in Android where we can store data in the user's device and can use it any time when required. In this article, we will take a look at creating an SQLite database in the Android app and adding data to that database in the Android app. This is a series of 4 ar
    8 min read
  • How to Build a Weather App in Android?
    In this project, we will be building a weather application. This application will show the temperature of a location. To fetch weather information we will need an API. An API(Application Programming Interface) is a function that allows applications to interact and share data using various components
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences