这个问题在这里已有答案:
在我运行它时编写应用程序后,我得到以下错误
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!
}
}
你需要像这样投射RecyclerView
..
RecyclerView rvContacts = (RecyclerView)findViewById(R.id.rvContacts);
而且你还需要调用setContentView(R.id.your_layout)
来设置你的布局。
你在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!
}
}