Set up Amplify DataStore
DataStore with Amplify
Amplify DataStore provides a programming model for leveraging shared and distributed data without writing additional code for offline and online scenarios, which makes working with distributed, cross-user data just as simple as working with local-only data.
Goal
To setup and configure your application with Amplify DataStore and use it to persist data locally on a device.
Prerequisites
- An Android application targeting Android API level 24 (Android 7.0) or above
- For a full example of creating Android project, please follow the project setup walkthrough
Install Amplify Libraries
Add the following dependencies to your build.gradle (Module :app) file and click "Sync Now" when asked:
1dependencies {2 implementation 'com.amplifyframework:aws-datastore:ANDROID_VERSION'3
4 // Support for Java 8 features5 coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'6}
At the top of the same file, add compileOptions
to support the Java 8 features used by Amplify:
1android {2 compileOptions {3 // Support for Java 8 features4 coreLibraryDesugaringEnabled true5 sourceCompatibility JavaVersion.VERSION_1_86 targetCompatibility JavaVersion.VERSION_1_87 }8}
Setup local development environment
To use Amplify, you must first initialize it for use in your project. If you haven't already done so, run this command:
1amplify init
The base structure for a DataStore app is created by adding a new GraphQL API to your app.
1# For new APIs2amplify add api3
4# For existing APIs5amplify update api
The CLI will prompt you to configure your API. Select GraphQL as the API type and reply to the questions as shown below. Conflict detection is required when using DataStore to sync data with the cloud.
1? Please select from one of the below mentioned services:2 `GraphQL`3? Here is the GraphQL API that we will create. Select a setting to edit or continue:4 `Name`5? Provide API name:6 `BlogAppApi`7? Here is the GraphQL API that we will create. Select a setting to edit or continue:8 `Authorization modes: API key (default, expiration time: 7 days from now)`9? Choose the default authorization type for the API10 `API key`11? Enter a description for the API key:12 `BlogAPIKey`13? After how many days from now the API key should expire (1-365):14 `365`15? Configure additional auth types?16 `No`17? Here is the GraphQL API that we will create. Select a setting to edit or continue:18 `Conflict detection (required for DataStore): Disabled`19? Enable conflict detection?20 `Yes`21? Select the default resolution strategy22 `Auto Merge`23? Here is the GraphQL API that we will create. Select a setting to edit or continue:24 `Continue`25? Choose a schema template26 `Single object with fields (e.g., “Todo” with ID, name, description)`
Idiomatic persistence
DataStore relies on platform standard data structures to represent the data schema in an idiomatic way. The persistence language is composed by data types that satisfies the Model
interface and operations defined by common verbs such as save
, query
and delete
.
Data schema
The first step to create an app backed by a persistent datastore is to define a schema. DataStore uses GraphQL schema files as the definition of the application data model. The schema contains data types and relationships that represent the app's functionality.
Sample schema
For the next steps, let's start with a schema for a small blog application. Currently, it has only a single model. New types and constructs will be added to this base schema as more concepts are presented.
Open the schema.graphql
file located by default at amplify/backend/{api_name}/
and define a model Post
as follows.
1type Post @model {2 id: ID!3 title: String!4 status: PostStatus!5 rating: Int6 content: String7}8
9enum PostStatus {10 ACTIVE11 INACTIVE12}
Now you will to convert the platform-agnostic schema.graphql
into platform-specific data structures. DataStore relies on code generation to guarantee schemas are correctly converted to platform code.
Like the initial setup, models can be generated either using the IDE integration or Amplify CLI directly.
Code generation: Platform integration
Code generation via the amplify-tools-gradle-plugin
Gradle plugin is deprecated, so please use the Amplify CLI instead.
Code generation: Amplify CLI
Models can also be generated using the Amplify CLI directly.
In your terminal, make sure you are in your project/root folder and execute the codegen command:
1amplify codegen models
You can find the generated files at app/src/main/java/com/amplifyframework/datastore/generated/model
.
Initialize Amplify DataStore
To initialize the Amplify DataStore, use the Amplify.addPlugin()
method to add the AWS DataStore Plugin. Next, finish configuring Amplify by calling Amplify.configure()
.
Add the following code to your onCreate()
method in your application class:
1import android.util.Log;2import com.amplifyframework.AmplifyException;3import com.amplifyframework.core.Amplify;4import com.amplifyframework.datastore.AWSDataStorePlugin;
1Amplify.addPlugin(new AWSDataStorePlugin());
Your class will look like this:
1public class MyAmplifyApp extends Application {2 @Override3 public void onCreate() {4 super.onCreate();5
6 try {7 Amplify.addPlugin(new AWSDataStorePlugin());8 Amplify.configure(getApplicationContext());9
10 Log.i("MyAmplifyApp", "Initialized Amplify");11 } catch (AmplifyException error) {12 Log.e("MyAmplifyApp", "Could not initialize Amplify", error);13 }14 }15}
Upon building and running this application you should see the following in your console window:
1Initialized Amplify
Persistence operations
Now the application is ready to execute persistence operations. The data will be persisted to a local database, enabling offline-first use cases by default.
Even though a GraphQL API is already added to your project, the cloud synchronization will only be enabled when the API plugin is initialized and the backend provisioned. See the Next steps for more info.
Writing to the database
To write to the database, create an instance of the Post
model and save it.
1import android.util.Log;2import com.amplifyframework.core.Amplify;3import com.amplifyframework.datastore.generated.model.Post;
1Post post = Post.builder()2 .title("Create an Amplify DataStore app")3 .status(PostStatus.ACTIVE)4 .build();5
6Amplify.DataStore.save(post,7 result -> Log.i("MyAmplifyApp", "Created a new post successfully"),8 error -> Log.e("MyAmplifyApp", "Error creating post", error)9);
Reading from the database
To read from the database, the simplest approach is to query for all records of a given model type.
1Amplify.DataStore.query(Post.class,2 queryMatches -> {3 if (queryMatches.hasNext()) {4 Log.i("MyAmplifyApp", "Successful query, found posts.");5 } else {6 Log.i("MyAmplifyApp", "Successful query, but no posts.");7 }8 },9 error -> Log.e("MyAmplifyApp", "Error retrieving posts", error)10);
Next steps
Congratulations! You’ve created and retrieved data from the local database. Check out the following links to see other Amplify DataStore use cases and advanced concepts: