📜  如何使用AWS DynamoDB作为数据库构建TODO Android应用程序?

📅  最后修改于: 2021-05-13 15:36:54             🧑  作者: Mango

这是在Android Studio IDE上创建的TODO应用程序,代码是用Java编写的,数据存储在AWS DynamoDB中,并提取到主屏幕。通过Amplify CLI在应用程序和AWS之间建立的连接,并通过在DynamoDB中创建TODO表成功存储了数据,还创建了一个显示数据结构的架构。数据已成功获取并显示在应用程序的主页上。该项目的目的是展示如何将您的android应用程序与AWS连接以及如何使用AWS资源(DynamoDB)。下面提供了一个示例视频,以使您对我们在本文中将要做的事情有个大概的了解

在转到实施之前,请先查看以下术语。

  • Amplify CLI :Amplify Command Line Interface(CLI)是一个组合工具链,可为您的应用程序创建,集成和管理AWS云服务/资源。
  • DynamoDB :这是一个快速,灵活的NoSQL数据库。它是一个完全托管的数据库,可帮助您使用文档和键值数据模型。

先决条件:安装Node.js(版本10.x),安装NPM(版本6.x),如果没有账户则创建一个AWS账户,安装android studio(4.0或更高版本),android SDK API级别29(android 10),安装amplify CLI(在命令提示符下输入以下内容)。

分步实施

1.配置放大CLI

步骤1:在命令提示符下编写以下内容

安装放大

步骤2:如果您已经创建了IAM用户,请输入“您是否要使用AWS配置文件?是” ,然后在其accessKeyIdsecretAccessKey下方写上,否则写“您是否要使用AWS配置文件?否”创建一个IAM用户并使用其accessKeyIdsecretAccessKey

配置放大

授予权限

用户创建

步骤3:编写以下内容以初始化新的Amplify项目

初始化放大

步骤4:使用GraphQL查询语言创建后端API,然后使用“放大发布”进行部署

将API添加到您的后端

2.在放大的帮助下将AWS集成到android studio

步骤1:在Gradle脚本的build.gradle(项目:Todo)的依赖项中添加以下内容

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'

步骤2:在Gradle脚本的build.gradle(模块:app)的依赖项中添加以下内容。运行Gradle同步

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

步骤3:在android studio中转到项目->放大->应用程序->后端-> api-> schema.graphql

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

步骤4:在MainActivity和MainActivity2的onCreate()方法中添加以下代码以初始化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);
 }

步骤5:在MainActivity2的onCreate()方法中添加以下代码,以创建具有两个属性的Todo项:名称和描述

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

步骤6:在MainActivity2的onCreate()方法中添加以下代码,以使用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)
                );

转到您的AWS管理控制台-> AppSync- >选择您的API- >数据源->选择待办事项表->项目

数据成功存储

步骤7:在MainActivity的onCreate()方法中添加以下代码,以获取数据/运行查询以检索存储的数据

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文件(App主页)

XML


  
    
    
    
    
    


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 arrayAdapter;
      
      // list to store data
    public static List 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();
         
          // 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(
                    getApplicationContext(),
                    android.R.layout.simple_list_item_1,
                    ls);
                lv.setAdapter(arrayAdapter);
                arrayAdapter.notifyDataSetChanged();
            }
        };
        handler.postDelayed(r, 1000);
    }
}


XML


  
    
  
    
  
    


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 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));
    }
}


MainActivity2文件(写注释页面)

XML格式



  
    
  
    
  
    

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 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));
    }
}

输出:

源代码: https : //github.com/shreya593/Shreyaawsapp.git

想要一个节奏更快,更具竞争性的环境来学习Android的基础知识吗?
单击此处,前往由我们的专家精心策划的指南,以使您立即做好行业准备!