📜  如何构建加密货币跟踪器 Android 应用程序?

📅  最后修改于: 2021-10-21 05:42:44             🧑  作者: Mango

如今,加密货币的需求量最大,许多人都在投资这些货币以获得高回报。许多网站和应用程序向我们提供了有关加密市场中可用的不同加密货币汇率的信息。在本文中,我们将构建一个类似的应用程序,在该应用程序中,我们将在 RecyclerView 的应用程序中显示不同加密货币的汇率。

How-to-Build-a-Cryptocurrency-Tracker-Android-App

我们将在此应用程序中构建什么?

我们将构建一个简单的应用程序,在该应用程序中,我们将在应用程序的 RecyclerView 中显示不同加密货币的汇率。在下面的视频中,我们将看到我们将在本文中构建的内容。请注意,我们将使用Java语言来实现这个项目。

分步实施

第 1 步:创建一个新项目

要在 Android Studio 中创建新项目,请参阅如何在 Android Studio 中创建/启动新项目。请注意,选择Java作为编程语言。

第 2 步:在进入编码部分之前,您必须先做一些预任务

转到app > res > values > colors.xml部分并为您的应用设置颜色。

XML


    #0F9D58
    #0F9D58
    #0F9D58
    #0F9D58
    #FF018786
    #FF000000
    #FFFFFFFF
 
    #292D36
    #272B33
    #22252D
    #021853
    #ffa500
 


XML


XML


 
    
    
 
    
    
 
    
    
 


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;
    }
}


XML


 
    
 
        
        
 
        
        
 
        
        
 
    
 


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 {
    private static DecimalFormat df2 = new DecimalFormat("#.##");
    private ArrayList currencyModals;
    private Context context;
 
    public CurrencyRVAdapter(ArrayList currencyModals, Context context) {
        this.currencyModals = currencyModals;
        this.context = context;
    }
 
    // below is the method to filter our list.
    public void filterList(ArrayList filterllist) {
        // adding filtered list to our
          // array list and notifying data set changed
        currencyModals = filterllist;
        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);
        }
    }
}


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 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 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 emoty 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.
        String url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest";
        // 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() {
            @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 getHeaders() {
                // in this method passing headers as
                  // key along with value as API keys.
                HashMap 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);
    }
}


第 3 步:在 build.gradle 文件中为 Volley 添加依赖项

转到Gradle Scripts > build.gradle (Module: app)部分并导入以下依赖项,然后单击上面弹出窗口中的“立即同步”。

// Volley library
implementation 'com.android.volley:volley:1.1.1'

第 4 步:在 AndroidManifest.xml 文件中添加 Internet 权限

导航到应用程序 > AndroidManifest.xml文件并在其中添加以下代码行。

XML


步骤 5:使用 activity_main.xml 文件

导航到app > res > layout > activity_main.xml并将以下代码添加到该文件中。下面是activity_main.xml文件的代码。

XML



 
    
    
 
    
    
 
    
    
 

第 6 步:创建一个新的Java文件来存储我们的数据

我们必须将数据存储在模态类中,因为我们将创建一个新的Java类文件。用于创建此文件。导航到应用程序 > Java > 您应用程序的包名称 > 右键单击它 > 新建 > Java类选项,然后选择类并将您的文件命名为 CurrencyModal 并将以下代码添加到其中。代码中添加了注释,以便更详细地了解。

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;
    }
}

第 7 步:为我们的 RecyclerView 项创建一个新的布局文件

导航到应用程序 > res > 布局 > 右键单击它 > 新建 > 布局文件并将其命名为currency_rv_item并向其添加以下代码。代码中添加了注释,以便更详细地了解。下面的布局文件用于显示我们 RecyclerView 的每个项目。

XML



 
    
 
        
        
 
        
        
 
        
        
 
    
 

第 8 步:为我们的 Adapter 类创建一个新的Java类文件

现在为我们的 Recycler View 的每个项目设置数据。我们必须创建一个新的适配器类来为我们的 Recycler View 的每个项目设置数据。要创建新的Java文件,请导航到应用程序 > Java > 您应用程序的包名称 > 右键单击它 > 新建 > Java文件/类并将其命名为CurrencyRVAdapter并将以下代码添加到其中。代码中添加了注释,以便更详细地了解。

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 {
    private static DecimalFormat df2 = new DecimalFormat("#.##");
    private ArrayList currencyModals;
    private Context context;
 
    public CurrencyRVAdapter(ArrayList currencyModals, Context context) {
        this.currencyModals = currencyModals;
        this.context = context;
    }
 
    // below is the method to filter our list.
    public void filterList(ArrayList filterllist) {
        // adding filtered list to our
          // array list and notifying data set changed
        currencyModals = filterllist;
        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);
        }
    }
}

第九步:生成API key,获取JSON格式的数据获取URL

转到以下链接。之后,您只需在该网站上注册并创建一个新帐户。创建新帐户后,只需使用您的凭据登录,然后您将看到以下页面。

在此页面上,我们只需单击“复制密钥”选项即可复制您的密钥。我们必须在下面添加的标头中的代码中使用此键。

第 10 步:使用MainActivity。 Java文件

转到主活动。 Java文件,参考如下代码。下面是MainActivity的代码。 Java文件。代码中添加了注释以更详细地理解代码。

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 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 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 emoty 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.
        String url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest";
        // 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() {
            @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 getHeaders() {
                // in this method passing headers as
                  // key along with value as API keys.
                HashMap 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);
    }
}

现在运行您的应用程序并查看应用程序的输出

输出

想要一个更快节奏和更具竞争力的环境来学习 Android 的基础知识吗?
单击此处前往由我们的专家精心策划的指南,旨在让您立即做好行业准备!