Reputation: 3102
I have a class in another java file that I'm calling in my MainActivity. I need to inflate some layouts in the external class. The problem I'm having is specifying the context, because when I try to inflate the layouts I get a Null Pointer Exception. The class doesn't have it's own onCreate()
method so I need to pass the context from my MainActivity? Not sure how to go about it. This is causing me the NullPointerException
:
Context context = getApplicationContext();
LayoutInflater inflater = (LayoutInflater)context.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);;
NullPointerException
on Context
context:
public class CameraListener extends Activity implements OnCameraChangeListener {
private static final int SCALE_HEIGHT = 50;
GoogleMap mMap;
GoogleC3iActivity mParent;
Context context = getApplicationContext();
Upvotes: 0
Views: 1181
Reputation: 9574
Multiple Issues
First
Context context = getApplicationContext();
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
You shouldn't need the getApplicationContext(), since you already have it.
OR (credits : @Delyan)
LayoutInflater.from(context)
Second
Context context = getApplicationContext();
does not work before setContentView
. So you need to initialize context after you call setContentView
in your onCreate
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
context = getApplicationContext() ;
Same goes for LayoutInflater
, you need to initialize it in the onCreate
Upvotes: 2
Reputation: 57672
Activity
extends from Context
that means you just need LayoutInflater inflater = LayoutInflater.from(this);
in your onCreate()
method.
Upvotes: 0