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 Android Lists and Adapters (2015) Using Parcelable Data Retrieving Parcelable Data

Andrew Zhang
Andrew Zhang
4,364 Points

FATAL EXCEPTION: main

After following all the steps, when I click the daily forecast button on the app, I get the following error:

03-08 13:38:09.824 1904-1904/zepplez.com.rainorshine E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: zepplez.com.rainorshine, PID: 1904 java.lang.NullPointerException: Attempt to invoke virtual method 'int zepplez.com.rainorshine.weather.Day.getIconId()' on a null object reference

it looks like it's saying the getIconId is having an null object passed to it, but I'm not sure where I missed a step?

Help please :)

Slava Fleer
Slava Fleer
6,086 Points

I have too same error but on temperatureLabel, my apps was crushing so i added catching for general exception for it till i would find the problem. I got the new custom list but w/o temperature =)

try {
            holder.temperatureLabel.setText(day.getTemperatureMax() + "");
        }
        catch (Exception e){
            Log.e(TAG,"Fatal Exception", e);
        }

Interesting! What does your geTemperatureMax() method look like?

Izaak Prats
Izaak Prats
4,149 Points

Was having the same problem til I came here, found someone else was having the same problem and I forgot to set my textView for the temperature completely! Glad to see I wasn't the only one!

8 Answers

Good work!

So, you are populating the holder.temperatureLabel with R.id.temperatureLabel but the xml calls it a different ID. I'm surprised that compiles:

android:id="@+id/temperaturLabel"

Slight spelling error in the id name. Is that the problem?

OK - so something is null ... I suggest you add a breakpoint at the previous line to the error which, in my code, is: Day day = mDays[position];. Then run the code using the debugger, not just the normal play button. This will take a little time to get going but be patient!

The code should execute and you can get to the breakpoint by hitting the 7-DAYS button. The bottom of your Android Studio screen should then fill with info.

You should see some variables listed in the central lower pane. One of these should be this, which is expandable. Inside of this you should have mDays which is also expandable. Does it contain any data? You should see your mIcon, mSummary, mTimezoneetc. inside all of the 8 items that mDays should contain.

Click the Step-Over button to move execution to the next line. You shold now have the instance of Day that you created called day which is expandable. Does it contain sensible data? Further, you should see holder.iconImageView too - does that expand to show sensible info?

Is that working?

Steve.

Slava Fleer
Slava Fleer
6,086 Points

HI. Cause I have similar problem I would continue here , if it is not a problem.

I have next Fatal Error, that I catching it with generic extension for not crushing my app.

03-09 11:31:18.989    2840-2840/com.slava.whetherapp E/DayAdapter Fatal Exception caught:
    java.lang.NullPointerException
            at com.slava.whetherapp.adapters.DayAdapter.getView(DayAdapter.java:68)
            at android.widget.AbsListView.obtainView(AbsListView.java:2159)
            at android.widget.ListView.makeAndAddView(ListView.java:1831)
            at android.widget.ListView.fillDown(ListView.java:674)
            at android.widget.ListView.fillFromTop(ListView.java:735)
            at android.widget.ListView.layoutChildren(ListView.java:1652)
            at android.widget.AbsListView.onLayout(AbsListView.java:1994)
            at android.view.View.layout(View.java:14008)
            at android.view.ViewGroup.layout(ViewGroup.java:4373)
            at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1021)
            at android.view.View.layout(View.java:14008)
            at android.view.ViewGroup.layout(ViewGroup.java:4373)
            at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
            at android.view.View.layout(View.java:14008)
            at android.view.ViewGroup.layout(ViewGroup.java:4373)
            at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1663)
            at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1521)
            at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
            at android.view.View.layout(View.java:14008)
            at android.view.ViewGroup.layout(ViewGroup.java:4373)
            at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
            at android.view.View.layout(View.java:14008)
            at android.view.ViewGroup.layout(ViewGroup.java:4373)
            at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1892)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1711)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
            at android.view.Choreographer.doCallbacks(Choreographer.java:562)
            at android.view.Choreographer.doFrame(Choreographer.java:532)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
            at android.os.Handler.handleCallback(Handler.java:725)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5041)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
            at dalvik.system.NativeStart.main(Native Method)

the clickable line turning me to

