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

04 Feb, 2021
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.
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 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
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)
        );
MainActivity file(Home page of App)
XML
Java
<?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>
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
Java
<?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>
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 toto 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));    }}
Source Code: https://github.com/shreya593/Shreyaawsapp.git
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.