Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setVisibility(int)'

Hello,

I was following along with the videos, however, I keep getting a fatal exception. Any help you can give would be absolutely fantastic!

This is a copy of the terminal output:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.jeremy.simpleweatherapp, PID: 11045
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jeremy.simpleweatherapp/com.example.jeremy.simpleweatherapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setVisibility(int)' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6077)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setVisibility(int)' on a null object reference
                      at com.example.jeremy.simpleweatherapp.MainActivity.onCreate(MainActivity.java:50)
                      at android.app.Activity.performCreate(Activity.java:6664)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
                      at android.app.ActivityThread.-wrap12(ActivityThread.java) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
                      at android.os.Handler.dispatchMessage(Handler.java:102) 
                      at android.os.Looper.loop(Looper.java:154) 
                      at android.app.ActivityThread.main(ActivityThread.java:6077) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 

This is my MainActivity.java:

package com.example.jeremy.simpleweatherapp;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    public static final String TAG = MainActivity.class.getSimpleName();
    private CurrentWeather mCurrentWeather;

    @BindView(R.id.timeLabel) TextView mTimeLabel;
    @BindView(R.id.temperatureLabel) TextView mTemperatureLabel;
    @BindView(R.id.humidityValue) TextView mHumidityValue;
    @BindView(R.id.precipValue) TextView mPrecipValue;
    @BindView(R.id.summaryLabel) TextView mSummaryLabel;
    @BindView(R.id.iconImageView) ImageView mIconImageView;
    @BindView(R.id.refreshImageView) ImageView mRefreshImageView;
    @BindView(R.id.progressBar) ProgressBar mProgressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this); // method that binds this activity?

        mProgressBar.setVisibility(View.INVISIBLE);

        final double latitude = 37.8267;
        final double longitude = -122.4233;

        mRefreshImageView.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                getForecast(latitude, longitude);
            }
        });

        getForecast(latitude, longitude);
        Log.d(TAG, "Main UI code is running.");
    }

    private void getForecast(double latitude, double longitude) {
        String apiKey = "3bf16c26506fd5b5a3f79dfe42fb0fcc";
        // Currently this lat-long is L.A., CA

        String forecastURL = "https://api.darksky.net/forecast/" + apiKey + "/" + latitude + "," + longitude;

        if(isNetworkAvailable()) {
            toggleRefresh();

            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(forecastURL)
                    .build();

            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            toggleRefresh();
                        }
                    });
                    alertUserAboutError();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            toggleRefresh();
                        }
                    });

                    try {
                        String jsonData = response.body().string();
                        Log.v(TAG, jsonData);
                        Log.d(TAG, "String jsonData.");
                        if (response.isSuccessful()) {
                            mCurrentWeather = getCurrentDetails(jsonData);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    updateDisplay();
                                    Log.d(TAG, "Update display.");
                                }
                            });
                        } else {
                            alertUserAboutError();
                        }

                    } catch (IOException e) {
                        Log.e(TAG, "Exception caught: ", e);
                    } catch (JSONException e) {
                        Log.e(TAG, "Exception caught: ", e);
                    }
                }
            });

        } else {
            Toast.makeText(this, R.string.network_unavailable_message, Toast.LENGTH_LONG).show();
        }
    }

    private void toggleRefresh() {
        if (mProgressBar.getVisibility() == View.INVISIBLE) {
            mProgressBar.setVisibility(View.VISIBLE);
            mRefreshImageView.setVisibility(View.INVISIBLE);
        } else {
            mProgressBar.setVisibility(View.INVISIBLE);
            mRefreshImageView.setVisibility(View.VISIBLE);
        }
    }

    private void updateDisplay() {
        mTemperatureLabel.setText(mCurrentWeather.getTemperature()+"");
        mTimeLabel.setText("At " + mCurrentWeather.getFormattedTime() + " it will be ");
        mHumidityValue.setText(mCurrentWeather.getHumidity() + "");
        Log.d(TAG, "UI Humidity.");
        mPrecipValue.setText(mCurrentWeather.getPrecipChance() + " %");
        mSummaryLabel.setText(mCurrentWeather.getSummary());

        // Drawable drawable = ResourcesCompat.getDrawable(getResources(), mCurrentWeather.getIconId(), null);
        Drawable drawable = ContextCompat.getDrawable(this, mCurrentWeather.getIconId());
        mIconImageView.setImageDrawable(drawable);
    }

    private CurrentWeather getCurrentDetails(String jsonData) throws JSONException {
        JSONObject forecast = new JSONObject(jsonData);
        String timezone = forecast.getString("timezone");
        Log.i(TAG, "From JSON: " + timezone);

        JSONObject currently = forecast.getJSONObject("currently");

        CurrentWeather currentWeather = new CurrentWeather();
        currentWeather.setHumidity(currently.getDouble("humidity"));
        currentWeather.setTime(currently.getLong("time"));
        currentWeather.setIcon(currently.getString("icon"));
        currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
        currentWeather.setSummary(currently.getString("summary"));
        currentWeather.setTemperature(currently.getDouble("temperature"));
        currentWeather.setTimeZone(timezone);

        Log.d(TAG, currentWeather.getFormattedTime());

        return currentWeather;
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager manager = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        boolean isAvailable = false;
        if (networkInfo != null && networkInfo.isConnected()) {
            isAvailable = true;
        }
        return isAvailable;
    }

    private void alertUserAboutError() {
        AlertDialogFragment dialog = new AlertDialogFragment();
        dialog.show(getFragmentManager(), "error_dialog");
    }


}

