Click here to Skip to main content
14,971,742 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I'm having a problem with my networking classes on my weather app. Whenever I run the app, it displays the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'com.tex.lightweatherforecast.Retrofit.Main com.tex.lightweatherforecast.Retrofit.Example.getMain()' on a null object reference
        at com.tex.lightweatherforecast.FirstFragment$1.onResponse(
        at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1.lambda$onResponse$0$DefaultCallAdapterFactory$ExecutorCallbackCall$1(
        at retrofit2.-$$Lambda$DefaultCallAdapterFactory$ExecutorCallbackCall$1$ Source:6)
        at android.os.Handler.handleCallback(
        at android.os.Handler.dispatchMessage(
        at android.os.Looper.loop(
        at java.lang.reflect.Method.invoke(Native Method)

Meaning one of my classes is returning null, I have no idea why this happens because I have checked the whole classes to find where the fault is but to no avail. These are the classes involved:
public interface ApiInterface {

    Call<Example> getWeatherData(@Query("q") String name);
public class ApiClient {

    private static Retrofit retrofit = null;

    public static  Retrofit getClient(){ //creating object

        if (retrofit == null) {

            Gson gson = new GsonBuilder()
                    .registerTypeAdapter(PrettyTime.class, new PrettyTimeDeserializer())

            retrofit = new Retrofit.Builder()

        return retrofit;

public class Example {

    private Main main;
    private List<Weather> weatherList;
    private Visibility visibility;
    private Wind wind;
    private Clouds clouds;
    private Dt dt;
    private Sys sys;
    private Name name;

    public Main getMain() {
        return main;

    public void setMain(Main main) {
        this.main = main;

    public List<Weather> getWeatherList() {
        return weatherList;

    public void setWeatherList(List<Weather> weatherList) {
        this.weatherList = weatherList;

    public Visibility getVisibility() {
        return visibility;

    public void setVisibility(Visibility visibility) {
        this.visibility = visibility;

    public Wind getWind() {
        return wind;

    public void setWind(Wind wind) {
        this.wind = wind;

    public Clouds getClouds() {
        return clouds;

    public void setClouds(Clouds clouds) {
        this.clouds = clouds;

    public Dt getDt() {
        return dt;

    public void setDt(Dt dt) {
        this.dt = dt;

    public Sys getSys() {
        return sys;

    public void setSys(Sys sys) {
        this.sys = sys;

    public Name getName() {
        return name;

    public void setName(Name name) { = name;
public class Main {

    String temp;

    String pressure;

    String humidity;

    public String getTemp() {
        return temp;

    public void setTemp(String temp) {
        this.temp = temp;
    public String getPressure() {
        return pressure;

    public void setPressure(String pressure) {
        this.pressure = pressure;

    public String getHumidity() {
        return humidity;

    public void setHumidity(String humidity) {
        this.humidity = humidity;

public class FirstFragment extends Fragment {
    // User current time, current temperature, current condition, sunrise, sunset, temperature, pressure, humidity, wind_speed, visibility, clouds
    TextView current_temp, current_output, rise_time, set_time, temp_out, Press_out, Humid_out, Ws_out, Visi_out, Cloud_out;
    // TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public FirstFragment() {
        // Required empty public constructor

     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SecondFragment.
// TODO: Rename and change types and number of parameters
    public static FirstFragment newInstance(String param1, String param2) {
        FirstFragment fragment = new FirstFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        return fragment;

    public void onCreate(Bundle savedInstanceState) {
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);


    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_first, container, false);
        current_temp = rootView.findViewById(;
        current_output = rootView.findViewById(;
        rise_time = rootView.findViewById(;
        set_time = rootView.findViewById(;
        temp_out = rootView.findViewById(;
        Press_out = rootView.findViewById(;
        Humid_out = rootView.findViewById(;
        Ws_out = rootView.findViewById(;
        Visi_out = rootView.findViewById(;
        Cloud_out = rootView.findViewById(;

        FragmentActivity fa = getActivity();
        assert fa != null;
        EditText textfield = fa.findViewById(;
        return rootView;

    private void getWeatherData(String name) {

        ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);

        Call<Example> call = apiInterface.getWeatherData(name);

        call.enqueue(new Callback<Example>() {
            public void onResponse(@NotNull Call<Example> call, @NotNull Response<Example> response) {

                assert response.body() !=null;
                current_temp.setText(response.body().getMain().getTemp() + " ℃");
                rise_time.setText(response.body().getSys().getSunrise() + " ");
                set_time.setText(response.body().getSys().getSunset() + " ");
                temp_out.setText(response.body().getMain().getTemp() + " ℃");
                Press_out.setText(response.body().getMain().getPressure() + " hpa");
                Humid_out.setText(response.body().getMain().getHumidity() + " %");
                Ws_out.setText(response.body().getWind().getSpeed() + " Km/h");
                Visi_out.setText(response.body().getVisibility() + " m");
                Cloud_out.setText(response.body().getClouds().getAll()+ " %");

            public void onFailure(@NotNull Call<Example> call, @NotNull Throwable t) {

What I have tried:

I have checked the whole class to find what is causing null but haven't seen it. I as well tried to parse my example and main classes well, but it still displays the error.
Updated 25-Apr-21 7:26am
David Crow 25-Apr-21 21:09pm
The problem is with line 107 of Did you look there? You are calling the getMain() method from a null object, most likely body().
Chinedum Ezeozue 26-Apr-21 1:46am
Sure, but I had no idea how to fix it
David Crow 26-Apr-21 7:55am
How about checking to see that an object is not null before using it?

1 solution

This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.

Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterday's shirt when you took it off last night.

We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!

Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and Visual Studio will help you here. Run your program in the debugger and when it fails, VS will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, VS will stop before the error, and let you examine what is going on by stepping through the code looking at your values.

But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!
Chinedum Ezeozue 25-Apr-21 17:00pm
This didn't fix my problem
OriginalGriff 25-Apr-21 17:33pm
It does fix your problem: it just doesn't give you a "do this, that'll fix it" solution.
The problem is that something isn't there that you expected to be: so step one is to find out exactly what.
Step to is to look back through the code - again using the debugger - to find out why it is missing.

And that needs your code running with your data: and we do not have that, so it's down to you to do it.

Sorry, but we can't tell you "change this line" because it's probably in something several miles away from where the error actually shows up!
Chinedum Ezeozue 25-Apr-21 17:34pm
Ok, thanks
OriginalGriff 26-Apr-21 1:46am
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900