无法启动活动ComponentInfo java.lang.NullPointerException:[duplicate]

问题描述 投票:-1回答:2

这个问题在这里已有答案:

在我运行它时编写应用程序后,我得到以下错误

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!
    }
}
java android nullpointerexception android-adapter
2个回答
1
投票

你需要像这样投射RecyclerView ..

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

而且你还需要调用setContentView(R.id.your_layout)来设置你的布局。


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!
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.