Question: I'm pretty new to android programming. And now, I'm trying to create a ImageView programmatically. But not in the MainActivity, but in a second class I created.

Here's my code:

```
package com.example.joystick;

import android.app.Activity;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

public class Joystick extends Activity{

    ImageView imView;
    RelativeLayout Layout;

public void create(int x, int y, RelativeLayout layout) {
    Layout = layout;
    imView = new ImageView(this);
    imView.setImageResource(R.drawable.joystickknuppel);
    LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    params.setMargins(x, y, 0, 0);
    imView.setLayoutParams(params);

    Layout.addView(imView);
    }

}

```

If I load the app to my device, it crashes. But if I copy the "create" method into MainActivity, it works well.

Can someone tell me why this happens, and how to fix it?

Thanks a lot!

Answer: 
Replace this method with this code...`onCreateView(...)`

```
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    Layout = layout;
imView = new ImageView(this);
imView.setImageResource(R.drawable.joystickknuppel);
params.setMargins(x, y, 0, 0);
imView.setLayoutParams(params);

Layout.addView(imView);

    return view;
}

```

Don't forget to initialize the Layout `Layout`
Call this create method from onCreate and send layout as a parameter to this function. Actually you are trying to access the view that is not registered yet. So in this case you will get null pointer exception.