0

I've been trying to pass through an arraylist into viewpager but NullPointerException keeps coming up, can anyone help me out?? Below are the code snippets for everything. This is for the Adapter class

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

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

import java.util.List;



public class Adapter extends PagerAdapter {

    private List<Model> models;
    private LayoutInflater layoutInflater;
    private Context context;

    public Adapter(List<Model> models, Context context) {
        this.models = models;
        this.context = context;
    }

    @Override
    public int getCount() {
        return models.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view.equals(object);
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        layoutInflater = layoutInflater.from(context);
        View view = layoutInflater.inflate(R.layout.item_layout, container, false);

        ImageView imageView;
        TextView title, desc;

        imageView = view.findViewById(R.id.image);
        title = view.findViewById(R.id.title);
        desc = view.findViewById(R.id.desc);

        imageView.setImageResource(models.get(position).getImage());
        title.setText(models.get(position).getTitle());
        desc.setText(models.get(position).getDesc());

        container.addView(view);
        return view;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View) object);
    }
}

This is for the Model class

public class Model {
    private int image;
    private String title;
    private String desc;

    public Model(int image, String title, String desc) {
        this.image = image;
        this.title = title;
        this.desc = desc;
    }

    public int getImage() {
        return image;
    }

    public void setImage(int image) {
        this.image = image;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }
}

This is for the MainActivity Class

package com.example.testapp;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import android.os.Bundle;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    ViewPager viewPager;
    Adapter adapter;
    List<Model> models;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        models = new ArrayList<>();
        models.add(new Model(R.drawable.ic_launcher_background,"Title 1", "Description 1"));
        models.add(new Model(R.drawable.ic_launcher_background,"Title 2", "Description 2"));
        models.add(new Model(R.drawable.ic_launcher_background,"Title 3", "Description 3"));
        models.add(new Model(R.drawable.ic_launcher_background,"Title 4", "Description 4"));
        viewPager.setAdapter(adapter);
        adapter = new Adapter(models, this);


        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }
}

This is the main_activity.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=".MainActivity">

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerInParent="true"
        android:clipToPadding="false"
        android:overScrollMode="never"
        android:foregroundGravity="center"/>

</RelativeLayout>

This is the item_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="500dp">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:id="@+id/image"
            android:scaleType="centerCrop"
            android:src="@drawable/ic_launcher_background"/>

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/image"
            android:layout_marginTop="40dp"
            android:layout_marginBottom="16dp"
            android:text="Title 1"
            android:layout_centerHorizontal="true"
            android:textColor="#000000"
            android:textSize="34sp" />

        <TextView
            android:id="@+id/desc"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/title"
            android:layout_marginTop="10dp"
            android:layout_centerHorizontal="true"
            android:text="felaFcnkrgjvnjAvd jfcnewnevnewengk wjcoaweovwjevwejv  joefwaofaevgjevjae "
            android:textAlignment="center"/>


    </RelativeLayout>


</LinearLayout>

This is the logcat error log

16252-16252/com.example.testapp E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.testapp, PID: 16252
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.testapp/com.example.testapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.viewpager.widget.ViewPager.setAdapter(androidx.viewpager.widget.PagerAdapter)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3304)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3443)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2040)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:224)
        at android.app.ActivityThread.main(ActivityThread.java:7520)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.viewpager.widget.ViewPager.setAdapter(androidx.viewpager.widget.PagerAdapter)' on a null object reference
        at com.example.testapp.MainActivity.onCreate(MainActivity.java:22)
        at android.app.Activity.performCreate(Activity.java:7894)
        at android.app.Activity.performCreate(Activity.java:7881)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3279)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3443) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2040) 
        at android.os.Handler.dispatchMessage(Handler.java:107) 
        at android.os.Looper.loop(Looper.java:224) 
        at android.app.ActivityThread.main(ActivityThread.java:7520) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950) 

Thanks in advance for those who are interested in this problem, have a nice day!

  • 1
    you're never assigning a value to the viewpager, so it will be null – a_local_nobody Aug 14 '20 at 16:46
  • 1
    You forgot to assign `viewPager` in `MainActivity` before calling `setAdapter()` on it; e.g., `viewPager = findViewById(R.id.viewPager);`. – Mike M. Aug 14 '20 at 16:46
  • 1
    Ohh ok, thanks a lot! My mistake :D. I'm still a beginner and thanks to this helpful and friendly community!! – Lee John Aug 14 '20 at 16:52
  • But right now after I added the line that you told me, it only shows a blank screen with nothing on it. So how do I fix that? – Lee John Aug 14 '20 at 16:54
  • Move the `viewPager.setAdapter(adapter);` line to after the `adapter = new Adapter(models, this);` line. – Mike M. Aug 14 '20 at 16:57
  • @MikeM. Thanks a lot!! You fixed my problem!! Hopefully, everything else would be a smooth sail for me. Have a nice day though!!! :D – Lee John Aug 14 '20 at 16:59
  • No problem. Sorry I didn't notice that initially. Glad you got it working. Cheers! – Mike M. Aug 14 '20 at 17:00

0 Answers0