【问题标题】:Nullpointerexception on RecyclerViewRecyclerView 上的空指针异常
【发布时间】:2021-01-22 04:06:23
【问题描述】:

我想要做的就是在 tablayout 中创建一个 recyclerview 我已经尝试在主要活动中设置适配器以及我在 tablayout 中使用的片段但是无论哪种方式我仍然得到这个错误

java.lang.RuntimeException:无法启动活动 ComponentInfo{knightsrealms.managment_app/knightsrealms.managment_app.Dashboard}:java.lang.NullPointerException:尝试调用虚拟方法 'void android.support.v7.widget.RecyclerView.setAdapter (android.support.v7.widget.RecyclerView$Adapter)' 在空对象引用上

package knightsrealms.managment_app;

import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;

import java.util.ArrayList;
import java.util.Calendar;

public class Dashboard extends AppCompatActivity {

private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPageAdapter viewPagerAdapter;
ArrayList<knightsrealms.managment_app.Calendar> contacts = new             ArrayList<knightsrealms.managment_app.Calendar>(5);

@Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dashboard);
    tabLayout = (TabLayout) findViewById(R.id.tabs);
    viewPager = (ViewPager) findViewById(R.id.viewpager);
    Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
    viewPagerAdapter = new ViewPageAdapter(getSupportFragmentManager());
    viewPager.setAdapter(viewPagerAdapter);
    final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    setSupportActionBar(toolbar);



    final TabLayout.Tab messages = tabLayout.newTab();
    final TabLayout.Tab dashboard = tabLayout.newTab();

    messages.setText("Messages");
    dashboard.setText("Dashboard");

    tabLayout.addTab(dashboard, 0);
    tabLayout.addTab(messages, 1);

    tabLayout.setTabTextColors(ContextCompat.getColorStateList(this, R.color.tab_selector));
    tabLayout.setSelectedTabIndicatorColor(ContextCompat.getColor(this, R.color.indicator));
    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
            RecyclerView rvContacts = (RecyclerView)findViewById(R.id.rvcal);


    contacts.add(0, new knightsrealms.managment_app.Calendar("Number 1",true));
    contacts.add(1, new knightsrealms.managment_app.Calendar("Number 2",true));
    CalendarAdapter adapter = new CalendarAdapter(contacts);


    rvContacts.setAdapter(adapter);
    rvContacts.setLayoutManager(new LinearLayoutManager(this));
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.dashboard_menu, menu);
    return true;
}

void selectPage(int pageIndex){
    tabLayout.setScrollPosition(pageIndex,0f,true);
    viewPager.setCurrentItem(pageIndex);
}
}

这是我的适配器

package knightsrealms.managment_app;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import java.util.List;

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

    // Provide a direct reference to each of the views within a data item
    // Used to cache the views within the item layout for fast access
    public static class ViewHolder extends RecyclerView.ViewHolder {
        // Your holder should contain a member variable
        // for any view that will be set as you render a row
        public TextView nameTextView;
        public Button messageButton;

        // We also create a constructor that accepts the entire item row
        // and does the view lookups to find each subview
        public ViewHolder(View itemView) {
            // Stores the itemView in a public final member variable that can be used
            // to access the context from any ViewHolder instance.
            super(itemView);

            nameTextView = (TextView) itemView.findViewById(R.id.contact_name);
            messageButton = (Button) itemView.findViewById(R.id.message_button);
        }

    }

private List<Calendar> mContacts;

    // Pass in the contact array into the constructor
    public CalendarAdapter(List<Calendar> contacts) {
    mContacts = contacts;
    }

// Usually involves inflating a layout from XML and returning the holder
@Override
public CalendarAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    Context context = parent.getContext();
    LayoutInflater inflater = LayoutInflater.from(context);

    // Inflate the custom layout
    View contactView = inflater.inflate(R.layout.recyclercell, parent, false);

    // Return a new holder instance
    ViewHolder viewHolder = new ViewHolder(contactView);
    return viewHolder;
}

// Involves populating data into the item through holder
@Override
public void onBindViewHolder(CalendarAdapter.ViewHolder viewHolder, int position) {
    // Get the data model based on position
    Calendar contact = mContacts.get(position);

    // Set item views based on the data model
    TextView textView = viewHolder.nameTextView;
    textView.setText(contact.getName());

    Button button = viewHolder.messageButton;

    if (contact.isOnline()) {
        button.setText("Message");
        button.setEnabled(true);
    }
    else {
        button.setText("Offline");
        button.setEnabled(false);
    }

}

