0

I am new to android studio and I have been trying to implement a recycler view and a pie chart fetching data from an API on to my app use search bar onto my app did it in a way and it worked but as l was adding more function to the application it started crushing with the above error

Logcat (Errors):
2022-06-28 10:21:02.158 9803-9803/com.example.covid19app E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.covid19app, PID: 9803
    java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object[] java.util.Collection.toArray()' on a null object reference
        at java.util.ArrayList.<init>(ArrayList.java:191)
        at com.example.covid19app.MainActivity$1.onResponse(MainActivity.java:83)
        at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1.lambda$onResponse$0$DefaultCallAdapterFactory$ExecutorCallbackCall$1(DefaultCallAdapterFactory.java:89)
        at retrofit2.-$$Lambda$DefaultCallAdapterFactory$ExecutorCallbackCall$1$hVGjmafRi6VitDIrPNdoFizVAdk.run(Unknown Source:6)
        at android.os.Handler.handleCallback(Handler.java:888)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:213)
        at android.app.ActivityThread.main(ActivityThread.java:8178)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
2022-06-28 10:21:02.179 9803-9803/com.example.covid19app I/Process: Sending signal. PID: 9803 SIG: 9

My code (Adapter.java):

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.hbb20.CountryCodePicker;

import org.eazegraph.lib.charts.PieChart;
import org.eazegraph.lib.models.PieModel;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    CountryCodePicker countryCodePicker;
    TextView mtodaytotal,mtotal,mactive,mtodayactive,mrecovered,mtodayrecovered,mdeaths,mtodaydeaths;

    String country;
    TextView mfilter;
    Spinner spinner;
    String[] types={"cases","deaths","recovered","active"};
    private List<ModelClass> modelClassList;
    private List<ModelClass> modelClassList2;
    PieChart mpiechart;
    private RecyclerView recyclerView;
    com.example.covid19app.Adapter adapter;

    //Initialize
    DrawerLayout drawerLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getSupportActionBar().hide();

        countryCodePicker=findViewById(R.id.ccp);
        mtodayactive=findViewById(R.id.todayactive);
        mactive=findViewById(R.id.activecase);
        mdeaths=findViewById(R.id.todaydeaths);
        mtodaydeaths=findViewById(R.id.totaldeaths);
        mrecovered=findViewById(R.id.recoveredcases);
        mtodayrecovered=findViewById(R.id.todayrecovered);
        mtotal=findViewById(R.id.totalcase);
        mtodaytotal=findViewById(R.id.todaytotal);
        mpiechart=findViewById(R.id.piechart);
        spinner=findViewById(R.id.spinner);
        mfilter=findViewById(R.id.filter);
        recyclerView=findViewById(R.id.recyclerview);
        modelClassList=new ArrayList<>();
        modelClassList2=new ArrayList<>();

        spinner.setOnItemSelectedListener(this);
        ArrayAdapter arrayAdapter=new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item,types);
        arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        spinner.setAdapter(arrayAdapter);

        ApiUtilities.getAPIInterface().getcountrydata().enqueue(new Callback<List<ModelClass>>() {
            @Override
            public void onResponse(Call<List<ModelClass>> call, Response<List<ModelClass>> response) {
                modelClassList2.addAll(response.body());
               //adapter.notify();
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(Call<List<ModelClass>> call, Throwable t) {

            }
        });

        adapter=new Adapter(getApplicationContext(),modelClassList2);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);

        countryCodePicker.setAutoDetectedCountry(true);
        country=countryCodePicker.getSelectedCountryName();

        countryCodePicker.setOnCountryChangeListener(new CountryCodePicker.OnCountryChangeListener() {
            @Override
            public void onCountrySelected() {
                country=countryCodePicker.getSelectedCountryName();
                fetchdata();
            }
        });

        fetchdata();

        //Assign variable
        drawerLayout = findViewById(R.id.drawer_layout);
    }

    private void fetchdata() {
        ApiUtilities.getAPIInterface().getcountrydata().enqueue(new Callback<List<ModelClass>>() {
            @Override
            public void onResponse(Call<List<ModelClass>> call, Response<List<ModelClass>> response) {
              // modelClassList.addAll(response.body());
               for (int i=0; i<modelClassList.size(); i++)
               {
                   if (modelClassList.get(i).getCountry().equals(country))
                   {
                       mactive.setText((modelClassList.get(i).getActive()));
                       mtodaydeaths.setText((modelClassList.get(i).getTodayDeaths()));
                       mtodayrecovered.setText((modelClassList.get(i).getTodayRecovered()));
                       mtodaytotal.setText((modelClassList.get(i).getTodayCases()));
                       mtotal.setText((modelClassList.get(i).getCases()));
                       mdeaths.setText((modelClassList.get(i).getDeaths()));
                       mrecovered.setText((modelClassList.get(i).getRecovered()));

                       int active,total,recovered,deaths;

                       active=Integer.parseInt(modelClassList.get(i).getActive());
                       total=Integer.parseInt(modelClassList.get(i).getCases());
                       recovered=Integer.parseInt(modelClassList.get(i).getRecovered());
                       deaths=Integer.parseInt(modelClassList.get(i).getDeaths());

                       updateGraph(active,total,recovered,deaths);

                       }
               }
            }

            @Override
            public void onFailure(Call<List<ModelClass>> call, Throwable t) {

            }
        });

    }

    private void updateGraph(int active, int total, int recovered, int deaths) {

        mpiechart.clearChart();
        mpiechart.addPieSlice(new PieModel("Confirm",total,Color.parseColor("#FFB701")));
        mpiechart.addPieSlice(new PieModel("Active",active,Color.parseColor("#FF4caf50")));
        mpiechart.addPieSlice(new PieModel("Recovered",recovered,Color.parseColor("#38ACCD")));
        mpiechart.addPieSlice(new PieModel("Deaths",deaths,Color.parseColor("#F55c47")));
        mpiechart.startAnimation();
    }
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • What's the response from api ? – Manohar Jun 28 '22 at 09:40
  • nothing the application instantly crushes when l open it pointing at this line of code "modelClassList2.addAll(response.body());" please if there is any ways l can get around this help me – cuthbert Jun 28 '22 at 11:11
  • 1
    According to the stack trace, you are passing a `null` collection to a `new ArrayList<>(…)` at the affected `onResponse` method. Doesn’t match the code you’ve posted. – Holger Jun 28 '22 at 13:40

0 Answers0