问题
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();
回答1:
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
回答2:
Activity extends from Context that means you just need LayoutInflater inflater = LayoutInflater.from(this); in your onCreate() method.
来源:https://stackoverflow.com/questions/17429205/nullpointer-on-layoutinflater-android