// Return the total count of items
@Override
public int getItemCount() {
    return mContacts.size();
}
}

此代码适用于 tablayout 内的片段

<android.support.v7.widget.RecyclerView
android:id="@+id/rvcal"
android:layout_width="match_parent"
android:layout_height="match_parent" />

</RelativeLayout>

这是主要的活动 xml

<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"
xmlns:app="http://schemas.android.com/apk/res-auto">

<include
android:id="@+id/tool_bar"
layout="@layout/tool_bar"
></include>

<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:layout_below="@+id/tool_bar"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
app:tabIndicatorHeight="3dp"/>

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

</RelativeLayout>

非常感谢您对此的任何见解/帮助!

【问题讨论】:

  • 这一行viewPager.setAdapter(viewPagerAdapter); 产生错误,导致viewPager 为空。请分享您的 xml,以便我们查看您在那里做了什么以及错误在哪里。
  • @Vucko 我刚刚用 xml 更新了问题
  • 你说这个xml是main_activity.xml,但是在你的Dashboard活动中你是setContentView(R.layout.activity_dashboard);。我想也许你正试图在错误的活动中访问 viewpager。你能检查一下吗?什么是 MainActivity,什么是 Dasboard?

标签: nullpointerexception android-recyclerview


【解决方案1】:

您是否已经尝试过:

tabLayout.setupWithViewPager(viewPager);

因为 recyclerView 在您的片段 xml 中而不是在您的活动 xml 中,因此 recyclerView 返回 null。 好的,所以你的代码差不多完成了,但你还需要做 2 件事:

  • 首先,是一个为您的 ViewPager 扩展 FragmentPagerAdapter 的类,我不知道您的 ViewPageAdapter 类是否已经这样做了,但我们假设您还没有这样做。
  • 第二个,是您的 FragmentPagerAdapter 的片段。

好的,让我们开始吧:

  1. 为 FragmentPagerAdapter 创建 FragmentContacts,在这个 Fragment 中你应该管理你的 RecyclerView,它的适配器不在 Activity 中。

    public class FragmentContacts extends Fragment {
      ArrayList<knightsrealms.managment_app.Calendar> contacts = new ArrayList<knightsrealms.managment_app.Calendar>(5);
    
      @Nullable
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
          View rootView = (View) inflater.inflate(R.layout.your_fragment_xml, container, false);
    
          contacts.add(0, new knightsrealms.managment_app.Calendar("Number 1",true));
          contacts.add(1, new knightsrealms.managment_app.Calendar("Number 2",true));
          CalendarAdapter adapter = new CalendarAdapter(contacts);
    
          RecyclerView rvContacts = (RecyclerView) rootView.findViewById(R.id.rvcal);
          rvContacts.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
          rvContacts.setAdapter(adapter);
    
          return rootView;
      }
    
    }
    
  2. 最后,回到您的 Dashboard Activity 中,在 onCreate 中,设置您的 Viewpager:

    @Override protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_dashboard);
      Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
    
      viewPager = (ViewPager) findViewById(R.id.viewpager);
      viewPagerAdapter = new ViewPageAdapter(getSupportFragmentManager());
    
      viewPager.setAdapter(viewPagerAdapter);
    
      tabLayout = (TabLayout) findViewById(R.id.tabs);
      tabLayout.setupWithViewPager(viewPager);
      viewPager.setCurrentItem(0);   
    }
    

    公共类 ViewPagerAdapter 扩展 FragmentPagerAdapter { 公共 ViewPagerAdapter(FragmentManager fragmentManager) { 超级(片段管理器); }

      @Override
      public Fragment getItem(int position) {
          if(position == 0) return new FragmentContacts();
          if(position == 1) return new FragmentContacts();
    
          throw new IllegalStateException("Unexpected position " + position);
      }
    
      @Override
      public int getCount() {
          return 2;
      }
    
      @Override
      public CharSequence getPageTitle(int position) {
          if(position == 0) return "Messages";
          if(position == 1) return "Dashboard";
    
          throw new IllegalStateException("Unexpected position " + position);
      }
    

    }

【讨论】:

  • 我把它放在哪里?我在设置适配器调用之前和之后尝试过,但结果相同
  • 等待我现在正在编辑我的答案.. :) 我还不能添加评论,当我第一次发布这个答案时
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-16
  • 2020-05-25
  • 2021-01-19
  • 2019-07-18
  • 2013-08-12
相关资源
最近更新 更多