Android. RecyclerView. Error class inheritance: ... by reference to null object

There is a base class. I've dropped too much for the sake of brevity. At the beginning of this action, everything works.

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);
    }
}

      

expanded

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);
    }
}

      

When you go to the News screen, blank, click Get:

E / InputEventReceiver: Exception dispatching an input event. E / MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback E / MessageQueue-JNI: java.lang.NullPointerException: Attempting to call virtual method "boolean android.support.v7.widget.RecyclerView $ LayoutManager.canScrollVertically ()" on null object reference

Where am I going wrong?

+3


source to share


1 answer


you have to provide a layout manager to your recylcerview add the following right after

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



and it won't work

LinearLayoutManager layoutManager = new LinearLayoutManager(context);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
rv.setLayoutManager(layoutManager);

      

+2


source







All Articles