Recyclerview适配器的空点异常

时间:2019-07-18 17:49:26

标签: android android-recyclerview nullpointerexception recycler-adapter

代码没有任何错误...但是,当我在手机上运行应用程序时,recycler view adapter出现了空点异常,并且我不知道哪些数据为空

我尝试使用recyclerview适配器重新创建布局,但是它不起作用

RecyclerViewAdapter.java

package com.example.schedule;

/*
* File to help create the recycler view items to be viewed
* Should help with the iteration
* */

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

import androidx.annotation.NonNull;
import androidx.appcompat.view.menu.MenuView;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import org.w3c.dom.Text;

import java.util.ArrayList;

import de.hdodenhof.circleimageview.CircleImageView;

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

    private ArrayList<String> mScheduleNames = new ArrayList<>();
    private ArrayList<String> mScheduleImages = new ArrayList<>();
    private Context mContext;

    private final String TAG = "RecyclerViewAdapter";


    public RecyclerViewAdapter(Context context, ArrayList<String> scheduleNames, ArrayList<String> scheduleImages) {
        mScheduleNames = scheduleNames;
        mScheduleImages = scheduleImages;
        mContext = context;
    }

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

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

        Glide.with(mContext)
                .load(mScheduleImages.get(position))
                .asBitmap()
                .into(holder.scheduleImage);

        holder.scheduleName.setText(mScheduleImages.get(position));
        holder.parentLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "Onclicked: clicked on:" + mScheduleImages.get(position));

                Toast.makeText(mContext, mScheduleImages.get(position), Toast.LENGTH_LONG).show();
            }
        });
    }

    @Override
    public int getItemCount() {
        return mScheduleImages.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{

        CircleImageView scheduleImage;
        TextView scheduleName;
        LinearLayout parentLayout;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            scheduleImage = itemView.findViewById(R.id.schedule_image);
            scheduleName = itemView.findViewById(R.id.schedule_name);
            parentLayout = itemView.findViewById(R.id.parent_layout);

        }
    }

}

我要回收的布局 eachelement.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"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/parent_layout">

    <de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/schedule_image"
        android:layout_width="135dp"
        android:layout_height="131dp"
        android:src="@drawable/watch"
        app:civ_border_color="#FF000000" />

    <TextView
        android:id="@+id/schedule_name"
        android:layout_width="match_parent"
        android:layout_height="131dp"
        android:layout_weight="1"
        android:fontFamily="casual"
        android:gravity="center"
        android:text="@string/scheduleNames"
        android:textSize="18sp"
        android:layout_toRightOf="@+id/schedule_image"/>
</RelativeLayout>

Schedules.java 此类应在下面的片段中回收上面的布局

package com.example.schedule;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;

public class Schedules extends Fragment {


    private static final String TAG = "AddingEvents";

    private ArrayList<String> mScheduleNames = new ArrayList<>();
    private ArrayList<String> mScheduleImageUrls = new ArrayList<>();


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        initImageBitmaps();
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_schedules, container, false);
    }

    private void initImageBitmaps(){
        Log.d(TAG, "initImageBitmaps: preparing image bitmaps.");

        mScheduleNames.add("Steve");
        mScheduleImageUrls.add("https://cdn.arstechnica.net/wp-content/uploads/2016/02/5718897981_10faa45ac3_b-640x624.jpg");

        mScheduleNames.add("Bella");
        mScheduleImageUrls.add("https://www.crockerriverside.org/sites/main/files/imagecache/square/main-images/camera_lense_0.jpeg");

        mScheduleNames.add("Carre");
        mScheduleImageUrls.add("https://upload.wikimedia.org/wikipedia/commons/thumb/5/5b/Ultraviolet_image_of_the_Cygnus_Loop_Nebula_crop.jpg/691px-Ultraviolet_image_of_the_Cygnus_Loop_Nebula_crop.jpg");

        initRecyclerView();
    }

    private void initRecyclerView(){
        Log.d(TAG, "initRecyclerView: init recyclerview.");
        RecyclerView recyclerView = getView().findViewById(R.id.recyclerviews);
        //problem
        RecyclerViewAdapter adapter = new RecyclerViewAdapter(getActivity(), mScheduleNames, mScheduleImageUrls);
        recyclerView.setAdapter(adapter);
        //problem
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    }
}

