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 different cryptocurrencies inside our application in RecyclerView.
What We Will be Building in this Application?
We will be building a simple application in which we will be displaying the rates of different cryptocurrencies inside our app’s RecyclerView. Below is the video in which we will get to see what we are going to build in this article. Note that we are going to implement this project using the Java language.
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.
Step 2: Before going to the coding section first you have to do some pre-task
Go to app > res > values > colors.xml section and set the colors for your app.
XML
<? xml version = "1.0" encoding = "utf-8" ?> < resources > < color name = "purple_200" >#0F9D58</ color > < color name = "purple_500" >#0F9D58</ color > < color name = "purple_700" >#0F9D58</ color > < color name = "teal_200" >#0F9D58</ color > < color name = "teal_700" >#FF018786</ color > < color name = "black" >#FF000000</ color > < color name = "white" >#FFFFFFFF</ color > < color name = "blac_shade_1" >#292D36</ color > < color name = "black_shade_2" >#272B33</ color > < color name = "black_shade_3" >#22252D</ color > < color name = "dark_blue_shade" >#021853</ color > < color name = "yellow" >#ffa500</ color > </ resources > |
Step 3: Adding dependency for Volley in build.gradle file
Go to Gradle Scripts > build.gradle (Module: app) section and import the following dependencies and click the “Sync Now” on the above pop-up.
// Volley library implementation 'com.android.volley:volley:1.1.1'
Step 4: Adding Internet Permissions in the AndroidManifest.xml file
Navigate to the app > AndroidManifest.xml file and add the below line of code in it.
XML
< uses-permission android:name = "android.permission.INTERNET" /> |
Step 5: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<? xml version = "1.0" encoding = "utf-8" ?> < RelativeLayout android:layout_width = "match_parent" android:layout_height = "match_parent" android:background = "@color/blac_shade_1" tools:context = ".MainActivity" > <!--edit text for searching our currency--> < EditText android:id = "@+id/idEdtCurrency" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_margin = "8dp" android:focusable = "auto" android:hint = "Search Currency" android:textColor = "@color/white" android:textColorHint = "@color/white" /> <!--recycler view for displaying the list of currencies--> < androidx.recyclerview.widget.RecyclerView android:id = "@+id/idRVcurrency" android:layout_width = "match_parent" android:layout_height = "match_parent" android:layout_below = "@id/idEdtCurrency" tools:listitem = "@layout/currency_rv_item" /> <!--progress bar for loading indicator--> < ProgressBar android:id = "@+id/idPBLoading" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_centerInParent = "true" android:visibility = "gone" /> </ RelativeLayout > |
Step 6: Creating a new Java file for storing our data
We have to store the data in a modal class for that we will be creating a new Java class file. For creating this file. Navigate to the app > java > your app’s package name > Right-click on it > New > Java Class option and then choose Class and name your file as CurrencyModal and add below code to it. Comments are added in the code to get to know in more detail.
Java
package com.gtappdevelopers.cryptotracker; public class CurrencyModal { // variable for currency name, // currency symbol and price. private String name; private String symbol; private double price; public CurrencyModal(String name, String symbol, double price) { this .name = name; this .symbol = symbol; this .price = price; } public String getName() { return name; } public void setName(String name) { this .name = name; } public String getSymbol() { return symbol; } public void setSymbol(String symbol) { this .symbol = symbol; } public double getPrice() { return price; } public void setPrice( double price) { this .price = price; } } |
Step 7: Creating a new layout file for our item of RecyclerView
Navigate to the app > res > layout > Right-click on it > New > Layout file and name it as currency_rv_item and add below code to it. Comments are added in the code to get to know in more detail. The below layout file be used to display each item of our RecyclerView.
XML
<? xml version = "1.0" encoding = "utf-8" ?> < androidx.cardview.widget.CardView android:id = "@+id/idCVCurrency" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_margin = "4dp" app:cardBackgroundColor = "@color/black_shade_2" app:cardCornerRadius = "4dp" app:cardElevation = "3dp" > < RelativeLayout android:id = "@+id/idRLCurrency" android:layout_width = "match_parent" android:layout_height = "wrap_content" > <!--text view for displaying symbol--> < TextView android:id = "@+id/idTVSymbol" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_margin = "2dp" android:layout_toStartOf = "@id/idTVRate" android:layout_toLeftOf = "@id/idTVRate" android:padding = "3dp" android:text = "Symbol" android:textColor = "@color/white" android:textStyle = "bold" /> <!--text view for displaying currency name--> < TextView android:id = "@+id/idTVName" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_below = "@id/idTVSymbol" android:layout_margin = "2dp" android:padding = "3dp" android:text = "Name" android:textColor = "@color/white" android:textSize = "13sp" /> <!--text view for displaying currency rate--> < TextView android:id = "@+id/idTVRate" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_alignParentEnd = "true" android:layout_alignParentRight = "true" android:layout_marginStart = "2dp" android:layout_marginLeft = "2dp" android:layout_marginTop = "2dp" android:layout_marginEnd = "3dp" android:layout_marginRight = "3dp" android:layout_marginBottom = "2dp" android:padding = "3dp" android:text = "123456" android:textColor = "@color/white" /> </ RelativeLayout > </ androidx.cardview.widget.CardView > |
Step 8: Creating a new Java class file for our Adapter class
Now for setting data to each item of our Recycler View. We have to create a new adapter class for setting data to each item of our Recycler View. For creating a new Java file, navigate to the app > java > your app’s package name > Right-click on it > New > Java File/Class and name it as CurrencyRVAdapter and add the below code to it. Comments are added in the code to get to know in more detail.
Java
package com.gtappdevelopers.cryptotracker; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.text.DecimalFormat; import java.util.ArrayList; // on below line we are creating our adapter class // in this class we are passing our array list // and our View Holder class which we have created. public class CurrencyRVAdapter extends RecyclerView.Adapter<CurrencyRVAdapter.CurrencyViewholder> { private static DecimalFormat df2 = new DecimalFormat( "#.##" ); private ArrayList<CurrencyModal> currencyModals; private Context context; public CurrencyRVAdapter(ArrayList<CurrencyModal> currencyModals, Context context) { this .currencyModals = currencyModals; this .context = context; } // below is the method to filter our list. public void filterList(ArrayList<CurrencyModal> filterlist) { // adding filtered list to our // array list and notifying data set changed currencyModals = filterlist; notifyDataSetChanged(); } @NonNull @Override public CurrencyRVAdapter.CurrencyViewholder onCreateViewHolder( @NonNull ViewGroup parent, int viewType) { // this method is use to inflate the layout file // which we have created for our recycler view. // on below line we are inflating our layout file. View view = LayoutInflater.from(context).inflate(R.layout.currency_rv_item, parent, false ); return new CurrencyRVAdapter.CurrencyViewholder(view); } @Override public void onBindViewHolder( @NonNull CurrencyRVAdapter.CurrencyViewholder holder, int position) { // on below line we are setting data to our item of // recycler view and all its views. CurrencyModal modal = currencyModals.get(position); holder.nameTV.setText(modal.getName()); holder.rateTV.setText( "$ " + df2.format(modal.getPrice())); holder.symbolTV.setText(modal.getSymbol()); } @Override public int getItemCount() { // on below line we are returning // the size of our array list. return currencyModals.size(); } // on below line we are creating our view holder class // which will be used to initialize each view of our layout file. public class CurrencyViewholder extends RecyclerView.ViewHolder { private TextView symbolTV, rateTV, nameTV; public CurrencyViewholder( @NonNull View itemView) { super (itemView); // on below line we are initializing all // our text views along with its ids. symbolTV = itemView.findViewById(R.id.idTVSymbol); rateTV = itemView.findViewById(R.id.idTVRate); nameTV = itemView.findViewById(R.id.idTVName); } } } |
Step 9: Generating the API key and getting the URL for fetching data in JSON format
Go to the below link. After that, you simply have to sign up and create a new account on this website. After creating a new account simply sign in with your credentials and then you will get to see the below page.
On this page, we simply have to click on the Copy key option to copy your key. We have to use this key in our code in headers which are added below.
Step 10: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. 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.gtappdevelopers.cryptotracker; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class MainActivity extends AppCompatActivity { // creating variable for recycler view, // adapter, array list, progress bar private RecyclerView currencyRV; private EditText searchEdt; private ArrayList<CurrencyModal> currencyModalArrayList; private CurrencyRVAdapter currencyRVAdapter; private ProgressBar loadingPB; @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); searchEdt = findViewById(R.id.idEdtCurrency); // initializing all our variables and array list. loadingPB = findViewById(R.id.idPBLoading); currencyRV = findViewById(R.id.idRVcurrency); currencyModalArrayList = new ArrayList<>(); // initializing our adapter class. currencyRVAdapter = new CurrencyRVAdapter(currencyModalArrayList, this ); // setting layout manager to recycler view. currencyRV.setLayoutManager( new LinearLayoutManager( this )); // setting adapter to recycler view. currencyRV.setAdapter(currencyRVAdapter); // calling get data method to get data from API. getData(); // on below line we are adding text watcher for our // edit text to check the data entered in edittext. searchEdt.addTextChangedListener( new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { // on below line calling a // method to filter our array list filter(s.toString()); } }); } private void filter(String filter) { // on below line we are creating a new array list // for storing our filtered data. ArrayList<CurrencyModal> filteredlist = new ArrayList<>(); // running a for loop to search the data from our array list. for (CurrencyModal item : currencyModalArrayList) { // on below line we are getting the item which are // filtered and adding it to filtered list. if (item.getName().toLowerCase().contains(filter.toLowerCase())) { filteredlist.add(item); } } // on below line we are checking // weather the list is empty or not. if (filteredlist.isEmpty()) { // if list is empty we are displaying a toast message. Toast.makeText( this , "No currency found.." , Toast.LENGTH_SHORT).show(); } else { // on below line we are calling a filter // list method to filter our list. currencyRVAdapter.filterList(filteredlist); } } private void getData() { // creating a variable for storing our string. // creating a variable for request queue. RequestQueue queue = Volley.newRequestQueue( this ); // making a json object request to fetch data from API. JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null , new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // inside on response method extracting data // from response and passing it to array list // on below line we are making our progress // bar visibility to gone. loadingPB.setVisibility(View.GONE); try { // extracting data from json. JSONArray dataArray = response.getJSONArray( "data" ); for ( int i = 0 ; i < dataArray.length(); i++) { JSONObject dataObj = dataArray.getJSONObject(i); String symbol = dataObj.getString( "symbol" ); String name = dataObj.getString( "name" ); JSONObject quote = dataObj.getJSONObject( "quote" ); JSONObject USD = quote.getJSONObject( "USD" ); double price = USD.getDouble( "price" ); // adding all data to our array list. currencyModalArrayList.add( new CurrencyModal(name, symbol, price)); } // notifying adapter on data change. currencyRVAdapter.notifyDataSetChanged(); } catch (JSONException e) { // handling json exception. e.printStackTrace(); Toast.makeText(MainActivity. this , "Something went amiss. Please try again later" , Toast.LENGTH_SHORT).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // displaying error response when received any error. Toast.makeText(MainActivity. this , "Something went amiss. Please try again later" , Toast.LENGTH_SHORT).show(); } }) { @Override public Map<String, String> getHeaders() { // in this method passing headers as // key along with value as API keys. HashMap<String, String> headers = new HashMap<>(); headers.put( "X-CMC_PRO_API_KEY" , "Enter your API key" ); // at last returning headers return headers; } }; // calling a method to add our // json object request to our queue. queue.add(jsonObjectRequest); } } |
Now run your app and see the output of the app
Output: