There are broadly two methods to execute queries in database –
Imperative – in this, code tells computer to perform certain operations in sequence. Most of the programming languages are imperative.
Declarative – in this method, one specifies the pattern of data needed, rest all is taken care by query optimizer. Most of the SQL languages are declarative. It is easier to work with, hides database engine’s implementation details. Also these languages support parallisation across multiple machines.
MapReduce Querying –
Neither imperative, nor declarative, combination of two.
It is based on the map (also known as collect) and reduce (also known as fold or inject) functions that exist in many functional programming languages.
Map and reduce are pure functions, which means they only use the data that is passed to them as input, they cannot perform additional database queries, and they must not have any side effects.
Thanks for stopping by! Hope this gives you a brief overview in to query languages for data models. Eager to hear your thoughts and chat, please leave comments below and we can discuss.
I am back with another update. I am thinking of one/two weekly updates instead of every alternate day as that sounds more feasible.
The DelightfullDiscoveries blog has four major categories and other minor categories of posts. The four major ones are Experiment In Kitchen, Recipes, Books, and Thoughts. The minor ones are Awards, Travel, and InANutshell. Right now we fetch all the posts irrespective of their categories and display them. But I want to group posts by their category and display them. That’s why I decided to use TabLayout with each tab displaying posts of a particular category. This led to complete overhaul of the app developed till now. And I ran into some issues, so only added four tabs for now.
Prior to any changes, the app looked like this:
activity_main.xml
If you remember from Day 2 when we added the RecyclerView to the main activity along with the ProgressBar from Day 1. Today, I movedthe RecyclerView, the ProgressBar, and the TextView to another Layout file called post_list.xml with FrameLayout as the root element.
Changed the root layout of activity_main.xml to linear layout with the vertical orientation and added TabLayout and ViewPager.
Fragments and FragmentPagerAdapter
Created Four Fragment classes: EIKFragment, BooksFragment, ThoughtsFragment and AwardsFragment which extends Fragment class and implemented the onCreateView method.
And moved the code handling the RecyclerView, ProgressBar and the TextView from MainActivity to each fragment. So basically what MainActivity was doing before, now each of these Fragments will do the same.
The first difference is in the URLs to get the posts (now the posts are accessed by category). Added another method in NetworkUtils called getUrlFromCategoryId(int id) to get posts with category “id”. And call this method from the AsyncTask class’s background method.
Having a different Loader ID (POST_LOADER_ID) for each fragment is necessary otherwise the fragments will get confused. Suppose the loader ID is same for EIKFragment and BooksFragment, we will see EIK’s posts in BooksFragment instead of EIKFragment. EIKFragment will go into infinite loop displaying only the ProgressBar.
Created CategoryAdapter which extends the FragmentPagerAdapter. FragmentPagerAdapter. This makes sure that each page represents a Fragment and that Fragment’s data remains in the FragmentManager so that user can come back afterward. The drawback here is with an increase in the number of posts with each category, the amount of data to be persisted will increase for each category resulting in the use of huge memory. Later, I might switch to FragmentStatePagerAdapter which deletes the fragment as soon as we switch to another fragment saving only the necessary data.
Another improvement that I can do is to reuse the fragment. All the four fragments have the same code. The only difference is the loader id and the URL to access the data. I am working on that right now.
MainActivity
Removed the menu implementation for now. Deleted the overridden methods of interfaces PostAdapter.PostAdapterOnClickHandler and LoaderManager.LoaderCallbacks<Post[]>.
Added the code to handle TabLayout and ViewPager.
PostDetailActivity
While going through post JSON, I found a field URL in every post. Earlier, I was passing slug and using it to create the same URL which is already present in a post. Therefore, while parsing JSON, I now fetch the URL and store along with other data in a Post object. And this URL is passed as extra data now, whenever we click on a post in the RecyclerView.
No need to create the URL in PostDetailsActivity now, just use the incoming URL and display it in the WebView.
The app looks like this now:
Files Created
EIKFragment.java
BooksFragment.java
ThoughtsFragment.java
AwardsFragment.java
CategoryAdapter.java
post_list.xml
Files Modified
MainActivity.java
PostDetailActivity.java
activity_main.xml
DDJsonUtils.java
NetworkUtils.java
Today’s task took 6 Pomodoros, ie, 2 hrs, 30 minutes.
I am back with another update. Today, I deal with orientation changes for both the activities (MainActivity and PostDetailActivity).
MainActivity
Let’s take the MainActivity first. It consists of a RecyclerView which displays the titles of all the posts fetched from the website. When I rotate the screen, it triggers another call to the internet to fetch data. We can see clearly, this last call is unnecessary as we already have the post objects list. Unnecessary network calls equal unnecessary network usage, the extra load on the battery and extra space.
Technically, when the orientation changes, Activity shuts down and restarts, calling separate AsyncTask which creates another background thread on which we communicate with the internet and fetch the data.
Or consider another scenario, we open the app, the current activity A creates a background thread 1 which sends a call to the internet. While the result is coming back, the user rotates the screen. Which restarts the current activity, call it B and creates another background thread 2 which also sends a call to the internet. Now there are two threads waiting for two network calls, equivalent to the extra network usage and longer time to get results. Also, the first async task will return data to an activity no longer there. These two backgrounds threads will keep on running until they get the result, resulting in extra memory usage.
To avoid this, I use AsynTaskLoader instead of AsyncTask which prevents duplicate loading. Loaders are registered with an ID by a component LoaderManager facilitating them to live beyond the lifecycle of the activity they are associated with. AsyncTaskLoader loads the data in the background thread. When the device is rotated, the LoadingManager makes sure runningLoader connects to the onLoadFinished function. Loader loads in the background, and sends the result to the onLoadFinished function on completion.
Changes made in the MainActivity to incorporate AsyncTaskLoader –
Delete inner class DDQueryTask.
Implement LoaderManager.LoaderCallbacks<Post[]>.
Override the methods onCreateLoader, onLoadFinished and onLoaderReset and implement them to load data in the background.
Initialize the loader inside the onCreate method.
Restart the loader when we click the REFRESH button on the menu.
After this, when we rotate the MainActivity we don’t see the data being reloaded.
WebView inside the PostDetailsActivity
When we click on a post in the MainActivity, it opens PostDetailsActivity which displays the URL in the WebView. When I rotate the screen, reloading happens. To prevent this we just need to add the following code to the PostDetailsActivity’s activity tag in AndroidManifest.xml. Here we don’t need to use AsyncTaskLoader or cache because the data is already there and we need to re-render it in the landscape view.
When we use android:configChanges, the activitywon’t shut down and restart on screen rotation. Instead, the onCOnfigurationChanged method is called which handles the configuration changes automatically. When this method is called, the resources object gets updated with newresource values matching the new configuration.
Now when we rotate the PostDetailsActivity screen, the webview doesn’t reload the URL.
Files Changed:
MainActivity.java
AndroidManifest.xml
Today’s update took me 2 Pomodoros i.e. 50 minutes.
Created another activity (PostDetailActivity) to be called using intent when we click on an individual post on our post list (recyclerview). We pass the slug derived from JSON data for that post as extra data to the intent.
PostDetailActivity’s layout is a webview. The webview will fetch the post using the URL. The URL is formed using the slug passed as extra with the intent. We pass the slug as a string to the getUrl method of the NetworkUtils class.
Added another method getUrl(String slug) inside the NetworkUtils class to create URL for fetching an individual post.
Added another class (Post) to store attributes of a single post. It stores id, title, slug for an individual post.
Each item of the RecyclerView was displayed as String before. But now each item is linked to a Post object having an id, title, and slug. And we have to pass the slug when we click on an item. Therefore we pass Post object instead of String Object to PostAdapterOnClickHandler’sonClick method. Changed String array to Post array for storing the posts received from the JSON.
Similarly implementation of the onCLick method of PostAdapterOnClickHandler in the MainActivity changes. Now it starts an intent which sends a call to PostDetailActivity with a slug as extra data.
The DDQueryTask returns a Post objects array instead of String array.
We extract the post title from Postobject using the getter methods to display them in the item’s TextView in PostAdapter class’s onBindViewHolder method.
In DDJsonUtils, we extract the post id, title, and slug as store the data as Post object inside the Post array.
Files Created
Post.java [Store the attributes of a post like an id, title, slug]
PostDetailsActivity.java [Fetch the correct URL corresponding to given slug in received Intent and display it using webview.]
activity_post_details.xml [Display the webview]
Files Modified
MainActivity.java,
activity_main.xml
NetworkUtils.java
DDJsonUtils.java
DDQueryTask
AndroidManifest.xml
All the above work was done in 3 Pomodoros, ie, 1 hour 15 minutes.
You can follow the progress on this application development on Day 0,Day 1, Day 2.
Today I went further in Delightfull Discoveries application development. And instead of a single textview, switched to a RecyclerView. That involved the following updations –
Replacing ScrollView with RecyclerView.
Creating a list item XML with LinearLayout and TextView to hold post titles inside and a view to display a line.
Creating the RecyclerViewAdapter and ViewHolder classes with the required methods.
Updating the MainActivity with RecyclerView object. Using LinearLayoutManager to set the RecyclerView’s orientation to vertical. Setting the Adapter on the object.
Adding item click by making the ViewHolder class implement the View.OnClickListener interface. For now, when we click an item, Toast message is displayed.
Files Created:
PostAdapter [which extends RecyclerView.Adapter class. It creates view holder for each item and binds data to them],
PostAdapterViewHolder [as an inner class inside PostAdapter. Extends RecyclerView.ViewHolder class. It creates the view objects and binds them to the item’s layout file. It also handles click actions, for which we implement View.OnCLickListener]
PostAdapterOnClickListener [an interface to receive onCLick messages.]
post_list_item.xml [layout file for an item inside RecyclerView.]
Files Edited:
MainActivity.java,
activity_main.xml
This is how the app looks right now –
Today I spent 3 Pomodoros, ie, 1 hour and 15 minutes on this application development. You can follow the progress of this development by going through Day 0 and Day 1 posts.
I am back as promised with another update regarding my Delightfull Discoveries App. You can check the [DD App] Day 0 post for more details.
We left last day with the app displaying a placeholder text as you can see in the below image.
The next step is to access these posts using the WordPress REST API from my blog and display their titles as a list. Earlier we needed to download a plugin to interact with our site using JSON objects. But that changed from WordPress version 4.7+. Now the REST API is integrated within the WordPress. And we can directly talk to the WordPress site using JSON.
So here is how I progressed today –
The URL to access WordPress blog’s posts as a list according to the API’s documentation is – “http://example.com/wp-json/wp/v2/posts”. I modified this URL according to the address of my blog to access the content.
I started with building the URL. It’s a two-step process. First, generating the URI using Android’s Uri class build method. Then converting the URI to URL by passing URI as a parameter to the URL object. This went fine. For testing, I displayed the URL in the TextView. The result displayed the right URL.
Next, I added the internet permission to the Android Manifest file. This makes sure our app has access to the internet. Otherwise, we will get SecurityException.
Now I needed to access the Http response from the URL and store it as a string. I used InputStreamReader and Scanner for this purpose.
To avoid NetworkOnMainThread Exception, I used AsyncTask‘s doInBackground() method to get the contents from the URL. Then it’s postExecute to display the JSON received in the textview. This step was also successful.
I don’t need the JSON with all the data. I only need the title of each post. This requires to parse the JSON string and extract the required fields. Which I did and extracted the titles into a string array.
Then updated the AsynTask class’s doInBackground method to return String array instead of a string. And displayed the contents of this array in the textview. But, there is an issue, the titles are displaying special characters weirdly as you can see in the screenshot.
Next, I changed the main_layout from LinearLayout to FrameLayout and added a textview to display error messages and a ProgressBar to display the loading progress. Currently, both of these views were set to invisible. If there is a problem in retrieving data from the API then the error message with become visible and the main textview will become invisible. The progress bar will be visible while the app is getting data from the API. Once it has the data, the progress bar will be invisible. Made necessary changes to the main activity to reflect this behavior.
Files Created:
NetworkUtils.java [Create URL, Get data from the internet],
DDJsonUtils.java [Parse JSON to get the required string],
DDQueryTask [inner class inside MainActivity.java to create a background thread on which network access will take place]
Files Edited:
MainActivity.java,
activity_main.xml
Today I spent 6 pomodoros on the development, ie, 150 minutes = 2 hours and 30 minutes.