fragment_schedules.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Schedules"
    android:orientation="vertical">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </androidx.constraintlayout.widget.ConstraintLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/textView2"
                android:layout_width="match_parent"
                android:layout_height="113dp"
                android:fontFamily="casual"
                android:gravity="center"
                android:text="@string/Schedules"
                android:textSize="18sp"
                tools:targetApi="jelly_bean" />

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

            </androidx.recyclerview.widget.RecyclerView>
        </LinearLayout>
    </ScrollView>

</RelativeLayout>

Navigator.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=".Navigator">

    <FrameLayout
        android:id="@+id/fragment_area"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/bottom_navigator">

    </FrameLayout>

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_navigator"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:layout_marginLeft="9dp"
        android:layout_marginRight="9dp"
        android:background="@android:color/darker_gray"
        android:textAlignment="gravity"
        app:menu="@menu/bottom_nav"
        android:layout_alignParentBottom="true">

    </com.google.android.material.bottomnavigation.BottomNavigationView>

</RelativeLayout>

Navigator.java 本课程应该帮助您浏览片段 时间表是片段之一

package com.example.schedule;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import android.os.Bundle;
import android.view.MenuItem;

import com.google.android.material.bottomnavigation.BottomNavigationView;

public class Navigator extends AppCompatActivity {

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

        BottomNavigationView bottom_nav = findViewById(R.id.bottom_navigator);
        bottom_nav.setOnNavigationItemSelectedListener(newListener);

        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_area,
                new Schedules()).commit();
    }

    private BottomNavigationView.OnNavigationItemSelectedListener newListener = new
            BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    Fragment selectedFragment = null;
                    switch (item.getItemId()){
                        case R.id.schedule:
                            selectedFragment = new Schedules();
                            break;
                        case R.id.add:
                            selectedFragment = new AddingEvents();
                            break;
                        case R.id.profile:
                            selectedFragment = new Profile();
                            break;
                    }
                    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_area,
                            selectedFragment).commit();
                    return true;
                }
            };
}

这是我得到的错误

D/AddingEvents: initImageBitmaps: preparing image bitmaps.
    initRecyclerView: init recyclerview.
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.schedule, PID: 16701
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.schedule/com.example.schedule.Navigator}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2572)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2654)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488)
        at android.os.Handler.dispatchMessage(Handler.java:111)
        at android.os.Looper.loop(Looper.java:207)
        at android.app.ActivityThread.main(ActivityThread.java:5763)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
        at com.example.schedule.Schedules.initRecyclerView(Schedules.java:60)
        at com.example.schedule.Schedules.initImageBitmaps(Schedules.java:55)
        at com.example.schedule.Schedules.onCreateView(Schedules.java:38)
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2539)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:875)
        at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1227)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1293)
        at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:710)
        at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2063)
        at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1853)
        at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1808)
        at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1715)
        at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2616)
        at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2572)
        at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:246)
        at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:525)
        at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:176)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1245)
        at android.app.Activity.performStart(Activity.java:6391)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2529)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2654) 
        at android.app.ActivityThread.-wrap11(ActivityThread.java) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488) 
        at android.os.Handler.dispatchMessage(Handler.java:111) 
        at android.os.Looper.loop(Looper.java:207) 
        at android.app.ActivityThread.main(ActivityThread.java:5763) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679) 
I/System: FinalizerDaemon: finalize objects = 81
I/Process: Sending signal. PID: 16701 SIG: 9
Application terminated.

我希望提供提供详细信息的回收时间表 在Schedules.java中,使用initBitmaps()方法 我认为问题是因为我正在使用片段,但我想要回收 不在活动中发生

1 个答案:

答案 0 :(得分:0)

更改为此

public class Schedules extends Fragment
{
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View view = inflater . inflate (R.layout.fragment_schedules, container, false);

        initImageBitmaps();

        RecyclerView recyclerView = view.findViewById (R.id.recyclerviews);

        RecyclerViewAdapter adapter = new RecyclerViewAdapter(getActivity(), mScheduleNames, mScheduleImageUrls);
        recyclerView.setAdapter(adapter);          
        recyclerView.setLayoutManager(new LinearLayoutManager (getActivity()));

        return view;
    }
}