App crashes when running, Models list added all the objects and ViewPager adapter seems fine

huangapple 未分类评论81阅读模式
英文:

App crashes when running, Models list added all the objects and ViewPager adapter seems fine

问题

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);
    }
}
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;
    }
}
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 = findViewById(R.id.viewPager);
        adapter = new Adapter(models, this);
        viewPager.setAdapter(adapter);

        viewPager.addOnPageChangeListener(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) {
            }
        });
    }
}

XML files remain unchanged. Logcat error log is retained for reference.

英文:

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&lt;Model&gt; models;
    private LayoutInflater layoutInflater;
    private Context context;

    public Adapter(List&lt;Model&gt; 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&lt;Model&gt; models;


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

        models = new ArrayList&lt;&gt;();
        models.add(new Model(R.drawable.ic_launcher_background,&quot;Title 1&quot;, &quot;Description 1&quot;));
        models.add(new Model(R.drawable.ic_launcher_background,&quot;Title 2&quot;, &quot;Description 2&quot;));
        models.add(new Model(R.drawable.ic_launcher_background,&quot;Title 3&quot;, &quot;Description 3&quot;));
        models.add(new Model(R.drawable.ic_launcher_background,&quot;Title 4&quot;, &quot;Description 4&quot;));
        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

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    tools:context=&quot;.MainActivity&quot;&gt;

    &lt;androidx.viewpager.widget.ViewPager
        android:id=&quot;@+id/viewPager&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;match_parent&quot;
        android:layout_centerInParent=&quot;true&quot;
        android:clipToPadding=&quot;false&quot;
        android:overScrollMode=&quot;never&quot;
        android:foregroundGravity=&quot;center&quot;/&gt;

&lt;/RelativeLayout&gt;

This is the item_layout.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    android:orientation=&quot;vertical&quot;
    android:gravity=&quot;center_vertical&quot;&gt;

    &lt;RelativeLayout
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;500dp&quot;&gt;

        &lt;ImageView
            android:layout_width=&quot;match_parent&quot;
            android:layout_height=&quot;200dp&quot;
            android:id=&quot;@+id/image&quot;
            android:scaleType=&quot;centerCrop&quot;
            android:src=&quot;@drawable/ic_launcher_background&quot;/&gt;

        &lt;TextView
            android:id=&quot;@+id/title&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:layout_below=&quot;@+id/image&quot;
            android:layout_marginTop=&quot;40dp&quot;
            android:layout_marginBottom=&quot;16dp&quot;
            android:text=&quot;Title 1&quot;
            android:layout_centerHorizontal=&quot;true&quot;
            android:textColor=&quot;#000000&quot;
            android:textSize=&quot;34sp&quot; /&gt;

        &lt;TextView
            android:id=&quot;@+id/desc&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:layout_below=&quot;@+id/title&quot;
            android:layout_marginTop=&quot;10dp&quot;
            android:layout_centerHorizontal=&quot;true&quot;
            android:text=&quot;felaFcnkrgjvnjAvd jfcnewnevnewengk wjcoaweovwjevwejv  joefwaofaevgjevjae &quot;
            android:textAlignment=&quot;center&quot;/&gt;


    &lt;/RelativeLayout&gt;


&lt;/LinearLayout&gt;

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 &#39;void androidx.viewpager.widget.ViewPager.setAdapter(androidx.viewpager.widget.PagerAdapter)&#39; 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 &#39;void androidx.viewpager.widget.ViewPager.setAdapter(androidx.viewpager.widget.PagerAdapter)&#39; 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)&#160;
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)&#160;
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)&#160;
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)&#160;
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2040)&#160;
        at android.os.Handler.dispatchMessage(Handler.java:107)&#160;
        at android.os.Looper.loop(Looper.java:224)&#160;
        at android.app.ActivityThread.main(ActivityThread.java:7520)&#160;
        at java.lang.reflect.Method.invoke(Native Method)&#160;
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)&#160;
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)&#160;

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

huangapple
  • 本文由 发表于 2020年8月15日 00:44:35
  • 转载请务必保留本文链接:https://java.coder-hub.com/63416874.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定