Android Activity Context is Null

后端 未结 5 1141
天涯浪人
天涯浪人 2021-01-27 09:49

So I have these Codes here, It runs without crashing. However When I pass \"this\" into the gridadapter the mContext is null. I tried to pass getApplicationContext() through but

5条回答
  •  走了就别回头了
    2021-01-27 10:02

    Try below code or use getFragmentManager() or getParent();

    public class ChampionInfo extends FragmentActivity {
    
    GridView gridtable;
    
    Context ctx;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_champion_info);
        ctx=ChampionInfo.this;//getFragmentManager() or getParent()
        gridtable = (GridView) findViewById(R.id.gridtable);        
        gridtable.setAdapter(new GridAdapter(ctx));
    
    }
    
    public class GridAdapter extends BaseAdapter {
        private Context mContext;
    
        String[] list = getResources().getStringArray(R.array.championlist);
    
        int[] champImage = getImage();
    
        public int[] getImage() {
    
            int[] tempImage = new int[list.length];
    
            for (int i = 0; i < list.length; i++) {
                tempImage[i] = getResources().getIdentifier(list[i],
                        "drawable", getPackageName());
            }
    
            return tempImage;
    
        }
    
        // Constructor
        public GridAdapter(Context c) {
    
            mContext = c;
    
        }
    
        public int getCount() {
            return champImage.length;
        }
    
        public Object getItem(int position) {
            return null;
        }
    
        public long getItemId(int position) {
            return 0;
        }
    
        // create a new ImageView for each item referenced by the Adapter
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            if (convertView == null) {
                imageView = new ImageView(mContext);
                imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setPadding(8, 8, 8, 8);
    
            } else {
                imageView = (ImageView) convertView;
            }
    
            imageView.setImageResource(champImage[position]);
            return imageView;
        }
    
        // Keep all Images in array
    
    }
    }
    

提交回复
热议问题