Osman
Osman

Reputation: 1771

Why am I getting "The method getContext() is undefined for the type MainActivity"?

My MainActivity extends activity and I use getContext() in another class that has a instance of MainActivity passed in and it works fine there, my code:

convertView = LayoutInflater.from(parent.getContext())
                            .inflate(R.layout.nowview, parent, false);

Class constructor:

public PictureCard(String url, String title, int index,
                                             int pos, MainActivity parent)
{
    this.parent = parent;
    // ...
}

How I call the class

Card newCard = new PictureCard(links.get(index) , titles.get(index),
                                                  index, position, parent);

(Parent is passed in as this from the MainActivity class)

Upvotes: 4

Views: 15382

Answers (3)

Eng.Fouad
Eng.Fouad

Reputation: 117597

If MainActivty extends Activty, then just use parent as the context:

convertView = LayoutInflater.from(parent)
                        .inflate(R.layout.nowview, parent, false);

Also, I suspect that you're passing the wrong instance here:

Card newCard = new PictureCard(links.get(index) , titles.get(index),
                                              index, position, parent);
                                                               ^^^^^^

it should be this, or MainActivty.this if it's within an inner class.

Upvotes: 0

stinepike
stinepike

Reputation: 54682

Instead of passing MainActivity you can pass context as parameter lik this

public PictureCard(String url, String title, int index, int pos, Context parent)

and call like

Card newCard = new PictureCard(links.get(index) , titles.get(index), index, position, MainActivity.this);

Upvotes: 0

Related Questions