【问题标题】:Unable to start activity ComponentInfo java.lang.NullPointerException: [duplicate]无法启动活动 ComponentInfo java.lang.NullPointerException:[重复]
【发布时间】:2017-12-25 07:57:34
【问题描述】:

当我运行应用程序时出现以下错误

Unable to start activity ComponentInfo java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference

这是我的 mainactivity.java 类

public class MainActivity extends AppCompatActivity {

    ArrayList<Contact> contacts;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        RecyclerView rvContacts = findViewById(R.id.rvContacts);
        contacts = Contact.createContactsList(20);
        ContactsAdapter adapter = new ContactsAdapter();items
        rvContacts.setAdapter(adapter);
        rvContacts.setLayoutManager(new LinearLayoutManager(this));
    }
}

【问题讨论】:

    标签: java android nullpointerexception android-adapter


    【解决方案1】:

    你需要像这样投射RecyclerView..

    RecyclerView rvContacts = (RecyclerView)findViewById(R.id.rvContacts);
    

    您还需要致电setContentView(R.id.your_layout) 来设置您的布局。

    【讨论】:

      【解决方案2】:

      您在 MainActivity 的 onCreate 中缺少 setContentView()

      所以在super.onCreate(savedInstanceState);下面添加行setContentView(R.layout.activity_main);校验码

       public class MainActivity extends AppCompatActivity {
      
          ArrayList<Contact> contacts;
      
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);  //change here
      
              RecyclerView rvContacts = findViewById(R.id.rvContacts);
      
              // Initialize contacts
              contacts = Contact.createContactsList(20);
              // Create adapter passing in the sample user data
              ContactsAdapter adapter = new ContactsAdapter();
              // Attach the adapter to the recyclerview to populate items
              rvContacts.setAdapter(adapter);
              // Set layout manager to position the items
              rvContacts.setLayoutManager(new LinearLayoutManager(this));
              // That's all!
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-14
        • 2014-07-18
        • 2017-04-10
        • 2014-05-10
        • 2023-03-25
        • 1970-01-01
        • 1970-01-01
        • 2013-07-05
        相关资源
        最近更新 更多