The Wayback Machine - https://web.archive.org/web/20241009145054/https://www.geeksforgeeks.org/how-to-build-a-bitcoin-tracker-android-app/
Open In App

How to Build a Bitcoin Tracker Android App?

Last Updated : 01 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will be building a Bitcoin Tracker App Project using Java and XML in Android. The application will display the current rates of Bitcoin in different countries using Bitcoin API. There are many free APIs available and for this project, we will be using API by Coinlayer. The API will return a JSON that we will parse according to our needs. There will be a single activity in this app. A sample GIF is given below to get an idea about what we are going to do in this article. 


Step-by-Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.

Note that select Java as the programming language.

Application Directory Structure

btc1


Step 2: Before going to the coding section first you have to do some pre-task

1. Permissions: To use the internet access and call the API, we need permission. Add internet permission in the AndroidManifest.xml file

<uses-permission android:name=”android.permission.INTERNET”/>

2. Change the style to NoActionBar in the themes.xml file: (No need to do this step for Android Studio version: Koala 2024.1.1 and later)

<style name=”AppTheme” parent=”Theme.AppCompat.NoActionBar”>

3. Get the API key: You need to create a free account on Coinlayer and get an API key for this project.

Click on “Get free API key” on the website

btc2

SignUp using your account information, and you will get your API key.

btc3


4. Adding dependency: 

Navigate to Gradle Scripts > build.gradle (app: module)

btc4


We need to add this dependency in the app gradle file to make HTTP requests. This HTTP request will be made to the API URL to get the current value of bitcoin in various currencies as a response.

implementation ‘com.loopj.android:android-async-http:1.4.9’


5. Add Currency list in string.xml:

Navigate to res > values > strings.xml

btc5


We need to add the list of all currencies in the strings.xml. From here we will display it in the activity to the users. Add the below code in the strings.xml file.

XML
<resources>
    <string name="app_name">Am I Rich?</string>
    <string name="label_default_text">304.74</string>
    <string name="label_error_text">Error</string>
    <string name="base">Base Currency</string>
    <string name="imageview_desc">Bitcoin Logo</string>

    <string-array name="currency_array">
        <item>AUD</item>
        <item>BRL</item>
        <item>CAD</item>
        <item>CNY</item>
        <item>EUR</item>
        <item>GBP</item>
        <item>HKD</item>
        <item>JPY</item>
        <item>PLN</item>
        <item>RUB</item>
        <item>SEK</item>
        <item>USD</item>
        <item>ZAR</item>
    </string-array>
    
</resources>


6. Adding Bitcoin Image

Download the bitcoin image from here and add it into your project inside the app > res > drawable folder

btc6


Refer this article: How to Add Image to Drawable Folder in Android Studio?


Step 3: Working with the activity_main.xml file

The XML codes are used to build the structure of the activity as well as its styling part. It contains an ImageView at the very top of the activity to display the logo of the app. Then it contains a TextView to display the bitcoin rate in the center of the activity. At last, we have a Spinner at the bottom of the activity to display the list of currencies from which the user can choose. This is a single activity application. Below is the code for the activity_main.xml file.

XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#6495ed"
    tools:context="com.example.bitcointracker.MainActivity">

    <TextView
        android:id="@+id/priceLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/label_default_text"
        android:textColor="#daa520"
        android:textSize="45sp"
        android:textStyle="bold" />

    <ImageView
        android:id="@+id/logoImage"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:contentDescription="@string/imageview_desc"
        android:layout_marginTop="50dp"
        android:src="@drawable/bitcoin_img" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/priceLabel"
        android:gravity="center_vertical|center_horizontal"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:text="@string/base"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textSize="30sp"
            android:textStyle="bold" />

        <Spinner
            android:id="@+id/currency_spinner"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:dropDownSelector="#daa520"
            android:gravity="center_horizontal"
            android:spinnerMode="dropdown" />

    </LinearLayout>

</RelativeLayout>


Step 4: Create new layout resource files

For the spinner to display the list we also need to create a spinner item’s XML layout as well as its item’s layout for the adapter. Add the below code in app > res > layout > spinner_item.xml.

spinner_item.xml file:

XML
<?xml version="1.0" encoding="utf-8"?>
<TextView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="start"
    android:padding="10dip"
    android:text="@string/label_error_text"
    android:textColor="@color/black"
    android:textSize="30sp"
    android:textStyle="bold" />


