package com.gfg.covid_java;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
private TextView tvCases, tvRecovered, tvCritical, tvActive,
private TextView tvTodayCases, tvTotalDeaths, tvTodayDeaths, tvAffectedCountries;
private RequestQueue queue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// API with Covid Data
String url="https://disease.sh/v3/covid-19/all";
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);
queue = Volley.newRequestQueue(this);
// Creating JSON Object Request from URL
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
//Responsible for Reading data in JSON format
@Override
public void onResponse(JSONObject response) {
try{
//Updating the data in the Layout elements
tvCases.setText(String.format("%,d", response.getInt("cases")));
tvRecovered.setText(String.format("%,d", response.getInt("recovered")));
tvCritical.setText(String.format("%,d", response.getInt("critical")));
tvActive.setText(String.format("%,d", response.getInt("active")));
tvTodayCases.setText(String.format("%,d", response.getInt("todayCases")));
tvTotalDeaths.setText(String.format("%,d", response.getInt("deaths")));
tvTodayDeaths.setText(String.format("%,d", response.getInt("todayDeaths")));
tvAffectedCountries.setText(String.format("%,d", response.getInt("affectedCountries")));
}
catch (JSONException e){
e.printStackTrace();
// Making Toast if error occurs
Toast.makeText(MainActivity.this, "Error fetching data", Toast.LENGTH_SHORT).show();
}
}
}, error -> {
// Handle error
Log.e("COVID_DATA", "Error fetching data", error);
// Making Toast if error occurs
Toast.makeText(MainActivity.this, "Network error. Please check your connection.",
Toast.LENGTH_SHORT).show();
});
// Add the request to the RequestQueue.
queue.add(req);
}
@Override
protected void onStop() {
super.onStop();
// Cancel any pending requests when the activity stops
if (queue != null) {
queue.cancelAll(this);
}
}
}