4

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)

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
Osman
  • 1,771
  • 4
  • 24
  • 47

3 Answers3

4

Have you tried using getApplicationContext() instead of getContext()?

These links might help:

http://developer.android.com/reference/android/app/Activity.html

getApplication() vs. getApplicationContext()

Difference between getContext() , getApplicationContext() , getBaseContext() and "this"

Community
  • 1
  • 1
paulsm4
  • 114,292
  • 17
  • 138
  • 190
  • Same issue "The method getActivityContext() is undefined for the type MainActivity" – Osman May 18 '13 at 05:50
  • all forms of getcontext result in some kind of error, weird this is i run the same code in another class with the same pass in and declaration of parent, and it works? – Osman May 18 '13 at 05:59
0

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);
stinepike
  • 54,068
  • 14
  • 92
  • 112
  • I think i will try that, I am just baffled to why what I am doing is working in one class and not another – Osman May 18 '13 at 05:59
0

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.

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • then I get "The method inflate(int, ViewGroup, boolean) in the type LayoutInflater is not applicable for the arguments (int, MainActivity, boolean)" – Osman May 18 '13 at 05:54
  • sorry I realized I misspoke I call this class from a class that is called by MainActivity, but still why would eclipse give me this error, I created the var correctly – Osman May 18 '13 at 05:56