ContextCompat.getcolor() going to null object reference

it is because context hasn't been initialized yet. I would recommend you not to have flying references to Context there and there. Activity is a subclass of Context. You can use directly this or NameOfActivity.this to access the context.

int bgColor = ContextCompat.getColor(context, R.color.colorAccent);

should be

int bgColor = ContextCompat.getColor(this, R.color.colorAccent);

You can solve this issue by getting context from the view

testview.setBackgroundColor(ContextCompat.getColor(testview.getContext(), R.color.colorBlack));