Android. RecyclerView. 错误类继承:...在空对象引用上

3

有一个基础类,为了简洁起见,我添加了太多内容。在这个活动开始时一切都正常运作。

public class MainActivity extends DrawerActivity {
    protected Activity activity = this;
    protected class GetDataFromMongoDb extends AsyncTask<String, Integer, ArrayList<CurrentNewsItem>> {
        protected ArrayList<CurrentNewsItem> doInBackground(String... provider) {
            //put data in array for adapter
        }
        protected void onPostExecute(final ArrayList<CurrentNewsItem> result) {
            adapter = new RecyclerAdapter(result);
            StaggeredGridLayoutManager llm = new StaggeredGridLayoutManager(UtilsScreen.getDisplayColumns((Activity) activity), StaggeredGridLayoutManager.VERTICAL);
            rv.setLayoutManager(llm);
            rv.setAdapter(adapter);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentView = inflater.inflate(R.layout.activity_main, null, false);
        mDrawer.addView(contentView, 0);

        CurrentSection = ("news");
        rv = (RecyclerView)findViewById(R.id.rv_main);
        new GetDataFromMongoDb().execute(CurrentSection);
    }
}

扩展

public class News extends MainActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentView = inflater.inflate(R.layout.activity_news, null, false);
        mDrawer.addView(contentView, 0);

        CurrentSection = getIntent().getExtras().getString("section");
        rv = (RecyclerView)findViewById(R.id.rv);
        new GetDataFromMongoDb().execute(CurrentSection);
    }
}

当您进入新闻屏幕时,屏幕是空白的,点击后会出现错误:

E/InputEventReceiver: 异常派发输入事件。E/MessageQueue-JNI: 消息队列中的异常回调:handleReceiveCallback E/MessageQueue-JNI: java.lang.NullPointerException: 尝试在null对象引用上调用'boolean android.support.v7.widget.RecyclerView$LayoutManager.canScrollVertically()'方法

我哪里出错了?


有解决方案吗? - Alan Godoi
你找到任何解决方案了吗? - mfaisalhyder
1个回答

2
你必须为你的RecyclerView提供布局管理器。 在

之后添加以下内容:

rv = (RecyclerView)findViewById(R.id.rv);

这样它将不会崩溃。
LinearLayoutManager layoutManager = new LinearLayoutManager(context);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
rv.setLayoutManager(layoutManager);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接