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: 
Is Joystick an Activity?? If not, you don't need to extend Activity instead pass a reference of your current activity and then use it inside your create method.
Here's how.

```
public class Joystick {

    ImageView imView;
    RelativeLayout Layout;
    Activity activity;

    public JoyStick(Activity activity)
    {
    this.activity=activity;
    }

    public void create(int x, int y, RelativeLayout layout) {
     Layout = layout;
    //here's the change
     imView = new ImageView(activity);
     imView.setImageResource(R.drawable.joystickknuppel);
     LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutPa rams.WRAP_CONTENT);
     params.setMargins(x, y, 0, 0);
     imView.setLayoutParams(params);
     Layout.addView(imView);
    }

}

```

From your MainActivity you can acces it via.

```
JoyStick joyStick=new JoyStick(this);
//add your params
joystick.create(x,y,relativeLayout);

```
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.