无法启动活动ComponentInfo java.lang.NullPointerException:

时间:2017-12-25 07:57:35

标签: java android nullpointerexception android-adapter

在我运行应用程序后编写应用程序时出现以下错误

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);

        // 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!
    }
}

2 个答案:

答案 0 :(得分:1)

你需要像这样投射RecyclerView ..

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

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

答案 1 :(得分:0)

您在setContentView()

的onCreate中遗失了MainActivity

所以在setContentView(R.layout.activity_main);检查代码

下面添加行super.onCreate(savedInstanceState);
 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!
    }
}