holder.temperatureLabel.setText(day.getTemperatureMax() + "");

this is my DayAdapter code

package com.slava.whetherapp.adapters;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.slava.whetherapp.R;
import com.slava.whetherapp.weather.Day;

/**
 * Created by Slava on 08/03/2015.
 */
public class DayAdapter extends BaseAdapter {

    public static final String TAG = DayAdapter.class.getSimpleName();

    private Context mContext;
    private Day[] mDays;

    public DayAdapter(Context context, Day[] days) {
        mContext = context;
        mDays = days;
    }

    @Override
    public int getCount() {
        return mDays.length;
    }

    @Override
    public Object getItem(int position) {
        return mDays[position];
    }

    @Override
    public long getItemId(int position) {
        return 0; // we would not use it. Tag items for easy reference.
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder;

        if(convertView == null) {
            // Brand new
            convertView = LayoutInflater.from(mContext).inflate(R.layout.daily_list_item, null);
            holder = new ViewHolder();
            holder.iconImageView = (ImageView) convertView.findViewById(R.id.iconImageView);
            holder.temperatureLabel = (TextView) convertView.findViewById(R.id.temperatureLabel);
            holder.dayLabel = (TextView) convertView.findViewById(R.id.dayNameLabel);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Day day = mDays[position];

        holder.iconImageView.setImageResource(day.getIconId());

        try {
            holder.temperatureLabel.setText(day.getTemperatureMax() + "");
        }
        catch (Exception e){
            Log.e(TAG,"Fatal Exception caught: ", e);
        }

        holder.dayLabel.setText(day.getDayOfTheWeek());

        return convertView;
    }

    private static class ViewHolder {
        ImageView iconImageView; // public by default
        TextView temperatureLabel;
        TextView dayLabel;
    }
}

and this is my Day.java

package com.slava.whetherapp.weather;

import android.os.Parcel;
import android.os.Parcelable;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

/**
 * Created by Slava on 05/03/2015.
 */
public class Day implements Parcelable {
    private long mTime;
    private String mSummary;
    private double mTemperatureMax;
    private String mIcon;
    private String mTimezone;

    public long getTime() {
        return mTime;
    }

    public void setTime(long time) {
        mTime = time;
    }

    public String getSummary() {
        return mSummary;
    }

    public void setSummary(String summary) {
        mSummary = summary;
    }

    public int getTemperatureMax() {
        return (int)Math.round(mTemperatureMax);
    }

    public void setTemperatureMax(double temperatureMax) {
        mTemperatureMax = temperatureMax;
    }

    public String getIcon() {
        return mIcon;
    }

    public void setIcon(String icon) {
        mIcon = icon;
    }

    public String getTimezone() {
        return mTimezone;
    }

    public void setTimezone(String timezone) {
        mTimezone = timezone;
    }

    public int getIconId() {
        return Forecast.getIconId(mIcon);
    }

    public String getDayOfTheWeek() {
        SimpleDateFormat formatter = new SimpleDateFormat("EEEE");
        formatter.setTimeZone(TimeZone.getTimeZone(mTimezone));
        Date dateTime = new Date(mTime * 1000);

        return formatter.format(dateTime);
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeLong(mTime);
        dest.writeString(mSummary);
        dest.writeDouble(mTemperatureMax);
        dest.writeString(mIcon);
        dest.writeString(mTimezone);
    }

    private Day(Parcel in) {
        mTime = in.readLong();
        mSummary = in.readString();
        mTemperatureMax = in.readDouble();
        mIcon = in.readString();
        mTimezone = in.readString();
    }

    public Day() {};

    public static final Creator<Day> CREATOR = new Creator<Day>() {
        @Override
        public Day createFromParcel(Parcel source) {
            return new Day(source);
        }

        @Override
        public Day[] newArray(int size) {
            return new Day[size];
        }
    };
}

with debugging I can't find the bug cause it entering to methods that come with java/android .

So what are suggestions? How to work in such case?

Thank you.

Andrew Zhang
Andrew Zhang
4,364 Points

Hi Steve, I tried to debug and found the mDays and day are both null...

I guess I need to trace back to see how come mDays has nothing in it...

Will report back.

Perfect, yes.

Find where they are instantiated and assigned the values that should be there. I had this problem but managed to fix it on my own which means it is very straightforward!!

I'll check back when I'm back from the meeting; that should be 5 hours or so ...

Steve.

Slava Fleer
Slava Fleer
6,086 Points

meantime =)

