Challange 2- keep getting NullPointerException


#1

Hello I am attempting Challenge 2 and keep getting a NullPointerException on mFirstButton, I have placed my code below, any help would be greatly appreciated.

Java
package com.bignerdranch.android.criminalintent;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import 	android.support.v7.widget.RecyclerView.ViewHolder;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import java.util.List;
import java.util.UUID;


public class CrimePagerActivity extends AppCompatActivity {
    private static final String EXTRA_CRIME_ID="com.bignerdranch.android.criminalintent.crime_id";
private ViewPager mViewPager;
private List<Crime> mCrimes;
private static int mPosition;
private static int mSize;
private Button mFirstButton;
private Button mLastButton;
private View mView;
public static Intent newIntent(Context packageContext,UUID crimeId){
    Intent intent=new Intent(packageContext, CrimePagerActivity.class);
    intent.putExtra(EXTRA_CRIME_ID,crimeId);
    return intent;
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_crime_pager);

    mViewPager=(ViewPager) findViewById(R.id.crime_view_pager);
    mCrimes =CrimeLab.get(this).getCrimes();
    UUID crimeId=(UUID) getIntent().getSerializableExtra(EXTRA_CRIME_ID);
    FragmentManager fragmentManager=getSupportFragmentManager();
    mViewPager.setAdapter(new FragmentStatePagerAdapter(fragmentManager) {
        @Override
        public Fragment getItem(int position) {
            Crime crime=mCrimes.get(position);
            mPosition=position;
            return CrimeFragment.newInstance(crime.getId());
        }
        @Override
        public int getCount() {
            mSize=mCrimes.size();
            return mCrimes.size();
        }
    });

    mFirstButton= findViewById(R.id.first_button); 
    mFirstButton.setOnClickListener(new View.OnClickListener() { /*<--This is where it crashes*/
        @Override
        public void onClick(View view) {
            mViewPager.setCurrentItem(0);
        }
    });

    mLastButton= findViewById(R.id.last_button);
    mLastButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mViewPager.setCurrentItem(getSize()-1);
        }
    });

    mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            mFirstButton.setEnabled(getPosition()!=0);
            mLastButton.setEnabled(getPosition() != CrimePagerActivity.getSize() - 1);
        }
        @Override
        public void onPageSelected(int position) {
        }
        @Override
        public void onPageScrollStateChanged(int state) {
        }
    });

    for (int i=0; i<mCrimes.size();i++){
        if(mCrimes.get(i).getId().equals(crimeId)){
            mViewPager.setCurrentItem(i);
            break;
        }
    }
}
public int getPosition(){
    return mPosition;
}
 public static int getSize() {
     return mSize;
  }
 }
}

XML

   <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_crime"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:orientation="vertical">
<TextView
    style="?android:listSeparatorTextViewStyle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/crime_title_label"/>
<EditText
    android:id="@+id/crime_title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/crime_title_hint"/>
<TextView
    style="?android:listSeparatorTextViewStyle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/crime_details_label"/>
<Button
    android:id="@+id/crime_date"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
<CheckBox
    android:id="@+id/crime_solved"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/crime_solved_label"/>

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_gravity="center">
    <Button
        android:id="@+id/first_button"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:layout_margin="2dp"
        android:text="@string/first_button_label" />
    <Button
        android:id="@+id/last_button"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:layout_margin="2dp"
        android:text="@string/last_button_label" />
</LinearLayout>
</LinearLayout>

#2

NullPointerException crash log will be more helpful for further analyze.
Please also provide it.


#3

This it the entire log thank you for your help

10/01 13:48:43: Launching app
$ adb shell am start -n "com.bignerdranch.android.criminalintent/com.bignerdranch.android.criminalintent.CrimeListActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Waiting for application to come online: com.bignerdranch.android.criminalintent.test | com.bignerdranch.android.criminalintent
Waiting for application to come online: com.bignerdranch.android.criminalintent.test | com.bignerdranch.android.criminalintent
Waiting for application to come online: com.bignerdranch.android.criminalintent.test | com.bignerdranch.android.criminalintent
Connecting to com.bignerdranch.android.criminalintent
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/art: Not late-enabling -Xcheck:jni (already on)
W/art: Unexpected CPU variant for X86 using defaults: x86
W/ActivityThread: Application com.bignerdranch.android.criminalintent is waiting for the debugger on port 8100...
I/System.out: Sending WAIT chunk
I/art: Debugger is active
Connected to the target VM, address: 'localhost:8607', transport: 'socket'
I/System.out: Debugger has connected
    waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: debugger has settled (1331)
W/System: ClassLoader referenced unknown path: /data/app/com.bignerdranch.android.criminalintent-2/lib/x86
I/InstantRun: starting instant run server: is main process
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
I/ViewConfigCompat: Could not find method getScaledScrollFactor() on ViewConfiguration
D/: HostConnection::get() New Host Connection established 0x9f22e6c0, tid 6948
D/: HostConnection::get() New Host Connection established 0x9f22ea00, tid 6974
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/OpenGLRenderer: Swap behavior 0
D/EGL_emulation: eglCreateContext: 0xa8f4b5c0: maj 3 min 0 rcv 3
D/EGL_emulation: eglMakeCurrent: 0xa8f4b5c0: ver 3 0 (tinfo 0x9d41e9a0)
E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008cdf
    glUtilsParamSize: unknow param 0x00008824
I/art: Do partial code cache collection, code=13KB, data=26KB
I/art: After code cache collection, code=13KB, data=26KB
    Increasing code cache capacity to 128KB
I/art: Do partial code cache collection, code=13KB, data=43KB
I/art: After code cache collection, code=13KB, data=43KB
    Increasing code cache capacity to 256KB
I/art: JIT allocated 60KB for compiled code of void android.widget.TextView.<init>(android.content.Context, android.util.AttributeSet, int, int)
W/art: Before Android 4.1, method int android.support.v7.widget.DropDownListView.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
D/EGL_emulation: eglMakeCurrent: 0xa8f4b5c0: ver 3 0 (tinfo 0x9d41e9a0)
I/art: Background sticky concurrent mark sweep GC freed 17162(1348KB) AllocSpace objects, 0(0B) LOS objects, 44% free, 4MB/8MB, paused 1.630ms total 117.459ms
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.bignerdranch.android.criminalintent, PID: 6948
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bignerdranch.android.criminalintent/com.bignerdranch.android.criminalintent.CrimePagerActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6119)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at com.bignerdranch.android.criminalintent.CrimePagerActivity.onCreate(CrimePagerActivity.java:59)
        at android.app.Activity.performCreate(Activity.java:6679)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
        at android.app.ActivityThread.-wrap12(ActivityThread.java) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:154) 
        at android.app.ActivityThread.main(ActivityThread.java:6119) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
Disconnected from the target VM, address: 'localhost:8607', transport: 'socket'

#4

I am a little out of practice with UI, but I think you need to create mFirstButton and mLastButton in the same section of code where the CrimeFragment View is inflated. You defined those two buttons in the CrimeFragment layout XML file, so you need to call findViewById() for those buttons after you have created the CrimeFragment View.


#5

Please also provide your layout activity_crime_pager.xml

According to your usage,

mFirstButton= findViewById(R.id.first_button);
mLastButton= findViewById(R.id.last_button);

both buttons should be defined in this layout file, not the current fragment_crime.xml.