[JAVA] Let's quickly create an app that uses Firestore! !!

Motivation for creating the application

I decided to make a smartphone application in a short period of time. I was interested in Firestore, so I wanted to use it. I wanted to make something that was monotonous but might be useful. I thought about making output and making it my own knowledge.

Overview of the created app

You can register cooking recipes. Everyone who owns the app can see the recipes of the dishes registered so far.

Introducing Firebase

Firebase Console Create a project here and follow the instructions to install it.

In the project

  1. Place google_service.json directly under app

  2. Add the following code

app/build.gradle


dependencies {
    ...
    //Firebase
    implementation 'com.google.firebase:firebase-analytics:17.0.1'
    implementation 'com.google.firebase:firebase-firestore:20.1.0'
    ...
}
apply plugin: 'com.google.gms.google-services'

build.gradle


buildscript {
    repositories {
        google()
        jcenter()
        
    }
    dependencies {
        ...
        classpath 'com.google.gms:google-services:4.2.0'
    }
}

Setup is now complete.

Process of registering data in Firestore

RecipeInfo.java


    private String fireStoreCollectionPath = "recipes";
    private FirebaseFirestore fireStore = FirebaseFirestore.getInstance();

    private OnSuccessListener successListener = new OnSuccessListener<DocumentReference>() {
        @Override
        public void onSuccess(DocumentReference documentReference) {
            Log.d("success", "Registration was successful");
        }
    };
    private OnFailureListener onFailureListener = new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.d("fail", "Signup failed");
        }
    };

    /**
    *The process of registering a recipe in the Firestore
    * @param map Recipe information registered in Firestore
    */
    public void recipeAdd(Map map) {
        //Firestore collection generation.
        fireStore.collection(fireStoreCollectionPath)
                .add(map)
                .addOnSuccessListener(successListener)
                .addOnFailureListener(onFailureListener);
    }

RecipeAddActivity.java


    private Map<String, String> recipe = new HashMap<>();
    private EditText getRecipeTitle;
    private EditText getCooking;
    private EditText getIngredients;
    private String recipeTitle;
    private String cooking;
    private String ingredients;
    public Button addButton;
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recipe_add);

        recipeInfo = new RecipeInfo();
        getRecipeTitle = findViewById(R.id.recipe_title);
        getIngredients = findViewById(R.id.ingredients);
        getCooking = findViewById(R.id.cooking);
        addButton = findViewById(R.id.add_recipe);
        addButton.setOnClickListener(this);
    }

    /**
     *Recipe registration
     * */
    @Override
    public void onClick(View v) {
        try {
            //Store the character entered by EditText in the character string
            recipeTitle = getRecipeTitle.getText().toString();
            ingredients = getIngredients.getText().toString();
            cooking = getCooking.getText().toString();
            
            //Add information to be registered in DB to map
            recipe.put("recipeTitle", recipeTitle);
            recipe.put("ingredients", ingredients);
            recipe.put("cooking", cooking);
            
            recipeInfo.recipeAdd(recipe);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

The above is the process in which the recipe entered when the button is pressed is registered in the Firestore.

Process to get a list of recipes

GetRecipeList.java


    private String fireStoreCollectionPath = "recipes";
    private FirebaseFirestore fireStore = FirebaseFirestore.getInstance();
    private RecipeCallback mRecipeCallback;
    private ArrayList<Map> recipes = new ArrayList<>();

     /**
     *Get list
     * */
    private OnCompleteListener onCompleteListener = new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                for (QueryDocumentSnapshot document : task.getResult()) {
                    recipes.add(document.getData());
                }
                mRecipeCallback.getRecipeMap(recipes);
            } else {
                mRecipeCallback.getRecipeMap(null);
            }
        }
    };

   /**
     *Recipe display
     * */
    void recipeList(RecipeCallback recipeCallback) {
        mRecipeCallback = recipeCallback;
        fireStore.collection(fireStoreCollectionPath)
                .get()
                .addOnCompleteListener(onCompleteListener);
    }

RecipeActivity.java


private Context mContext;
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recipe);

        mContext = getApplicationContext();
        mRecipeCallback = new RecipeCallback() {
            @Override
            //Callback to return Map
            public void getRecipeMap(ArrayList<Map> recipes) {
                RecyclerView rv = (RecyclerView) findViewById(R.id.recyclerView);
                rv.setLayoutManager(new LinearLayoutManager(mContext));
                if (recipes == null) {
                    Log.d("fail", "Read failure");
                    return;
                }
                final List<RecipeData> list = recipeListClass.createRecipeTitleList(recipes);
                
                //Reflect the list in RecyclerView creation
                RecyclerViewAdapter adapter = new RecyclerViewAdapter(list);
                LinearLayoutManager llm = new LinearLayoutManager(mContext);
                rv.setHasFixedSize(true);
                rv.setLayoutManager(llm);
                rv.setAdapter(adapter);
                progressBar.setVisibility(ProgressBar.INVISIBLE);
                //Item tap processing
                adapter.setOnItemClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //Transition to Activity where materials and how to make are displayed
                    }
                });
            }
        };

        //Recipe list call
        getRecipeList = new GetRecipeList();
        getRecipeList.recipeList();
    }

Now you can get the list of recipes. This time, I decided to focus on the Firestore, so regarding the Adepter and ViewHolder of RecyclerView. If I have a chance, I would like to give you a separate article on how to use it.

The screen of the created application

Additional screen add.jpg List screen list.jpg After list tap processing cooking.jpg

Impressions I made

Firestore was too convenient and easier to implement than expected. If anything, I struggled with my lack of design sense. Asynchronous processing is also done by the Firestore method used this time, so there is no need to do it from here.

Conclusion: Firebase is the best.

Recommended Posts

Let's quickly create an app that uses Firestore! !!
Create an Annotator that uses kuromoji with NLP4J [007]
Create an app that uses the weather API to determine if you need an umbrella.
Create an app with Spring Boot 2
Create an app with Spring Boot
Let's create an instance with .new yourself. .. ..
Create an iOS shortcut app and quickly open the key with NFC
Create an app by specifying the Rails version
Let's create JUnit.
Create a docker image that runs a simple Java app
How to create an environment that uses Docker (WSL2) and Vagrant (VirtualBox) together on Windows