title: Android: How to initialise a custom View in code and connect it to an existing xml view
body: <p>I have my own custom view class like below:</p>
  <pre><code>public class speak extends ConstraintLayout implements View.OnClickListener {
  
      
      private TextView text;
      private ImageView img;
  
      public speak(Context context, AttributeSet attrs) {
          super(context, attrs);
          TypedArray a = context.getTheme().obtainStyledAttributes(
                  attrs,
                  R.styleable.speak,
                  0, 0);
          try {
              
              text = findViewById(a.getResourceId(R.styleable.speak_text,0));
              img = findViewById(a.getResourceId(R.styleable.speak_img, 0));
  
          } finally {
              a.recycle();
          }
  
      }
  }
  </code></pre>
  <p>With this I created <code>attr.xml</code> where I put this resource:</p>
  <pre><code>&lt;declare-styleable name=&quot;speak&quot;&gt;      
      &lt;attr name=&quot;text&quot; format=&quot;string&quot;/&gt;
      &lt;attr name=&quot;img&quot; format=&quot;reference&quot;/&gt;
  &lt;/declare-styleable&gt;
  </code></pre>
  <p>and I also created my own layout xml of how the custom view should look. This way I can add  multiple views easily in <code>activity_main.xml</code>. I started by adding one view in <code>activity_main.xml</code>. But now I want to link it to the custom view class in <code>onCreate</code>. what I am doing is this:</p>
  <pre><code>@Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      speak sl =  findViewById(R.id.ss);
      sl.seImage(getResources().getIdentifier(&quot;com.example.app:drawable/img.png&quot;, null, null));
  }
  </code></pre>
  <p>where <code>setImage</code> is my own setter for the components in the customView. However, this is returning a <code>null pointer exception</code> which I think I understand since I am not creating a new <code>speak</code> Object and passing attributes in the constructor and so on.</p>
  <p>create a new view object but at the same time pass it the xml element which sets its position on screen apart form other stuff.</p>
  <p>I am also not sure what should I pass to <code>AttributeSet</code> in the constructor.</p>
  <h1>udpate</h1>
  <p>this is the error:</p>
  <pre><code>java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
  </code></pre>
  <p>This is because my setter contains img.SetImageResource(int) to get a drawable Id and set te image to that image in drawable folder</p>