0

I tried to make a covid-19 tracking app by watching Youtube tutorials.

My app shows the country list with flags and when you click on any country it opens an activity and shows the details of that country i.e total cases, deaths, recovered, etc. The video on Youtube uses ListView and I am using recyclerView

I fetched the country list successfully and set onClickListener on the view and it opens second activity which shows the case in detail. But I don't know how to show the data.

my adapter class:

class Countries_adapter extends RecyclerView.Adapter<Countries_adapter.MyViewHolder> {


    Context ct;
    List<Countries_data> list;

    public Countries_adapter(Context context,List<Countries_data> country)
    {
        ct=context;
        list=country;
    }


    @Override
    public MyViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(ct).inflate(R.layout.countries_row,parent,false);
        return new MyViewHolder(v);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, final int position) {

        holder.tvCountryName.setText(list.get(position).getCountry());
        holder.tvtotal.setText(list.get(position).getActive());
        Glide.with(ct).load(list.get(position).getFlag()).into(holder.imageView);

        holder.linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(ct,CountriesDetails.class);
                i.putExtra("Country",list.get(position).getCountry());
                ct.startActivity(i);
            }
        });


    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        TextView tvCountryName,tvtotal;
        ImageView imageView;
        LinearLayout linearLayout;
        public MyViewHolder( View itemView) {
            super(itemView);

            tvCountryName = itemView.findViewById(R.id.tvCountryName);
            tvtotal=itemView.findViewById(R.id.tvCountrytotalcaese);
            imageView = itemView.findViewById(R.id.imageFlag);
            linearLayout=itemView.findViewById(R.id.linear_layout);

        }
    }

my AffectedCoutries class activity is as follows:

    public class AffectedCountries extends AppCompatActivity {
    
        EditText edtSearch;
       RecyclerView recyclerView;
        SimpleArcLoader simpleArcLoader;
        public static ArrayList countryList = new ArrayList<>();
        Countries_data countryData;
        Countries_adapter  CountriesAdapter;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_affected_countries);
    
            edtSearch = findViewById(R.id.edtSearch);
            recyclerView=findViewById(R.id.recyclerAffectedCountries);
            simpleArcLoader = findViewById(R.id.loader);
    
          fetchData();
        }
        private void fetchData() {
    
            String url  = "https://corona.lmao.ninja/v2/countries/";
    
            simpleArcLoader.start();
    
            StringRequest request = new StringRequest(Request.Method.GET, url,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
    
                            try {
    
                                JSONArray jsonArray = new JSONArray(response);
    
                                for(int i=0;i<jsonArray.length();i++){
    
                                    JSONObject jsonObject = jsonArray.getJSONObject(i);
    
                                    String countryName = jsonObject.getString("country");
                                    String cases = jsonObject.getString("cases");
                                    String todayCases = jsonObject.getString("todayCases");
                                    String deaths = jsonObject.getString("deaths");
                                    String todayDeaths = jsonObject.getString("todayDeaths");
                                    String recovered = jsonObject.getString("recovered");
                                    String active = jsonObject.getString("active");
                                    String critical = jsonObject.getString("critical");
    
                                    JSONObject object = jsonObject.getJSONObject("countryInfo");
                                    String flagUrl = object.getString("flag");
    
                                    countryData = new Countries_data(flagUrl,countryName,cases,todayCases,deaths,todayDeaths,recovered,active,critical);
                                    countryList.add(countryData);
                                }
    
                               CountriesAdapter = new Countries_adapter(AffectedCountries.this,countryList);
                                recyclerView.setLayoutManager(new LinearLayoutManager(AffectedCountries.this));
                                recyclerView.setAdapter(CountriesAdapter);
                                simpleArcLoader.stop();
                                simpleArcLoader.setVisibility(View.GONE);
    
    
                            } catch (JSONException e) {
                                e.printStackTrace();
                                simpleArcLoader.start();
                                simpleArcLoader.setVisibility(View.GONE);
                                Toast.makeText(AffectedCountries.this,"catch response", Toast.LENGTH_SHORT).show();
                            }
    
    
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    simpleArcLoader.stop();
                    simpleArcLoader.setVisibility(View.GONE);
                    Toast.makeText(AffectedCountries.this,"error response", Toast.LENGTH_SHORT).show();
                }
            });
    
            RequestQueue requestQueue = Volley.newRequestQueue(this);
            requestQueue.add(request);

    }
}

