Michael A
Michael A

Reputation: 5840

Null Pointer exception when trying to call getLayoutInflater

In class socialNetworksActivity i have a method:

public void getResultFromFBPost(String result)
{
  if (result.equals("SUC"))
    ShowToast("Your message have been posted successfully", Toast.LENGTH_LONG);
  else
    ShowToast("There was an error posting,"
        + " please check your Internt connection", Toast.LENGTH_LONG);
}

Which calls this method (also in class socialNetworksActivity):

public void ShowToast(String message, int duration)
{
    LayoutInflater inflater = getLayoutInflater();
          ....
}

When I call this method from inside the class it works fine.

But when I call this method from class B like this:

@Override
protected void onPostExecute(String result)
{
  socialNetworksActivity.getResultFromFBPost(result);
  pd.dismiss();
}

I get a NullPointerException when code get to:

LayoutInflater inflater = getLayoutInflater();

Any idea why?

Upvotes: 2

Views: 1349

Answers (2)

Igor Čordaš
Igor Čordaš

Reputation: 5954

I think it's a problem with calling it from async task. Call it from the Activity or if you don't want to do that pass activity context into AsyncTask and call it on that object. Also be sure to call it on the UI thread (althou you are already doing that by using onPostExecute but just keep that in mind).

Upvotes: 1

SDJMcHattie
SDJMcHattie

Reputation: 1699

I'm not sure why the LayoutInflater is coming back null but another way to get the LayoutInflater is to simply call LayoutInflater.from(this) or, if this isn't a Context, some other Context, maybe by using the method getContext() or getApplicationContext() depending on the class you're in.

Upvotes: 1

Related Questions