在我运行应用程序后编写应用程序时出现以下错误
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!
}
}
答案 0 :(得分:1)
你需要像这样投射RecyclerView
..
RecyclerView rvContacts = (RecyclerView)findViewById(R.id.rvContacts);
您还需要致电setContentView(R.id.your_layout)
来设置布局。
答案 1 :(得分:0)
您在setContentView()
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!
}
}