Null pointer


#1

I added the code in Listing 12.4 on page 216, and when I run in the emulator, I get a NullPointerException. I can’t seem to figure out why. Can someone please give me an idea of what to look at?

Here is the code in DatePickerFragment.java:

[code]package com.bignerdrand.android.criminalintent;

import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.View;

public class DatePickerFragment extends DialogFragment {

View v = getActivity().getLayoutInflater()   <-- null pointer exception on this line
        .inflate(R.layout.dialog_date, null);

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
	return new AlertDialog.Builder(getActivity())
	.setView(v)
	.setTitle(R.string.date_picker_title)
	.setPositiveButton(android.R.string.ok, null)
	.create();
}

}[/code]

Thanks!


#2

Had the same problem moments ago, and realized I had to register to let you know. Be sure to put that line in the method, and that should do it. I misread it myself.


#3

Thanks very much fanboy. I had just noticed that as well and was about to post that when I saw your post. I assume I was getting the null pointer because of a scope issue. Can you or anyone else shed some light for me on what was out of scope? The getActivity() returns the activity associated with the fragment. It seems like that should have been valid at that point.

Thanks.


#4

Hi fanboy, thanks for your reply, I also had the same problem, but I had to read it a few times before I understood it. So I’m going to rephrase it :slight_smile:

This line:

View v = getActivity().getLayoutInflater() .inflate(R.layout.dialog_date, null);

Has to be placed in the method onCreateDialog();
The result should look like this:

[code]package com.bignerdrand.android.criminalintent;

import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.View;

public class DatePickerFragment extends DialogFragment {

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
View v = getActivity().getLayoutInflater().inflate(R.layout.dialog_date, null);

  return new AlertDialog.Builder(getActivity())
  .setView(v)
  .setTitle(R.string.date_picker_title)
  .setPositiveButton(android.R.string.ok, null)
  .create();

}

}[/code]