Android中的Recycleview无法启动活动错误

时间:2017-01-11 13:27:38

标签: android android-layout android-recyclerview

我正在使用RecycleView开发应用程序。我收到了一条错误消息

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.appname/com.app.appname.SpeedDialViewActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference

我的代码如下所示。

SpeedDialViewActivity.java

public class SpeedDialViewActivity extends AppCompatActivity {

private List<Bean> beanList = new ArrayList<>();
private RecyclerView recyclerView;
private ViewAdapter mAdapter;
Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_speed_dial_view);
    mAdapter = new ViewAdapter(beanList);
    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(mAdapter);
    prepareData();
}

private void prepareData() {

    DatabaseHandler handler = new DatabaseHandler(getApplicationContext());
    Log.d("Reading: ", "Reading all contacts..");
    List<Bean> contacts = handler.getAllContacts();
    for (Bean cn : contacts) {
        String log = "Id: " + cn.getId() + " ,Name: " + cn.getName() + " ,Phone: " + cn.getNumber();
        // Writing Contacts to log
        //Log.d("Name: ", log);

        cn = new Bean(cn.getName(), cn.getNumber(), cn.getSpeeddial());
        beanList.add(cn);

    }

}
}

错误发生在

    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(mLayoutManager);

我不知道如何解决错误。

2 个答案:

答案 0 :(得分:1)

您刚刚错过了recyclerView的findViewById

recyclerView = (RecyclerView) findViewById(R.id.your_recyclerview_id);

答案 1 :(得分:-1)

我错过了 recyclerView =(RecyclerView)findViewById(R.id.your_recyclerview_id);