I recognized that from beginning the holder.temperatureLabel is null and not expandable while holder.iconImageView and holder.dayLabel are.

Imgur

I don't see any difference in my code when I creating holder.temperatureLabel or holder.dayLabel.

Glad you got it fixed, Andrew - that's one way of tackling tricky issues; get the code running in the debugger bit by bit.

Slava Fleer; how are you getting on?

Steve.

Slava Fleer
Slava Fleer
6,086 Points

Sadly still no progress.

Slava Fleer can you upload your code into Github - I can take a look through it, then, and see if I can spot the issue.

Looking at your screenshot, if temperatureLabel is null but others aren't then that's a start. Does you mDays[] array have anything in it and is that assigned to day OK?

There are differences in how you are setting your labels. The breakpoint might need to move for clarity and the extra code you've added can be deleted too - that's not helping solve the problem, rather it just avoids it!

As above, can you please put the breakpoint at Day day = mDays[position];. Then see what's expandable and what is in this & day. That's the key to this.

Slava Fleer
Slava Fleer
6,086 Points

still don't familiar with gitHub so much, so i am posting dropbox folder here. it's all the project as zip file.

https://www.dropbox.com/sh/sqdltaxzw6snbf5/AAB48Jqt2DIBszTgoYaNnRhLa?dl=0

thanks again.

p.s.

if tomorrow would not find the solution, would start gitHub basic =)

Slava Fleer
Slava Fleer
6,086 Points

to Steve: Yes. the arrays looks fine.

Imgur

and on next stepover

Imgur

I think my problem is not with data transferring but in defining holders. But I can't see any difference in creating between holder.temperatureLabel.setText(day.getTemperatureMax() + ""); and holder.dayLabel.setText(day.getDayOfTheWeek()); in my code.

Ben Jakuben
STAFF
Ben Jakuben
Treehouse Teacher

WOW?!!! just one little char =) can throw away 2 days of your time =)

Spoken like a true programmer! This is sad but true. But not that bad, because these kind of struggles really help you learn how to troubleshoot in the future. Issues like this get much easier to solve, and the skills about debugging and troubleshooting help you solve harder problems, too.

As a side note - this was an awesome thread to read through. Great help from Steve Hunter!

Hi Slava,

The issue is a NullPointerException so something's null. The code compiles, builds and runs, so it isn't a code issue, per se. This is likely to be some semantics that populate the day instance with the JSON data. I had a problem with mine when I did this course, so maybe there's a little bug in there somewhere.

If I was in your position, I would do what I initially suggested to Andrew at the outset. Set a breakpoint just above the line highlighted by Logcat then run the app in the debugger; not the usual play button. Then, you can see if mDays[] has anything in it and the other variables too. This will lead us towards the problem, rather than trying to unpick lots of code. That's the best starting point - let's find out what is null and we can track that error backwards through the code to its root.

I'm off out on business for the afternoon - I should be back by 5 and will try to compare your code with mine then.

Alternatively, you can have a look at mine in Github. The project is work in progress so it isn't just the code for this course.

https://github.com/OnlySteveH/Stormy2

Slava Fleer
Slava Fleer
6,086 Points

thanks. I would check it.

Andrew Zhang
Andrew Zhang
4,364 Points

Hey Steve, thank you for your help.

I've debugged my code and found the problem.

It was missing the following code:

            days[i] = day;

