0

I have been trying to add relative layouts to a linear layout inside a scroll view in android-studio.

It kept giving me an error:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.addView(android.view.View)' on a null object reference

I thought maybe I can't add it to the scroll view because of so many layouts. So I removed everything and created a small code like so:

public class ChildAccountsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.child_accounts_activity);

        LinearLayout linearLayout = findViewById(R.id.accountHolder);

        Button myButton = new Button(this);
        myButton.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT));

        linearLayout.addView(myButton);  <<--ERROR HERE
}

Here I am just trying to add a button to the linear layout, but it keeps giving me the error mentioned above.

Any guidance will be appreciated and please keep in mind that I'm new to programming and very likely don't know what I'm doing. Thanks for your time :D

Swati
  • 23,244
  • 4
  • 14
  • 34
dr_nyt
  • 155
  • 1
  • 7
  • 1
    Post your layout file for the small code – Jude Osbert K Jun 25 '19 at 13:04
  • Looks as if you don't have a `LinearLayout` with the id `accountHolder` in your `child_accounts_activity.xml` layout file. Then `findViewById(R.id.accountHolder);` returns `null`. – Markus Kauppinen Jun 25 '19 at 13:06
  • 1
    @MarkusKauppinen that was technically the problem. I had multiple layouts for different screen sizes and was referencing the wrong one. – dr_nyt Jun 26 '19 at 12:23

2 Answers2

0

Instead of this

Button myButton = new Button(this);

Try this

Button myButton = (Button) findViewById(R.id.HERE_YOUR_VIEW_ID);
Boris Ruzanov
  • 1,684
  • 1
  • 8
  • 21
  • Thank you for taking the time to answer this, but I found the problem. I had multiple layouts created for different phone sizes and was probably referencing the wrong layout. – dr_nyt Jun 26 '19 at 12:21
0

I had multiple layouts created for different screen sizes and that created issues when referencing. I fixed it by deleting all the extra layouts, but there is probably a better way to fix this.

dr_nyt
  • 155
  • 1
  • 7