Join Chiu-Ki Chan for an in-depth discussion in this video RecipeActivity: Loading a recipe, part of Effective Android Testing for Mobile Developers.
- [Instructor] Now that we have added a click listener to the reciper adapter, we will need to add logic to recipe activity to open the actual recipe. Go RecipeActivity. First, we will need to find the views to display the title and the description. In the onCreate function, after you do setContentView, do TextView, and then titleView = (TextView), in a cast, meaning in parentheses.
findViewById, with the id R.id.title. Press Cmd+D to duplicate this line. Change the titleView to be descriptionView, and the id to be R.id.description. Next, we will need to retrieve the recipe from the store. First, we will create a store. RecipeStore store, _store_ = new RecipeStore, with a context, which is this, the activity, and the directory "recipes".
Next, we will retrieve from the store the id that got passed in. So what we need to get the id out of the intent first. String id = getIntent().getStringExtra, and we will need the key, which is what we have defined it in line 12. KEY_ID. Once again, it is good practice to use a constant to make sure that whatever key you use to put in this value will be exactly the same as the one we use to retrieve it.
Now that we have the store and the id, we can retrieve a recipe out of the store. Recipe, we call recipe = _store.getRecipe, and then we will give it the id. If we give it that invalid id, we need to make sure that we handle it properly. When that happens, your recipe's going to be null. So let's handle that. If recipe == null, we will hide the titleView.
titleView.setVisibility(View.GONE). We will also change the descriptionView to say recipe not found. descriptionView.setText(R.string.recipe_not_found). We don't have the string yet, so press Alt+Enter to define it. Choose Create string value resource. We will put in the value "Recipe not found" and press OK.
If the recipe is null, that's it. We are done in the onCreate function. So in line 31, say return. If we did not return from this if block, we know that we have a valid recipe. So we can go ahead and show that in our titleView and our descriptionView. titleView.setText, and then we will call recipe.title. Do the same thing for the descriptionView. descriptionView.setText, and then recipe.description.
Great! That was a lot of code. Let's run this app to see what it does. Press the green triangle. Here, we are in the main activity with the list of recipes. Click on Chocolate Pudding. Yay! We got sent into the recipe activity with the proper title and the description loaded. Next, we are going to add one more feature to the app, which is to allow the user to mark some recipes as favorites.
- Why test?
- Local vs. on-device
- Code coverage
- UI testing
- Hermetic environment
- Dependency injection
- Testing with MVP