我不确定为什么,但是它带有 java.lang.RuntimeException:无法启动活动ComponentInfo {krispo.callie / krispo.callie.MainActivity}:java.lang.NullPointerException:尝试调用虚对象上的虚拟方法'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView $ LayoutManager)'
错误。我尝试添加LinearLayoutManager是因为我认为这是我阅读的另一篇文章的解决方案。谁能帮我谢谢
public class MainActivity extends AppCompatActivity {
FloatingActionButton FAB;
List<Contact> contactsList;
private RecyclerView recyclerView;
private ContactAdapter contactAdapter;
private String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactsList = new ArrayList<>();
recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
contactsList.add(new Contact("Bob","123456789","1", true));
contactsList.add(new Contact("Jo","987654321","2",true));
contactAdapter = new ContactAdapter(contactsList);
final LinearLayoutManager layoutManager = new LinearLayoutManager(this.getApplicationContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(contactAdapter);
FAB = (FloatingActionButton)findViewById(R.id.floatingActionButton);
FAB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this,NumberActivity.class);
startActivity(i);
}
});
}
}
答案 0 :(得分:1)
最有可能的错误是您为recyclerview使用了错误的ID,该ID与activity_main.xml
中声明的ID不同
在设置适配器之前,先设置LinearLayoutManager
,如下所示,并确保activity_main
中的recyclerview的ID为recycler_view
public class MainActivity extends AppCompatActivity {
FloatingActionButton FAB;
List<Contact> contactsList;
private RecyclerView recyclerView;
private ContactAdapter contactAdapter;
private String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactsList = new ArrayList<>();
recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
final LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
contactsList.add(new Contact("Bob","123456789","1", true));
contactsList.add(new Contact("Jo","987654321","2",true));
contactAdapter = new ContactAdapter(contactsList);
recyclerView.setAdapter(contactAdapter);
FAB = (FloatingActionButton)findViewById(R.id.floatingActionButton);
FAB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this,NumberActivity.class);
startActivity(i);
}
});
}
}