my Countries_data class(model class)

public class Countries_data {
    public String country;
    public String cases;
    public String todayCases;
    public String deaths;
    public String todayDeaths;
    public String recovered;
    public String active;
    public String critical;
    public String flag;
    
    public Countries_data(String flag, String country, String cases, String 
           todayCases, String deaths, String todayDeaths, String recovered, 
          String active, String critical) {
       

        this.country = country;
        this.cases = cases;
        this.todayCases = todayCases;
        this.deaths = deaths;
        this.todayDeaths = todayDeaths;
        this.recovered = recovered;
        this.active = active;
        this.critical = critical;
        this.flag = flag;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getCases() {
        return cases;
    }

    public void setCases(String cases) {
        this.cases = cases;
    }

    public String getTodayCases() {
        return todayCases;
    }

    public void setTodayCases(String todayCases) {
        this.todayCases = todayCases;
    }

    public String getDeaths() {
        return deaths;
    }

    public void setDeaths(String deaths) {
        this.deaths = deaths;
    }

    public String getTodayDeaths() {
        return todayDeaths;
    }

    public void setTodayDeaths(String todayDeaths) {
        this.todayDeaths = todayDeaths;
    }

    public String getRecovered() {
        return recovered;
    }

    public void setRecovered(String recovered) {
        this.recovered = recovered;
    }

    public String getActive() {
        return active;
    }

    public void setActive(String active) {
        this.active = active;
    }

    public String getCritical() {
        return critical;
    }

    public void setCritical(String critical) {
        this.critical = critical;
    }

    public String getFlag() {
        return flag;
    }

    public void setFlag(String flag) {
        this.flag = flag;
    }
}

my Country_details class

public class CountriesDetails extends AppCompatActivity {

    TextView tvCountry, tvCases, tvRecovered,tvdeaths;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_countries_details2);

        tvCountry = findViewById(R.id.tvCountry);
        tvCases = findViewById(R.id.tvCases);
        tvRecovered = findViewById(R.id.tvRecovered);
        tvdeaths=findViewById(R.id.tvTotalDeaths);

        String positionCountry = getIntent().getStringExtra("Country");
        Log.i("country name", positionCountry);

    }
}


    

How to set the data in tvcases?

How can I show the data? Do I have to create a separate recycler view and then fetch the data from the API or can I use my main activity to show the data?

Abhishek
  • 36
  • 6
  • show more code and exception stacktrace from logcat especially – snachmsm Sep 15 '20 at 12:31
  • Specifically, what do you mean by "I try to set text like this but it gives an error in getCountry() (contains the name of the country);" What error? NullPointerException? If so, is the TextView null? The countryModelsList? – drdaanger Sep 15 '20 at 13:01
  • @drdaanger tvCountry.setText(AffectedCountries.countryModelsList.get(positionCountry).getCountry()); it gives error in getCountry() it says cannot resolves method getCases() into object – Abhishek Sep 15 '20 at 13:02
  • @Abhishek Okay. This is a build-time exception then? If that's the case, then make sure that your `Countries_data` class has a public getCases method that returns a String or CharSequence. – drdaanger Sep 15 '20 at 13:06
  • @drdaanger sir its public – Abhishek Sep 15 '20 at 13:11

1 Answers1

0

I have some sad information for you: Google Play policy restricts such apps from being published in store... especially when you are showing deaths count. Been there, done that, my app was blocked...

besides above:

you are passing country name in intent:

i.putExtra("Country",list.get(position).getCountry());