inside the

 private Day[] getDailyForecast(String jsonData) throws JSONException {

Which means everytime it did the for loop, it took out the day data but wasn't putting it anywhere, therefore the days array is always null. =)

very glad i got it fixed, thanks again Steve.

Hi Andrew,

If you could post your code, that would help - plus, does the error in Logcat mention the java line number where the error is occurring? That's often a good strating point.

My getIconId() method looks like:

public int getIconId() {
    return Forecast.getIconId(mIcon);
}

But yours may differ depending on where you are up to in the course.

I'm not sure why it is referring to a virtual method ... that's a new one on me.

In my code, the day.getIconId() is called inside an adapter; that is the only time it is used. It would be useful to post that piece of code from your project too.

Steve.

Andrew Zhang
Andrew Zhang
4,364 Points

Hi Steve, thank you very much for your reply.

The error has a clickable link which is:

            at zepplez.com.rainorshine.adapters.DayAdapter.getView(DayAdapter.java:61)

following that (DayAdapter.java:61) brings me to the following line of code:

        holder.iconImageView.setImageResource(day.getIconId());

my getIconId() looks exactly like yours.

Slava Fleer
Slava Fleer
6,086 Points

I think I found spot where need to look for my issue:

I putted break point here:

Imgur

and after running line 54 , holder.iconImageView received its value.

Imgur

and after line 55, holder.temperatureLabel - didn't.

Imgur

and after it holder.dayLabel received value too.

Is it something wrong with my daily_list_item.xml ?

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingLeft="50dp"
                android:paddingRight="32dp"
                android:paddingTop="4dp"
                android:paddingBottom="4dp"
                tools:background="#ffaa00">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/circleImageView"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:src="@drawable/bg_temperature"/>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/iconImageView"
        android:src="@drawable/clear_day"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/circleImageView"
        android:layout_toEndOf="@+id/circleImageView"
        android:paddingLeft="10dp"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/dayNameLabel"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/iconImageView"
        android:layout_toEndOf="@+id/iconImageView"
        android:textColor="@android:color/white"
        android:textSize="20sp"
        android:paddingLeft="10dp"
        tools:text="Wednesday"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/temperaturLabel"
        android:layout_alignTop="@+id/circleImageView"
        android:layout_alignBottom="@+id/circleImageView"
        android:layout_alignLeft="@+id/circleImageView"
        android:layout_alignRight="@+id/circleImageView"
        android:gravity="center"
        android:textColor="#f25019"
        tools:text="100"/>
</RelativeLayout>

thanks for any help =)

Slava Fleer
Slava Fleer
6,086 Points

WOW?!!! just one little char =) can throw away 2 days of your time =)

Thank you very much for your time.

I now can continue with the project.

Haha! Glad it worked and, yes, chasing down the errors can be time consuming and frustrating, but we get there in the end!

Steve.

Joe Goodall
Joe Goodall
3,483 Points

This is the error I get. Any idea as to a solution?

04-29 17:08:06.367 16614-16614/com.getstrength.stormy E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.getstrength.stormy, PID: 16614 java.lang.NullPointerException: id == null at java.util.TimeZone.getTimeZone(TimeZone.java:349) at com.getstrength.stormy.weather.Day.getDayOfTheWeek(Day.java:66) at com.getstrength.stormy.adapters.DayAdapter.getView(DayAdapter.java:65) at android.widget.AbsListView.obtainView(AbsListView.java:2344) at android.widget.ListView.makeAndAddView(ListView.java:1864) at android.widget.ListView.fillDown(ListView.java:698) at android.widget.ListView.fillFromTop(ListView.java:759) at android.widget.ListView.layoutChildren(ListView.java:1673) at android.widget.AbsListView.onLayout(AbsListView.java:2148) at android.view.View.layout(View.java:15596) at android.view.ViewGroup.layout(ViewGroup.java:4966) at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1076) at android.view.View.layout(View.java:15596) at android.view.ViewGroup.layout(ViewGroup.java:4966) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573) at android.widget.FrameLayout.onLayout(FrameLayout.java:508) at android.view.View.layout(View.java:15596) at android.view.ViewGroup.layout(ViewGroup.java:4966) at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703) at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557) at android.widget.LinearLayout.onLayout(LinearLayout.java:1466) at android.view.View.layout(View.java:15596) at android.view.ViewGroup.layout(ViewGroup.java:4966) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573) at android.widget.FrameLayout.onLayout(FrameLayout.java:508) at android.view.View.layout(View.java:15596) at android.view.ViewGroup.layout(ViewGroup.java:4966) at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2072) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1829) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1054) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5779) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767) at android.view.Choreographer.doCallbacks(Choreographer.java:580) at android.view.Choreographer.doFrame(Choreographer.java:550) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5239) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Hi Joe,

You got a NullPointer too! Way to go! It happens to us all ...

There were lots of suggestions in the thread above. These involved breakpoints and other such stuff. Plus, when does your app crash - what are you doing to it at the time it falls over? Click a button?

Steve.