Search code examples
javaandroidapinullpointerexceptionretrofit2

My app crushed for a java.lang.NullPointerException


I'm trying to develop an android app with my api and retrofit 2 but unfortunaly my app crush many time, and I got a message like this, java.lang.RuntimeException: Unable to start activity ComponentInfo{com.apitest.firsttry/com.apitest.firsttry.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'retrofit2.Call com.apitest.firsttry.api.ApiInterface.getAllData()' on a null object reference and Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'retrofit2.Call com.apitest.firsttry.api.ApiInterface.getAllData()' on a null object reference here is code of ApiInterface.java


import com.apitest.firsttry.Models.DataModels;
import com.apitest.firsttry.Response.GetDataResponse;

import retrofit2.Call;
import retrofit2.http.GET;

public interface ApiInterface {
    @GET("fetchdata.php")
    Call<GetDataResponse> getAllData();

}

and here is code of ApiClient.java

package com.apitest.firsttry.api;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiClient {
    public static Retrofit RETROFIT=null;

    public static Retrofit getClient(){

        if (RETROFIT==null) {

            OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
            Gson gson = new GsonBuilder().create();

            RETROFIT = new Retrofit.Builder().baseUrl("https://wight-baths.000webhostapp.com/").client(okHttpClient).addConverterFactory(GsonConverterFactory.create(gson)).build();
        }
        return RETROFIT;
    
    }

}

And this is code of MainActivity

package com.apitest.firsttry;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.apitest.firsttry.Adapter.DataAdapter;
import com.apitest.firsttry.Models.DataModels;
import com.apitest.firsttry.Response.GetDataResponse;
import com.apitest.firsttry.api.ApiClient;
import com.apitest.firsttry.api.ApiInterface;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
DataAdapter dataAdapter;
ApiInterface apiInterface;



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

    }
    private void initializing(){
        recyclerView=findViewById(R.id.recycler_view);
        Retrofit retrofit= ApiClient.getClient();
        apiInterface=retrofit.create(ApiInterface.class);
    }
    private void setDataAdapter(List<DataModels>dataModels){
        dataAdapter=new DataAdapter(this, dataModels);
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this);

        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(dataAdapter);
    }
    private void getdata(){
        apiInterface.getAllData().enqueue(new Callback<GetDataResponse>() {
            @Override
            public void onResponse(Call<GetDataResponse> call, Response<GetDataResponse> response) {
                try {
                    if (response!=null){
                        if (response.body().getStatus().equals("1")){

                            setDataAdapter(response.body().getData());

                        }else {
                            Toast.makeText(MainActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                        }

                    }

                }catch (Exception e){
                    Log.e("exp",e.getLocalizedMessage());
                }

            }

            @Override
            public void onFailure(Call<GetDataResponse> call, Throwable t) {
                Log.e("failer",t.getLocalizedMessage());

            }
        });

    }
}

How to fix it?


Solution

  •     @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        getdata();
        initializing();
    
        }
    

    Call initializing() before calling getdata(). You set up apiInterface in initializing() and cannot use it before initializing() returns.