RecyclerView выбрасывает нулевой указатель для setAdapter, хотя адаптер определен - PullRequest
0 голосов
/ 04 февраля 2020

У меня исключение из-за нулевого указателя, но я не вижу, в чем причина. Я пытался исправить эту ошибку в течение 2 дней.

Вот поле activity_main. xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>

и код для класса MainActivity

package com.example.servicestest1;

import android.os.Bundle;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity{
    private static final String TAG = "MainActivity";
    private ArrayList<String> mDescriptions = new ArrayList<>();
    private ArrayList<String> mStartDates = new ArrayList<>();
    private ArrayList<String> mEndDates = new ArrayList<>();
    private ArrayList<String> mImageUrls = new ArrayList<>();
    private ArrayList<String> mTopicList = new ArrayList<>();
    RecyclerView recyclerView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = findViewById(R.id.recycler_view);
        initRecyclerViewItems();
    }
    private void initRecyclerViewItems() {
        Log.d(TAG, "initRecyclerViewItems: preparing items");

        addRecyclerViewItem("https://i.redd.it/3p6500yf3he41.jpg","Hogwarts Express","Working for the soviet union"
                ,"20/01/1968","20/10/1984");
        addRecyclerViewItem("https://i.redd.it/s8bmctrhdxd41.jpg","Some scene about Nature","Some title",
                "20/09/1897","20/03/1989");
        addRecyclerViewItem("https://i.redd.it/lrbmhm707rd41.jpg","Boating","Boating in a pristine location",
                "30/09/1998","31/09/1998");
        initRecyclerView();

    }
    private void addRecyclerViewItem(String imageUrl, String topic, String description, String startDate, String endDate){
        Log.w(TAG, "addRecyclerViewItem: called", null);
        mImageUrls.add(imageUrl);
        mTopicList.add(topic);
        mStartDates.add(startDate);
        mEndDates.add(endDate);
        mDescriptions.add(description);
    }
    private void initRecyclerView(){

        RecyclerViewAdapter adapter = new RecyclerViewAdapter(this,mTopicList,mDescriptions,
                mStartDates,mEndDates,mImageUrls);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }
}

recyclerView.setAdapter возвращает исключение NullPointer, даже если я определили адаптер.

и код для адаптера RecyclerView

package com.example.servicestest1;

import android.content.Context;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;