Step 5: Working with the MainActivity.java file

In the java file, we will create a function that will make HTTP requests from the URL. The URL will be consisting of the API key the base URL and the target currency code.

  • First, we will create an adapter for the list of all the currencies and set it to the Spinner view in the main activity. The Array we created in Strings.xml will be used here.
  • Then we will call the function onItemSelectedListener and get the selected currency code.
  • When a new currency is selected, the API will be automatically called to provide the rate of Bitcoin in the selected currency.
  • Then we will call the function that makes HTTP requests to get a JSON. We will parse the JSON object to get the required rate of the bitcoin of the selected currency.

Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

Java
package com.example.bitcointracker;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import cz.msebera.android.httpclient.Header;

public class MainActivity extends AppCompatActivity {

    // Constants:
    // TODO: Create the base URL
    private final String BASE_URL = "http://api.coinlayer.com/live?access_key=";

    // Member Variables:
    TextView mPriceTextView;

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

        mPriceTextView = findViewById(R.id.priceLabel);
        Spinner spinner = findViewById(R.id.currency_spinner);

        // Create an ArrayAdapter using the String array and a spinner layout
        final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.currency_array, R.layout.spinner_item);

        // Specify the layout to use when the list of choices appears
        adapter.setDropDownViewResource(R.layout.spinner_item);

        // Apply the adapter to the spinner
        spinner.setAdapter(adapter);

        // TODO: Set an OnItemSelected listener on the spinner
        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                  // The API key you got when you signed up inside coinlayer.com
                String publicKey = "cd9ebbd0c5c20340b9d638e409f41fb1";
                String finalUrl = BASE_URL + publicKey + "&TARGET=" + adapterView.getItemAtPosition(i) + "&symbols=BTC";
                try {
                    letsDoSomeNetworking(finalUrl);
                } catch (IOException | JSONException e) {
                    System.out.println(e);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    // TODO: complete the letsDoSomeNetworking() method
    private void letsDoSomeNetworking(String url) throws IOException, JSONException {


        AsyncHttpClient client = new AsyncHttpClient();
        client.get(url, new JsonHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                // called when response HTTP status is "200 OK"
                Log.d("Clima", "JSON: " + response.toString());
                try {
                    JSONObject price = response.getJSONObject("rates");
                    String object = price.getString("BTC");
                    mPriceTextView.setText(object);
                } catch (JSONException E) {
                    E.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable e, JSONObject response) {
                // called when response HTTP status is "4XX" (eg. 401, 403, 404)
                  // Below lines are used for getting the cause of failure.
                  // These are used for debugging
                Log.d("Clima", "Request fail! Status code: " + statusCode);
                Log.d("Clima", "Fail response: " + response);
                Log.e("ERROR", e.toString());
            }
        });

    }
}

Output:


Note : To access the full android application check this repository: Bitcoin Tracker Android




Previous Article
Next Article

Similar Reads