but trying to read "position" in details Activity - it will be always 0 (default)

edit due to comments:

pass position of clicked View

holder.linearLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent i = new Intent(ct,CountriesDetails.class);
            i.putExtra("position", position);
            ct.startActivity(i);
        }
    });

in CountriesDetailss onCreate method receive this position and restore proper Countries_data object from your static countryList array in AffectedCountries

int position = getIntent().getIntExtra("position", 0);
Countries_data country = AffectedCountries.countryList.get(position);
tvCountry.setText(country.getCountry());

that should work, but this isn't best way to store data, in fact its very weak... after downloading data (list of countries) you should store it somehow, e.g. SQLite/Room lib or at least SharedPreferences... then in details activity you should restore int position and using it take proper object from database or preferences, instead of stright from static array

it may be also useful to implement Parcelable inteface to your Countries_data - this will allow to put whole Countries_data object into Intents extras, not only primitive int with position in array. in this case details activity won't even need access to whole array or sql database/preferences, it will get whole object straight from Intents extras

snachmsm
  • 17,866
  • 3
  • 32
  • 74
  • i accidentally did that. but when i try to set the text like `tvCountry.setText(AffectedCountries.countryModelsList.get(positionCountry).getCountry());` it gives error in getCountry() it says cannot resolves method getCases() into object – Abhishek Sep 15 '20 at 12:54
  • 1
    again: show more code of both `Activites` and full exception stacktrace (edit question, put in there) – snachmsm Sep 15 '20 at 13:08
  • why have you posted adapters code if it is working well? what is `AffectedCountries`? `it shows error in getCases();` - what error it shows? put whole [stacktrace](https://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors) what is returning `getCountry()` method? you are trying to read this value on the other side as `int` (`getIntExtra` method), I bet this is `String`... – snachmsm Sep 15 '20 at 13:35
  • AffectedCountries is my main activity class and i use `getIntExtra method becuase it passes in adapter list position in adapter class – Abhishek Sep 15 '20 at 14:10
  • sorry, I can't help you. you didn't described problem properly, didn't posted full or at least relevant pieces of code. besides that: you are not passing `position` to receive by `getIntExtra`, you are passing `getCountry()`, which no one knows what is, because you didn't posted `Countries_data`... – snachmsm Sep 15 '20 at 14:24
  • sir can you please provide me you email so i can send you my project zip file. sir i want to know how can i show the data in countries_details class. i create the affected_countries class that shows the list of countries. and i correct the intent it passes the name of the countries – Abhishek Sep 15 '20 at 14:54
  • edit your question and post WHOLE `AffectedCoutries`, `CountriesDetails` and `Countries_data` code (without imports on top). you may also remove adapters code, leave only part with `onClick` listener, in which you are starting `CountriesDetails`. without these sources it's impossible to help you... – snachmsm Sep 15 '20 at 15:46
  • sir please check – Abhishek Sep 15 '20 at 17:08
  • thank you sir that solve my problem.i am new to android and i m learning recycler view and after that i learn storage . sir can you suggest me any source where i can learn recycler view with api and storage as every blog and youtube channel use their own approch so its a bit confusing and difficult to learn. – Abhishek Sep 15 '20 at 18:21
  • I would go with [offcial training site](https://developer.android.com/courses) at first, personally I like [vogella tutorials site](https://www.vogella.com/tutorials/android.html), but there is a plenty valuable blogs and sites as you noticed. yes, they are using different aproaches and solutions, but this is how coding works - you may oftenly achieve your goal with different ways, more or less suitable for specific case, but only practical coding and experience will suggest you most proper solutions :) try some courses/tutorials on sites montioned above and make some practise, good luck! – snachmsm Sep 15 '20 at 21:09
  • PS. If you have just started your journey with Android then I strongly recomend to learn Kotlin instead of Java. you should be familiar with both, but Kotlin seems to be future of Android and not only – snachmsm Sep 15 '20 at 21:13