This question already has answers here:
What is a NullPointerException, and how do I fix it?
                                
                                    (12个答案)
                                
                        
                                去年关闭。
            
                    
我刚刚启动了一个项目的应用程序,想要为其添加滑块。除页面点外,我一切正常,在启动IntroSlider活动(显示所有幻灯片的活动)时,该页面点不显示,并在尝试转到下一张幻灯片时使应用程序崩溃。我不了解是什么原因导致了错误,请提供任何帮助。在IntroSlider.java中查找注释,该注释指定Android Studio所说的引起错误的行号。谢谢

IntoSlider.java:

 package com.businessbrains.businessbrains.Activities;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.businessbrains.businessbrains.Adapters.SlidesAdapter;
import com.businessbrains.businessbrains.Internals.PreferenceManager;
import com.businessbrains.businessbrains.R;

 public class IntroSlider extends AppCompatActivity implements View.OnClickListener{

        private ViewPager mPager;
        private int[] layouts = {R.layout.slide_welcome, R.layout.slide_account, R.layout.slide_selftest, R.layout.slide_mutliplayer};
        private SlidesAdapter slidesAdapter;
        private LinearLayout Dots_Layout;
        private ImageView[] dots;
        private Button skipBtn, nextBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if(new PreferenceManager(this).isSlidesEnabled()){
            loadLogin();
        }

        if(Build.VERSION.SDK_INT >= 19){
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        } else{
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        setContentView(R.layout.activity_intro_slider);

        mPager= (ViewPager) findViewById(R.id.viewPager);
        slidesAdapter = new SlidesAdapter(layouts, this);
        mPager.setAdapter(slidesAdapter);
        Dots_Layout = findViewById(R.id.dotsLayout);
        nextBtn = (Button) findViewById(R.id.nextBtn);
        nextBtn.setOnClickListener(this);
        skipBtn = (Button) findViewById(R.id.skipBtn);
        skipBtn.setOnClickListener(this);


        mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {
            }

            @Override
            public void onPageSelected(int i) {
                    createDots(i);
                    if(i==layouts.length-1){
                        nextBtn.setText("Start");
                        skipBtn.setVisibility(View.INVISIBLE);
                    }
                    else{
                        nextBtn.setText("Next");
                        skipBtn.setVisibility(View.VISIBLE);
                    }
            }

            @Override
            public void onPageScrollStateChanged(int i) {
            }
        });
    }

    private void createDots(int current_position){
        if(Dots_Layout!=null){
            Dots_Layout.removeAllViews();
        }
        dots = new ImageView[layouts.length];
        for(int i = 0; i < layouts.length; i++){
            if(i==current_position){
                dots[i].setImageDrawable((Drawable)ContextCompat.getDrawable(getApplicationContext(), R.drawable.accessory_active_dots));
            }
            else{
                dots[i].setImageDrawable((Drawable)(ContextCompat.getDrawable(getApplicationContext(), R.drawable.accessory_inactive_dots)));
                //line which is causing the error
            }
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(4,0,4,0);
            Dots_Layout.addView(dots[i], params);
        }
    }

     @Override
     public void onClick(View view) {
        switch(view.getId()){
            case R.id.nextBtn:
                loadNextSlide();
                break;
            case R.id.skipBtn:
                loadLogin();
                new PreferenceManager(this).writeDisableSlides();
                break;
        }
     }

     private void loadLogin(){
        startActivity(new Intent(this, LoginOptionsActivity.class));
        finish();
     }

     private void loadNextSlide(){
        int nextslide = mPager.getCurrentItem() + 1;
        if(nextslide < layouts.length){
            mPager.setCurrentItem(nextslide);
        }
        else{
            loadLogin();
            new PreferenceManager(this).writeDisableSlides();
        }
     }
 }


相应的.xml,activity_into_slider.xml:

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Activities.IntroSlider">


    <android.support.v4.view.ViewPager
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/viewPager"
        />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:alpha=".5"
        android:layout_above="@+id/dotsLayout"
        android:background="@android:color/white"
        android:layout_marginBottom="15dp"
    ></View>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/dotsLayout"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal"
        android:gravity="center"
        android:layout_marginBottom="55sp"
    />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Skip"
        android:textSize="16sp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:background="@android:color/transparent"
        android:id="@+id/skipBtn"
        android:layout_marginBottom="8dp"
        android:textColor="@android:color/white"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Next"
        android:textSize="16sp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:background="@android:color/transparent"
        android:id="@+id/nextBtn"
        android:layout_marginBottom="8dp"
        android:textColor="@android:color/white"
        />
</RelativeLayout>


幻灯片之一:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorSlide_welcome">

    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@drawable/ic_welcome"
        android:layout_centerHorizontal="true"
        android:scaleType="centerCrop"
        android:layout_marginTop="150dp"
        android:id="@+id/img"
        android:tint="@android:color/black"
        />

    <TextView
        android:layout_width="132dp"
        android:layout_height="100dp"
        android:text="@string/slide1title"
        android:textColor="@android:color/white"
        android:textSize="30sp"
        android:textStyle="bold"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/img"
        android:layout_marginTop="12dp"
        android:id="@+id/slidetitle"
        />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/slide1desc"
        android:textColor="@android:color/white"
        android:textSize="18sp"
        android:gravity="center_horizontal"
        android:layout_below="@+id/slidetitle"
        android:layout_marginTop="10dp"
        android:id="@+id/slide_desc"
        android:layout_marginRight="40sp"
        android:layout_marginLeft="40sp"
        />




</RelativeLayout>


被抛出的错误:

07-11 00:30:30.253 6010-6010/com.businessbrains.businessbrains E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.businessbrains.businessbrains, PID: 6010
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageDrawable(android.graphics.drawable.Drawable)' on a null object reference
        at com.businessbrains.businessbrains.Activities.IntroSlider.createDots(IntroSlider.java:89)
        at com.businessbrains.businessbrains.Activities.IntroSlider.access$000(IntroSlider.java:21)
        at com.businessbrains.businessbrains.Activities.IntroSlider$1.onPageSelected(IntroSlider.java:62)
        at android.support.v4.view.ViewPager.dispatchOnPageSelected(ViewPager.java:1947)
        at android.support.v4.view.ViewPager.scrollToItem(ViewPager.java:686)
        at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:670)
        at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:631)
        at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:612)
        at com.businessbrains.businessbrains.Activities.IntroSlider.loadNextSlide(IntroSlider.java:118)
        at com.businessbrains.businessbrains.Activities.IntroSlider.onClick(IntroSlider.java:101)
        at android.view.View.performClick(View.java:6256)
        at android.view.View$PerformClick.run(View.java:24701)
        at android.os.Handler.handleCallback(Handler.java:789)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)


annex_active_dots.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="oval"
        android:useLevel="true"
        android:dither="true">

    <size android:height="8dp" android:width="8dp"/>
    <solid android:color="@color/active_dots"/>

</shape>


annex_inactive_dots.xml:

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval"
    android:useLevel="true"
    android:dither="true">

    <size android:height="8dp" android:width="8dp"/>
    <solid android:color="@color/inactive_dots"/>

</shape>

最佳答案

dots = new ImageView[layouts.length];创建一个大小为layouts.length的数组,但该数组的所有元素均为空。

因此,当您在setImageDrawable(..)上调用dots[i]时,实际上是在空对象上调用方法setImageDrawable(..)

修复:在使用前,使用非空值初始化dots[i](即dots[i] =)。例如,在dots[i] = new ImageView()上调用setImageDrawable(..)之前,请先执行dots[i]

07-24 15:42