-2

It's a simple gallery program. I've cut the code to just necessary parts needed to answer the question. My question is why context is not initialized and then how to know what the context reference is in the code below?

public class GalleryActivity extends Activity { 

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);        
    gallery.setAdapter(new ImageAdapter(this));
    gallery.setOnItemClickListener(new OnItemClickListener()
    {
        public void onItemClick(AdapterView<?> parent, View v,
        int position, long id)
        {
            myImageView.setImageResource(imageIDs[position]);
        }
    });
}

public class ImageAdapter extends BaseAdapter
{
    Context context;
    public ImageAdapter(Context c)
    {
        context = c;   
    }

    public View getView(int position, View convertView, ViewGroup parent) {

        ImageView imageView = new ImageView(context);
        imageView.setImageResource(imageIDs[position]);
        return imageView;
    }
  }
}
hayden
  • 29
  • 5
  • Before, it may be of some help to understand *what* is Context. You may therefore be interested in reading this: http://stackoverflow.com/questions/3572463/what-is-context-in-android – GMax Sep 07 '15 at 21:10

2 Answers2

1

The context is not initialized because when you instatiate the ImageAdapter class you have to set the context, for example:

ImageAdapter myImageAdapter = new ImageAdapter(getApplicationContext());

then inside of the ImageAdapter Class you will make use of the context variable:

  ImageView imageView = new ImageView(context);
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Jorgesys
  • 124,308
  • 23
  • 334
  • 268
0

In your code,you have:

new ImageAdapter(this);

this refers to the current class, GalleryActivity. GalleryActivity is an Activity, and Activity is a subclass of Context. So, you are calling the ImageAdapter constructor with a Context. Then, in your constructor you store a reference to that Context, context = c. In fact, context now points to a Context, which is an Activity.

You don't need to explicitly instantiate Context, because the Android system has already given you a valid Activity instance, and since Activity is a type of Context, you have a valid Context.

vman
  • 1,264
  • 11
  • 20
  • So in the line : ImageView imageView = new ImageView(context); imageViews are being built inside activity? or gallery? – hayden Sep 08 '15 at 07:19
  • Well, once GalleryActivity is running, the `gallery`'s image adapter is set. Then based on what portion of the gallery is showing, getView will be called with the view that needs to be displayed. At that point the image view is created and the image set to that view. You should know that gallery is of type Gallery, which is also an AdapterView. There are some guides online regarding ListView which could prove useful to you – vman Sep 08 '15 at 21:28