Avin's Blog

Android Basics: Introduction and Setup

May 19, 2020
Tags: Android, Android Basics, Github API, Github Repository App,

Android Basics will be a series on topics that are essential for Android Development. We will go through Async Task, JSON parsing, Recycler View, Intents, Fragments, Android Lifecycle, Content Providers and a lot more. We will learn about all the topics by implementing them in the Github Repository Search App. I do assume you know what XML is and how to reference the XML objects in Java.

The reason we are using the Github repo search API is because it does not require you to get an API key and is pretty straight forward to use.

Lets start with creating a new project with empty activity.

New Project

Accessing the Internet

Add the following dependency in your app level build.gradle and then sync it. I am using OkHttp for the network queries.

implementation("com.squareup.okhttp3:okhttp:4.7.1")

Now lets create network utilities so that we can build and query the url. We create a separate package called utilities and add classes like NetworkUtils so that they can be used everywhere else in the app.

Create a new package called utilities and in that package/folder create a new class and name it NetworkUtils. Network Utils

Add the following code to it we will use this later to get results of our github search query.

package com.avinsharma.githubrepositorysearch.utilities;

import android.net.Uri;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class NetworkUtils {
    private static final OkHttpClient client = new OkHttpClient();

    final static String GITHUB_BASE_URL = "https://api.github.com/search/repositories";
    final static String PARAM_QUERY = "q";

    /*
     * The sort field. One of stars, forks, or updated.
     * Default: results are sorted by best match if no field is specified.
     */
    final static String PARAM_SORT = "sort";
    final static String sortBy = "stars";

    /**
     * Builds the URL used to query GitHub.
     *
     * @param githubSearchQuery The keyword that will be queried for.
     * @return The URL to use to query the GitHub server.
     */
    public static URL buildUrl(String githubSearchQuery) {
        Uri builtUri = Uri.parse(GITHUB_BASE_URL).buildUpon()
                .appendQueryParameter(PARAM_QUERY, githubSearchQuery)
                .appendQueryParameter(PARAM_SORT, sortBy)
                .build();

        URL url = null;
        try {
            url = new URL(builtUri.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        return url;
    }

    /**
     * This method returns the entire result from the HTTP response.
     *
     * @param url The URL to fetch the HTTP response from.
     * @return The contents of the HTTP response.
     * @throws IOException Related to network and stream reading
     */
    public static String getResponseFromHttpUrl(URL url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }
}

Since we are accessing the Internet we need to have permission to do so. So we add the permission in the manifest.xml below the manifest opening tag.

<!--Permission to access internet-->
<uses-permission android:name="android.permission.INTERNET"/>

Layout for the app

Right now we are trying to search for a repo and get some JSON back as the result of query. So we are going to keep it simple and build a layout which allows us to search and see the result of our search.

Add the following to your res -> layout -> activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <EditText
        android:id="@+id/et_search_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Search for repos..."/>

    <Button
        android:id="@+id/button_search"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="16dp"
        android:text="Search"
        android:layout_gravity="center"/>

    <!-- To scroll if the result is longer than our screen -->
    <ScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/tv_search_result"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

    </ScrollView>

</LinearLayout>

Connecting layout to code

We first create views in our MainActivity.java and then initialize them in onCreate finding them by their id.

public class MainActivity extends AppCompatActivity {

    private EditText mSearchQueryEditText;
    private Button mSearchButton;
    private TextView mSearchResultTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mSearchQueryEditText = findViewById(R.id.et_search_bar);
        mSearchButton = findViewById(R.id.button_search);
        mSearchResultTextView = findViewById(R.id.tv_search_result);
    }
}

Now that we have our layout and views setup, we are ready to tackle the next AsyncTask. AsyncTasks are used to run tasks off of main UI thread. Since fetching data from the internet may take sometime we cannot do it on the main UI thread, we use AsyncTask instead.

Right now our app looks like this:

app

You can find the code here.

In the next post we are going to add functionality to the search button, so that when we press search it fetches search results from Github and display the search results on our TextView.




This website may contain affiliate links, meaning I may receive a small commission for products purchased through these link at no extra cost to you.