无法启动活动ComponentInfo java.lang.NullPointerException:[duplicate]
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了无法启动活动ComponentInfo java.lang.NullPointerException:[duplicate]相关的知识,希望对你有一定的参考价值。
这个问题在这里已有答案:
在我运行它时编写应用程序后,我得到以下错误
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!
}
}
以上是关于无法启动活动ComponentInfo java.lang.NullPointerException:[duplicate]的主要内容,如果未能解决你的问题,请参考以下文章
无法启动活动 ComponentInfo java.lang.RuntimeException:无法创建 webview
java.lang.RuntimeException:无法启动活动 ComponentInfo。 java.lang.ArrayIndexOutOfBoundsException:长度=7;指数=7
无法启动活动ComponentInfo java.lang.NullPointerException:[duplicate]