ContextCompat.getcolor() going to null object reference

会有一股神秘感。 提交于 2020-01-14 09:37:11

问题


I'm getting error when I set color to SlidingTabLayout object. Here is my mainActivity, first I found that getResource.getColor is deprecated. So I used contextCompat.getColor. But now its going to null.

public class MainActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private ViewPager mPager;
    private SlidingTabLayout mTabs;
    private MyPagerAdapter adapter;
     Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar = (Toolbar) findViewById(R.id.app_bar);
        mPager = (ViewPager) findViewById(R.id.pager);
        mTabs = (SlidingTabLayout) findViewById(R.id.tabs);

        setSupportActionBar(toolbar);
        assert getSupportActionBar() != null;
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        NavigationDrawerFragment navigationDrawerFragment = (NavigationDrawerFragment)
                getSupportFragmentManager().findFragmentById(R.id.fragment_nav_drawer);
        navigationDrawerFragment.setUp(R.id.fragment_nav_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);

        adapter = new MyPagerAdapter(getSupportFragmentManager(),MainActivity.this);
        mPager.setAdapter(adapter);
        mTabs.setViewPager(mPager);
        mTabs.setDistributeEvenly(true);

        int bgColor = ContextCompat.getColor(context,R.color.colorAccent);
        mTabs.setBackgroundColor(bgColor);
        mTabs.setSelectedIndicatorColors(ContextCompat.getColor(context, R.color.colorAccent));
        mTabs.invalidate();
        mTabs.setCustomTabView(R.layout.custom_tab_view,R.id.tabText);
    }


    @Deprecated
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Deprecated
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {

            return true;
        }
        if (id == R.id.navigate) {
            startActivity(new Intent(this, SubActivity.class));
        }

        return super.onOptionsItemSelected(item);
    }

    public static class MyFragment extends Fragment {
        private TextView textView;

        public static MyFragment getInstance(int position) {
            MyFragment myFragment = new MyFragment();
            Bundle args = new Bundle();
            args.putInt("position", position);
            myFragment.setArguments(args);
            return myFragment;
        }


        @Override
        public View onCreateView(LayoutInflater inflater,@Nullable ViewGroup container, Bundle savedInstanceState) {
            View layout = inflater.inflate(R.layout.fragment_my, container, false);
            textView = (TextView) layout.findViewById(R.id.position);
            Bundle bundle = getArguments();
            if (bundle != null) {
                textView.setText(bundle.getInt("position"));
            }
            return layout;
        }
    }

    class MyPagerAdapter extends FragmentStatePagerAdapter {
        Context mContext;
        int icons[] = {R.drawable.home,R.drawable.hot_article,R.drawable.dizzy_person};
        String[] tabText = getResources().getStringArray(R.array.tabs);
        public MyPagerAdapter(FragmentManager fm,Context context ) {
            super(fm);
            this.mContext = context;

        }

        @Override
        public Fragment getItem(int position) {
            MyFragment myFragment = MyFragment.getInstance(position);
            return myFragment;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Drawable drawable = ResourcesCompat.getDrawable(getResources(),icons[position],null);
            drawable.setBounds(0, 0, 36, 36);
            ImageSpan imageSpan = new ImageSpan(drawable);
            SpannableString spannableString = new SpannableString(" ");
            spannableString.setSpan(imageSpan,0,spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            return spannableString;
        }

        @Override
        public int getCount() {
            return 3;
        }
    }
}

Is there any new method in marshmallow to solve this problem?


回答1:


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



回答2:


You can solve this issue by getting context from the view

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



回答3:


change context to MainActivity.this

use this way

int bgColor = ContextCompat.getColor(MainActivity.this,R.color.colorAccent);
mTabs.setBackgroundColor(bgColor);
mTabs.setSelectedIndicatorColors(ContextCompat.getColor(MainActivity.this, R.color.colorAccent));



回答4:


Use ContextCompat.getColor(context, R.color.color_name) and check whether your context is null or your color_name value actually exists




回答5:


Its an Activity. so we can use,

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

in case of Fragment we can use,

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



回答6:


If you are trying to modify a view based on an asynchronous database call you might want to pass the context to the method which executes the database call you might even follow this

  private void dbCall(Activity activity){

      // perform the database call 
      int bgColor = ContextCompat.getColor(activity,R.color.colorAccent);

}


来源:https://stackoverflow.com/questions/35624743/contextcompat-getcolor-going-to-null-object-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!