And this is my activity_main.xml file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.jeremy.simpleweatherapp.MainActivity"
    android:background="#fffc970b"
    >

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/degree"
        android:id="@+id/degreeImageView"
        android:layout_alignTop="@+id/temperatureLabel"
        android:layout_toRightOf="@+id/temperatureLabel"
        android:layout_toEndOf="@+id/temperatureLabel"
        android:layout_marginRight="30dp"
        android:layout_marginTop="10dp"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="--"
        android:id="@+id/temperatureLabel"
        android:textSize="150sp"
        android:textAlignment="center"
        android:textColor="#ffffffff"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="..."
        android:ems="10"
        android:id="@+id/timeLabel"
        android:textColor="#80ffffff"
        android:textSize="18sp"
        android:layout_above="@+id/temperatureLabel"
        android:layout_centerHorizontal="true"
        android:textAlignment="center"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Alcatraz Island, CA"
        android:id="@+id/locationLabel"
        android:textColor="#ffffffff"
        android:textAlignment="center"
        android:textSize="24sp"
        android:layout_above="@+id/timeLabel"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="40dp"/>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/cloudy_night"
        android:id="@+id/iconImageView"
        android:background="#fffc970b"
        android:layout_alignBottom="@+id/locationLabel"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"/>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/temperatureLabel"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:weightSum="100"
        android:id="@+id/table">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="50">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="HUMIDITY"
                android:ems="10"
                android:id="@+id/humidityLabel"
                android:textColor="#80ffffff"
                android:gravity="center_horizontal"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="-"
                android:ems="10"
                android:id="@+id/humidityValue"
                android:layout_below="@+id/humidityLabel"
                android:textSize="24sp"
                android:textAlignment="center"
                android:textColor="#ffffffff"
                android:gravity="left"/>

        </LinearLayout>

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="50">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Rain/Snow"
                android:id="@+id/precipLabel"
                android:textColor="#80ffffff"
                android:gravity="center_horizontal"/>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="-"
                android:ems="10"
                android:id="@+id/precipValue"
                android:layout_below="@+id/precipLabel"
                android:textColor="#ffffffff"
                android:textSize="24sp"
                android:gravity="center_horizontal"/>

        </LinearLayout>

    </LinearLayout>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:id="@+id/summaryLabel"
        android:textColor="#ffffffff"
        android:text="Retrieving current weather..."
        android:gravity="center_horizontal"
        android:textSize="18sp"
        android:layout_below="@+id/table"
        android:layout_marginTop="40dp"/>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/refresh"
        android:id="@+id/refreshImageView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"/>

    <ProgressBar

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/refreshImageView"
        android:layout_centerHorizontal="true"
        android:id="@+id/progressBar"/>

</RelativeLayout>

<!-- style="?android:attr/progressBarStyle" -->

2 Answers

Took me a little while to find, but I ended up commenting out the progressBar and refreshImageView items, but to no avail. It seemed that every time Butterknife was called, it would have a null pointer issue.

It turns out I was missing a dependency in build.gradle (Module: app). It was

annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'

Which is a requirement for Butterknife 8.4.0 (and possibly others) but not a requirement for Butterknife 6.0.0 (which was shown in the video.

Thanks for the help, Seth!

Seth Kroger
Seth Kroger
56,413 Points

I think your missing the attribute android:layout_alignParentTop="true" on the ProgressBar in the layout. Since the width and height are both wrap_content you need to specify both a top and bottom alignment or the bar will "collapse".

Hi Seth,

Thanks for pointing out that missing attribute. I have implemented the change, but I'm still getting the null pointer exception.

Any ideas on what this might be caused by?

Thanks!

Seth Kroger
Seth Kroger
56,413 Points

Were you able to run the app successfully before adding the progress bar? Did it display the data fine without refresh functionality?

Hi Seth,

Edit: Sorry, it's still giving a null pointer exception.

It was working before hand. I think I've figured out the problem, I've removed

android:layout_alignBottom="@+id/refreshImageView"

From the progressBar attribute in the XML file. I'm not sure why, but it seems to have improved it.