📜  如何创建 COVID-19 追踪器 Android 应用

📅  最后修改于: 2022-05-13 01:54:27.283000             🧑  作者: Mango

如何创建 COVID-19 追踪器 Android 应用

先决条件:

  • 面向初学者的 Android 应用开发基础
  • 安装和设置 Android Studio 指南
  • 安卓 |如何在 Android Studio 中创建/启动新项目?
  • 安卓 |运行你的第一个 Android 应用
  • REST API(介绍)
  • Android 中的排球库

世界正面临着最严重的流行病之一,即 COVID-19 的爆发,你们都知道这一点。因此,在此锁定期间,让我们使用 REST API创建一个COVID-19 跟踪器 Android 应用程序,该应用程序跟踪全球统计数据

  1. Step1:打开一个新项目
    • 打开一个新项目只需单击左上角的文件选项。
    • 然后单击新建并使用您想要的任何名称打开一个新项目。
    • 现在我们将使用Java语言处理 Empty Activity。保留所有其他选项不变。
    • 您可以根据自己的选择更改项目名称。


    • 默认情况下,会有两个文件activity_main.xmlMainActivity。Java
  2. 第 2 步:在进入编码部分之前,您必须先做一些准备工作。
    • 转到app->res->values->colors.xml部分并为您的应用设置颜色。
      colors.xml
      
      
          #42C14B
          #3BC545
          #05af9b
        
          #fb7268
          #ededf2
        
      


      build.gradle (:app)
      // Volley library
      implementation 'com.android.volley:volley:1.1.1'


      AndroidManifests.xml
      
      


      actibity_main.xml
      
      
        
        
          
          
        
              
              
        
                  
                  
        
                  
                  
        
              
              
        
              
              
        
              
              
        
              
              
        
              
              
        
              
              
        
              
              
        
              
              
        
              
              
        
              
              
        
              
              
        
              
              
        
              
              
        
              
              
        
              
        
      


      MainActivity.java
      package com.example.covid_19tracker;
        
      import androidx.appcompat.app.AppCompatActivity;
        
      import android.os.Bundle;
      import android.widget.TextView;
      import android.widget.Toast;
        
      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.StringRequest;
      import com.android.volley.toolbox.Volley;
        
      import org.json.JSONException;
      import org.json.JSONObject;
        
      public class MainActivity
          extends AppCompatActivity {
        
          // Create the object of TextView
          TextView tvCases, tvRecovered,
              tvCritical, tvActive,
              tvTodayCases, tvTotalDeaths,
              tvTodayDeaths,
              tvAffectedCountries;
        
          @Override
          protected void onCreate(Bundle savedInstanceState)
          {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
        
              // Link those objects with their respective id's
              // that we have given in .XML file
              tvCases
                  = findViewById(R.id.tvCases);
              tvRecovered
                  = findViewById(R.id.tvRecovered);
              tvCritical
                  = findViewById(R.id.tvCritical);
              tvActive
                  = findViewById(R.id.tvActive);
              tvTodayCases
                  = findViewById(R.id.tvTodayCases);
              tvTotalDeaths
                  = findViewById(R.id.tvTotalDeaths);
              tvTodayDeaths
                  = findViewById(R.id.tvTodayDeaths);
              tvAffectedCountries
                  = findViewById(R.id.tvAffectedCountries);
        
              // Creating a method fetchdata()
              fetchdata();
          }
        
          private void fetchdata()
          {
        
              // Create a String request
              // using Volley Library
              String url = "https:// corona.lmao.ninja/v2/all";
        
              StringRequest request
                  = new StringRequest(
                      Request.Method.GET,
                      url,
                      new Response.Listener() {
                          @Override
                          public void onResponse(String response)
                          {
        
                              // Handle the JSON object and
                              // handle it inside try and catch
                              try {
        
                                  // Creating object of JSONObject
                                  JSONObject jsonObject
                                      = new JSONObject(
                                          response.toString());
        
                                  // Set the data in text view
                                  // which are available in JSON format
                                  // Note that the parameter inside
                                  // the getString() must match
                                  // with the name given in JSON format
                                  tvCases.setText(
                                      jsonObject.getString(
                                          "cases"));
                                  tvRecovered.setText(
                                      jsonObject.getString(
                                          "recovered"));
                                  tvCritical.setText(
                                      jsonObject.getString(
                                          "critical"));
                                  tvActive.setText(
                                      jsonObject.getString(
                                          "active"));
                                  tvTodayCases.setText(
                                      jsonObject.getString(
                                          "todayCases"));
                                  tvTotalDeaths.setText(
                                      jsonObject.getString(
                                          "deaths"));
                                  tvTodayDeaths.setText(
                                      jsonObject.getString(
                                          "todayDeaths"));
                                  tvAffectedCountries.setText(
                                      jsonObject.getString(
                                          "affectedCountries"));
                              }
                              catch (JSONException e) {
                                  e.printStackTrace();
                              }
                          }
                      },
                      new Response.ErrorListener() {
                          @Override
                          public void onErrorResponse(VolleyError error)
                          {
                              Toast.makeText(
                                       MainActivity.this,
                                       error.getMessage(),
                                       Toast.LENGTH_SHORT)
                                  .show();
                          }
                      });
        
              RequestQueue requestQueue
                  = Volley.newRequestQueue(this);
              requestQueue.add(request);
          }
      }


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

      build.gradle (:app)

      // Volley library
      implementation 'com.android.volley:volley:1.1.1'
      
    • 转到app->manifests->AndroidManifests.xml部分并允许“Internet Permission”。

      AndroidManifests.xml

      
      
      
  3. 步骤 3:设计 UI
    • 下面是xml文件的代码。

      活动主.xml

      
      
        
        
          
          
        
              
              
        
                  
                  
        
                  
                  
        
              
              
        
              
              
        
              
              
        
              
              
        
              
              
        
              
              
        
              
              
        
              
              
        
              
              
        
              
              
        
              
              
        
              
              
        
              
              
        
              
              
        
              
        
      
      
    • .xml 文件中使用此代码后,UI 将如下所示:

  4. 步骤 4:使用Java文件
    • 打开主活动类里面有Java文件,首先创建TextView类的对象。
    • 其次,在onCreate()方法中,我们必须将这些对象与我们在 .XML 文件中给出的各自 id 链接起来。
    • onCreate()方法之外创建一个private void fetchdata() onCreate()方法并定义它。
    • fetchdata()方法中,最重要的任务将发生,即我们如何从第三方 API 获取数据并在我们的应用程序中实现它。我的要求是请仔细阅读 Android 中的 Volley Library 和 REST API(介绍)两篇文章,以了解以下概念。
    • 使用 Volley 库创建一个字符串请求,并使用“ https://corona.lmao.ninja/v2/all ”链接分配“url”。
      // Create a String request using Volley Library
        
      String url = "https:// corona.lmao.ninja/v2/all";
        
      StringRequest request
          = new StringRequest(
              Request.Method.GET,
              url,
              new Response.Listener() {
                  @Override
                  public void onResponse(
                      String response)
                  {
                  }
              },
              new Response.ErrorListener() {
                  @Override
                  public void onErrorResponse(
                      VolleyError error)
                  {
                  }
              });
        
      RequestQueue requestQueue
          = Volley.newRequestQueue(this);
      requestQueue.add(request);
      
    • 请参阅此网站以查看请求的数据是否为 JSON 格式。

    • 所以接下来你要做的是,在onResponse()方法中创建“JSONObject”类的对象,然后在“jsonobject”的帮助下以JSON格式在文本视图中设置数据。确保您必须在“try”块中执行这些操作。请记住, getString()中的参数必须与以 JSON 格式给出的名称匹配。
      // Handle the JSON object and handle it inside try and catch
        
      try {
          // Creating object of JSONObject
          JSONObject jsonObject
              = new JSONObject(
                  response.toString());
        
          // Set the data in text view
          // which are available in JSON format
          // Note that the parameter
          // inside the getString() must match
          // with the name given in JSON format
          tvCases.setText(
              jsonObject.getString("cases"));
          tvRecovered.setText(
              jsonObject.getString("recovered"));
          tvCritical.setText(
              jsonObject.getString("critical"));
          tvActive.setText(
              jsonObject.getString("active"));
          tvTodayCases.setText(
              jsonObject.getString("todayCases"));
          tvTotalDeaths.setText(
              jsonObject.getString("deaths"));
          tvTodayDeaths.setText(
              jsonObject.getString("todayDeaths"));
          tvAffectedCountries.setText(
              jsonObject.getString("affectedCountries"));
      }
      catch (JSONException e) {
          e.printStackTrace();
      }
      
    • onErrorResponse()方法中,如果发生任何错误,您必须显示一条吐司消息。
      Toast.makeText(MainActivity.this, 
                     error.getMessage(), 
                     Toast.LENGTH_SHORT)
           .show();
      
    • 最后调用onCreate()方法中的fetchdata() onCreate()方法。

    下面是 MainActivity 的完整代码。 Java文件:

    主要活动。Java

    package com.example.covid_19tracker;
      
    import androidx.appcompat.app.AppCompatActivity;
      
    import android.os.Bundle;
    import android.widget.TextView;
    import android.widget.Toast;
      
    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.StringRequest;
    import com.android.volley.toolbox.Volley;
      
    import org.json.JSONException;
    import org.json.JSONObject;
      
    public class MainActivity
        extends AppCompatActivity {
      
        // Create the object of TextView
        TextView tvCases, tvRecovered,
            tvCritical, tvActive,
            tvTodayCases, tvTotalDeaths,
            tvTodayDeaths,
            tvAffectedCountries;
      
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
      
            // Link those objects with their respective id's
            // that we have given in .XML file
            tvCases
                = findViewById(R.id.tvCases);
            tvRecovered
                = findViewById(R.id.tvRecovered);
            tvCritical
                = findViewById(R.id.tvCritical);
            tvActive
                = findViewById(R.id.tvActive);
            tvTodayCases
                = findViewById(R.id.tvTodayCases);
            tvTotalDeaths
                = findViewById(R.id.tvTotalDeaths);
            tvTodayDeaths
                = findViewById(R.id.tvTodayDeaths);
            tvAffectedCountries
                = findViewById(R.id.tvAffectedCountries);
      
            // Creating a method fetchdata()
            fetchdata();
        }
      
        private void fetchdata()
        {
      
            // Create a String request
            // using Volley Library
            String url = "https:// corona.lmao.ninja/v2/all";
      
            StringRequest request
                = new StringRequest(
                    Request.Method.GET,
                    url,
                    new Response.Listener() {
                        @Override
                        public void onResponse(String response)
                        {
      
                            // Handle the JSON object and
                            // handle it inside try and catch
                            try {
      
                                // Creating object of JSONObject
                                JSONObject jsonObject
                                    = new JSONObject(
                                        response.toString());
      
                                // Set the data in text view
                                // which are available in JSON format
                                // Note that the parameter inside
                                // the getString() must match
                                // with the name given in JSON format
                                tvCases.setText(
                                    jsonObject.getString(
                                        "cases"));
                                tvRecovered.setText(
                                    jsonObject.getString(
                                        "recovered"));
                                tvCritical.setText(
                                    jsonObject.getString(
                                        "critical"));
                                tvActive.setText(
                                    jsonObject.getString(
                                        "active"));
                                tvTodayCases.setText(
                                    jsonObject.getString(
                                        "todayCases"));
                                tvTotalDeaths.setText(
                                    jsonObject.getString(
                                        "deaths"));
                                tvTodayDeaths.setText(
                                    jsonObject.getString(
                                        "todayDeaths"));
                                tvAffectedCountries.setText(
                                    jsonObject.getString(
                                        "affectedCountries"));
                            }
                            catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error)
                        {
                            Toast.makeText(
                                     MainActivity.this,
                                     error.getMessage(),
                                     Toast.LENGTH_SHORT)
                                .show();
                        }
                    });
      
            RequestQueue requestQueue
                = Volley.newRequestQueue(this);
            requestQueue.add(request);
        }
    }
    

输出:

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