How to Build a Cryptocurrency Tracker Android App?
CryptoCurrency nowadays is in most demand and many people are investing in these currencies to get high returns. Many websites and applications provide us information about the rates of different cryptocurrencies available in the Crypto Market. In this article, we will be building a similar application in which we will be displaying the rates of di
10 min read
How to Create a COVID-19 Tracker Android App to See Details of any City and State in India?
In the previous article, we have discussed How to create a COVID-19 Tracker Android App which shows only the Global Stats. In this article, we will learn how to create a COVID-19 Tracker Android App which will show the details of any city in any State in India. Details like - Total Active cases, Cured Cases, Deaths, and the total number of confirme
9 min read
How to Create a Medicine Tracker Android App with Firebase?
A medicine tracker app can be a useful tool for individuals who need to take multiple medications on a regular basis. It can help users track when they need to take their medications and provide alerts and reminders to ensure they don't miss a dose. This article will look at how to build a medicine tracker app using Kotlin and Firebase. A sample vi
8 min read
How to Build a Number Shapes Android App in Android Studio?
Android is a vast field to learn and explore and to make this learning journey more interesting and productive we should keep trying new problems with new logic. So, today we are going to develop an application in android studio which tells us about Numbers that have shapes. We will be covering two types of numbers i.e. triangular and square. So, f
4 min read
How to Build Binary to Decimal Converter Android App in Android Studio?
This app will convert a Binary Number into a Decimal Number. Some people may also have written a java program to convert a Binary Number into a Decimal Number, but while making an app let's see how to do that. Brief Go Through We will start by creating a new project with an Empty Activity. After creating a project, we would add the drawable resourc
5 min read
How to Build a Prime Number Checker Android App in Android Studio?
A prime number is a natural number greater than 1, which is only divisible by 1 and itself. First few prime numbers are : 2 3 5 7 11 13 17 19 23 …... In this article, we will be building a Prime Number Checker android app in Android Studio using Kotlin and XML. The app will check whether the entered number is a Prime number or not, if the entered w
3 min read
Build an Android App with HTML, CSS and JavaScript in Android Studio
Android is a mobile operating system based on a modified version of the Linux kernel and other open-source software, designed primarily for touchscreen mobile devices such as smartphones and tablets. Yes, you read it right in the title of this article. In this article, we are going to build an Android App with HTML, CSS, and JavaScript in Android S
2 min read
Android Java Projects - Build Your First Android App from Scratch
Are you eager to boost your Android development skills and create cool projects? Our blog post, "Android Java Projects," is here to help! Whether you're just starting your software development career or want to add good projects to your CV then, working on real projects is the best way to learn and grow as a developer. In this post, we've gathered
6 min read
How to Build Decimal to Hexadecimal Converter Android App in Android Studio?
In this article, we would be learning how to make a Decimal to Hexadecimal Converter App in Java in Android Studio. This app would take an input of a Decimal number, convert it into a Hexadecimal number and then show the output. So let's go through the brief go through of how we would be making the app. Brief Go throughWe will begin by first creati
5 min read
How to Build a Decimal to Binary Converter Android App in Android Studio?
This app will convert a Decimal Number into a Binary Number. Some people may also have written a java program to convert a Decimal Number into Binary Number, but while making an app let's see how to do that.  Brief Go throughWe will start by creating a new project with an Empty Activity. After creating a project, we would add the drawable resource
5 min read
How to Build a Simple Android App with Flask Backend?
Flask is an API of Python that allows us to build up web applications. It was developed by Armin Ronacher. Flask’s framework is more explicit than Django’s framework and is also easier to learn because it has less base code to implement a simple web-Application. A Web-Application Framework or Web Framework is the collection of modules and libraries
8 min read
How to Build a QR Code Android App using Firebase?
QR (Quick Response) code is a type of two-dimensional barcode that contains information encoded in a pattern of black and white squares. It was first developed in 1994 by a company named Denso Wave. Qr codes can be scanned by a smartphone or a dedicated QR code scanner, which uses the device's camera to read the code and extract the information sto
6 min read
How to Build a Simple Magic 8 Ball App in Android?
In this article, we will be building a Magic 8 Ball App Project using Java and XML in Android. The application is based on a decision making application. In this app, a user can ask the ball what decision they should make. The ball will randomly answer Yes, No, Not Sure, and other such answers. There will be a single activity in this application. A
3 min read
How to Build a Book Library App using Google Books API in Android?
If you are looking for building a book library app and you want to load a huge data of books then for adding this feature, you have to use a simple API which is provided by Google, and of course, it's free. In this article, we will take a look at the implementation of this API in our Android App. What we are going to build in this article? We will
13 min read
How to Build a Simple Alarm Setter App in Android?
In this article, we are going to see how to build a much interesting app named Alarm Setter. Alarm plays a vital role in our day-to-day life. Nowadays alarm has become our wake-up assistant. Every mobile phone is associated with an alarm app. We will create this app using android studio. Android Studio provides a great unified environment to build
6 min read
How to Build a Palindrome Checker App in Android Studio?
In this article, we will be building a Palindrome Checker android app in Android Studio using Kotlin and XML. The app will check whether the entered word is Palindrome or not, if the entered word is a Palindrome then a toast will be displayed having the message "Entered word is Palindrome" otherwise Toast's message will be "Entered word is not a Pa
3 min read
Build an Android App to Check COVID-19 Vaccination Availability
Pre-requisites: Android App Development Fundamentals for BeginnersGuide to Install and Set up Android StudioAndroid | How to Create/Start a New Project in Android Studio?Android | Running your first Android appREST API (Introduction)Volley Library in Android https://www.youtube.com/watch?v=F-E6mFPIOrY The government of India has started the biggest
12 min read
How to Build a News App Using WebView Controller in Android Studio?
In this article, we are going to make a News App with help of a WebView Controller in Android Studio. By making this application we will learn how to access Internet Permission in our android application and how to use WebView with its class named WebView Controller. After making this application you will also be aware of Navigation Drawer activity
7 min read
How to Build a Simple Voice Typer App in Android using Java?
Pre-requisites: Android App Development Fundamentals for BeginnersGuide to Install and Set up Android StudioHow to Create/Start a New Project in Android Studio?Running your first Android appSpinner in AndroidRecognizerIntent in Android In this article, we are going to build a simple Voice Typer app in Android using Java. This is a glimpse of the ap
5 min read
How to Build a Simple Note Android App using MVVM and Room Database?
Android provides us a feature with which we can store users' data inside their mobile itself with different storage options such as Shared Preferences, SQLite database, and the Room Database. All the data storing techniques are having different use cases. In this article, we will specifically take a look at using a Room Database with Architecture C
15+ min read
Build an Android App to Check a Year is Leap Year or Not
In this article, we will learn how to make an App to check a year is a leap year or not. Before that, we need to have an idea of what is a leap year? If a year is: Multiple of 400multiple of 4 and not multiple of 100 Then the year is a leap year. Algorithmif the year is divisible by 400 then it is a leap year.else if the year is divisible by 100 th
3 min read
Build an Android App to Check a Number is Armstrong or Not
What is Armstrong's number? A number is said to be Armstrong if the sum of its digits is raised to the power of the total number of digits in the number. Given a number x, determine whether the given number is Armstrong's number or not. A positive integer of n digits is called an Armstrong number of order n (order is the number of digits) if. abcd.
3 min read
Build an Android App to Check a Number is Automorphic or Not
What is an Automorphic number? A number is said to be Automorphic if its square ends in the same digits as the number itself. Examples: Input : N = 76 Output : Automorphic Explanation: As 76*76 = 5776 Input : N = 25 Output : Automorphic As 25*25 = 625 Input : N = 7 Output : Not Automorphic As 7*7 = 49Step by Step Implementation Step 1: Create a New
3 min read
How to Build SIP Calculator Android App using MVP Architecture?
SIP, the Systematic Investment Plan. One of the methods to invest in Mutual Funds is weekly, monthly quarterly, or half-yearly. The SIP calculator is the tool to get an idea for investors about their investment returns. However, the returns of mutual funds vary on various factors. For example, the SIP calculator does not calculate the Absolute retu
10 min read
How to Build a Simple Expense Calculator App in Android?
Pre-requisites: Android App Development Fundamentals for BeginnersGuide to Install and Set up Android StudioHow to Create/Start a New Project in Android Studio?Running your first Android appRecyclerView in Android with ExampleShared Preferences in Android with Example A simple expense calculator lets you add income and expenditures in a simplified
10 min read
How to Build a Simple e-Crackers App using Android?
Pre-requisites: Android App Development Fundamentals for BeginnersGuide to Install and Set up Android StudioHow to Create/Start a New Project in Android Studio?Running your first Android appHow to add Lottie Animation in an Android AppMediaPlayer Class in Android In this article, we are going to build a simple e-Crackers app. It consists of a singl
12 min read
Build Modular Android App Architecture with Example
Modules are piece of code that is independently created and maintained and can be used in a different system. In Android apps modules can be a simple feature like Search or it may be purchased on demand. For eg. In gaming apps like PUBG, skins of the guns and the character are also a module. There are several modules namely they are, Application mo
4 min read
How to Build an Android App to Compress Video?
Nowadays we see many applications are made to compress videos and other files so that users can save memory as well as maintain the quality of that file. In this article, we are going to see how we can compress videos in the android studio and can make our own video compressing application. What we are going to build in this article? Below is a sam
5 min read
How to Build a Simple Torch App in Android using Kotlin?
Torch Application is a very basic application that every beginner level android developer should definitely try to build while learning Android. In this article, we will be creating an application in which we will simply display a toggle button to switch on and switch off the torch. Note: If you are looking to implement the Torch application in and
4 min read
Android - Build a Book Library App using Kotlin
There are so many apps that are present in the play store which provides details related to different books inside it. Book Library is considered one of the basic applications which a beginner can develop to learn some basic concepts within android such as JSON parsing, using recycler view, and others. In this article, we will be building a simple
11 min read