public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{

    private static final String TAG = "RecyclerViewAdapter";

    private ArrayList<String> mTopicListOfTheEvent;
    private ArrayList<String> mDescriptionListOfTheEvent;
    private ArrayList<String> mStartDateListOfTheEvent;
    private ArrayList<String> mEndDateListOfTheEvent;
    private ArrayList<String> mImageListDescribingTheEvent;
    private Context mContext;

    RecyclerViewAdapter(Context context,
                        ArrayList<String> topicListOfTheEvent,
                        ArrayList<String> descriptionListOfTheEvent,
                        ArrayList<String> startDateListOfTheEvent,
                        ArrayList<String> endDateListOfTheEvent,
                        ArrayList<String> imageListDescribingTheEvent){
        this.mContext = context;
        this.mTopicListOfTheEvent = topicListOfTheEvent;
        this.mDescriptionListOfTheEvent = descriptionListOfTheEvent;
        this.mStartDateListOfTheEvent = startDateListOfTheEvent;
        this.mEndDateListOfTheEvent = endDateListOfTheEvent;
        this.mImageListDescribingTheEvent = imageListDescribingTheEvent;
    }

    @NonNull
    @Override
    public RecyclerViewAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_recycler_view_layout,parent,true);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerViewAdapter.ViewHolder holder, int position) {
        Log.d(TAG, "onBindViewHolder: called");

        holder.descriptionOfTheEvent.setText(mDescriptionListOfTheEvent.get(position));
        holder.imageDescribingTheEvent.setImageURI(Uri.parse(mImageListDescribingTheEvent.get(position)));
        holder.startDateOfTheEvent.setText(mStartDateListOfTheEvent.get(position));
        holder.endDateOfTheEvent.setText(mEndDateListOfTheEvent.get(position));
        holder.topicListOfTheEvent.setText(mTopicListOfTheEvent.get(position));
        holder.parentLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: Clicked on");
                Toast.makeText(mContext,"You pressed me",Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public int getItemCount() {
        return mTopicListOfTheEvent.size();
    }
    class ViewHolder extends RecyclerView.ViewHolder{
        TextView descriptionOfTheEvent;
        TextView topicListOfTheEvent;
        TextView startDateOfTheEvent;
        TextView endDateOfTheEvent;
        ImageView imageDescribingTheEvent;
        LinearLayout parentLayout;
        ViewHolder(@NonNull View itemView) {
            super(itemView);
            parentLayout = itemView.findViewById(R.id.recycler_view_item);

        }
    }
}

и код activity_recycler_view_layout. xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    android:id="@+id/recycler_view_item">

    <!-- The code for the AppBar -->
    <androidx.appcompat.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="44dp"
        android:background="#FFFEFE"
        android:elevation="5dp"
        tools:targetApi="lollipop">

        <RelativeLayout
            android:id="@+id/relativeLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/imageView"
                android:layout_width="wrap_content"
                android:layout_height="44dp"
                android:layout_alignParentStart="true"
                android:layout_alignParentLeft="true"
                android:layout_marginTop="8dp"
                android:src="@drawable/bottom_lotus"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                tools:ignore="ContentDescription" />

            <ImageView
                android:id="@+id/imageView2"
                android:layout_width="11dp"
                android:layout_height="44dp"
                android:layout_marginStart="18dp"
                android:layout_marginLeft="18dp"
                android:layout_marginTop="17dp"
                android:layout_marginBottom="10dp"
                android:src="@drawable/arrow"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                tools:ignore="ContentDescription" />

            <TextView
                android:id="@+id/textView"
                android:layout_width="66dp"
                android:layout_height="44dp"
                android:layout_marginStart="49dp"
                android:layout_marginLeft="49dp"

                android:layout_marginTop="13dp"
                android:layout_marginBottom="10dp"
                android:lineHeight="21sp"
                android:text="Services"
                android:textColor="#403E42"
                android:textSize="16sp"
                app:fontFamily="@font/roboto_condensed_regular"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <de.hdodenhof.circleimageview.CircleImageView
                android:id="@+id/profile_picture"
                android:layout_width="wrap_content"
                android:layout_height="44dp"
                android:layout_alignParentRight="true"
                android:layout_marginLeft="4dp"
                android:layout_marginTop="4dp"
                android:layout_marginBottom="4dp"
                android:src="@drawable/ic_launcher_background"
                android:layout_alignParentEnd="true" />
        </RelativeLayout>

    </androidx.appcompat.widget.Toolbar>


    <RelativeLayout
        android:layout_width="348dp"
        android:layout_height="296dp"
        android:layout_margin="6dp">

        <ImageView
            android:layout_width="348dp"
            android:layout_height="296dp"

            android:src="@drawable/images" />

        <TextView
            android:id="@+id/topic_text_view"
            android:layout_width="wrap_content"
            android:layout_height="28dp"
            android:layout_marginStart="25dp"
            android:layout_marginLeft="25dp"
            android:layout_marginTop="25dp"
            android:alpha="0.41"
            android:text="It's His Birthday"
            android:textColor="#f93f3f"
            android:textSize="21sp"
            app:fontFamily="@font/roboto_condensed_bold" />

        <!--This LinearLayout is used for drawing the text inside the rectangle -->
        <LinearLayout
            android:layout_width="242dp"
            android:layout_height="51dp"
            android:layout_marginLeft="26dp"
            android:layout_marginTop="64dp"
            android:background="@drawable/rectangle"
            android:orientation="vertical"

            android:layout_marginStart="26dp">

            <TextView
                android:layout_width="198dp"
                android:layout_height="32dp"
                android:gravity="center"
                android:lineHeight="16dp"

                android:text="This is Sample Text"
                android:textColor="#ffffff"
                android:textSize="12sp"

                app:fontFamily="@font/roboto_bold" />

        </LinearLayout>

        <TextView

            android:layout_width="37dp"
            android:layout_height="19dp"
            android:layout_marginStart="26dp"
            android:layout_marginLeft="26dp"
            android:layout_marginTop="142dp"
            android:lineHeight="19dp"

            android:text="Dates"
            android:textColor="#FFFFFF"
            android:textSize="14sp"
            app:fontFamily="@font/roboto_condensed_bold" />

        <LinearLayout
            android:layout_width="86dp"
            android:layout_height="35dp"
            android:layout_marginStart="62dp"
            android:layout_marginLeft="62dp"
            android:layout_marginTop="142dp"
            android:orientation="vertical">

            <TextView
                android:id="@+id/start_date_of_the_event"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:lineHeight="16dp"
                android:text="12 June 2019"
                android:textColor="#ffffff"
                android:textSize="12sp"
                app:fontFamily="@font/roboto" />

            <TextView
                android:id="@+id/end_date_of_the_event"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:lineHeight="16dp"
                android:text="13 June 2019"
                android:textColor="#ffffff"
                android:textSize="12sp"
                app:fontFamily="@font/roboto" />
        </LinearLayout>
    </RelativeLayout>

    <TextView
        android:id="@+id/reject_button"
        android:layout_width="35dp"
        android:layout_height="16dp"

        android:layout_marginStart="160dp"
        android:layout_marginLeft="160dp"
        android:layout_marginTop="15dp"
        android:clickable="true"
        android:text="REJECT"
        android:textColor="#4B0082"
        android:textStyle="bold"
        tools:ignore="KeyboardInaccessibleWidget" />

    <Button
        android:id="@+id/accept_button"
        android:layout_width="103dp"
        android:layout_height="37dp"
        android:layout_marginStart="248dp"
        android:layout_marginLeft="248dp"
        android:background="#4B0082"

        android:text="ACCEPT"
        android:textColor="#ffffff"
        android:textSize="20sp" />


</LinearLayout>

И вот ошибки

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.servicestest1/com.example.servicestest1.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)' on a null object reference
        at com.example.servicestest1.MainActivity.initRecyclerView(MainActivity.java:53)
        at com.example.servicestest1.MainActivity.initRecyclerViewItems(MainActivity.java:38)
        at com.example.servicestest1.MainActivity.onCreate(MainActivity.java:27)
        at android.app.Activity.performCreate(Activity.java:7136)
        at android.app.Activity.performCreate(Activity.java:7127)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:193) 
        at android.app.ActivityThread.main(ActivityThread.java:6669) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 

Ответы [ 3 ]

4 голосов
/ 04 февраля 2020

recyclerView переменная задается после ее использования, поэтому она равна нулю при попытке установить адаптер.

Назначить recyclerView перед настройкой адаптера

protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    recyclerView = findViewById(R.id.recycler_view);
    initRecyclerViewItems();
}
0 голосов
/ 22 апреля 2020

Требуется некоторое время, чтобы надуть взгляд переработчика. Попробуйте добавить цикл ожидания:

recyclerView = findViewById(R.id.recycler_view);
while (recyclerView == null){
  Thread.sleep(1);
}

init();
0 голосов
/ 04 февраля 2020

in Java, вызов findViewById(...) инициализирует переменную view. Переменная обычно равна нулю, когда findViewById(..) еще не был вызван или был вызван с id из макета, который еще не был раздут. В твоем случае. Вы можете исправить ошибку, просто изменив метод onCreate.

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

    recyclerView = findViewById(R.id.recycler_view); //recyclerView gets initialized here
    initRecyclerViewItems();
}

Документы Google на findViewById

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...