Search code examples
androidnullpointerexceptionimagebuttonlayoutparams

Null Pointer Exception when setting LayoutParams


I created button in activity programmaticaly, not in xml file. Then I wanted to set it LayoutParams like in this link: How to programmatically set the layout_align_parent_right attribute of a Button in Relative Layout?

But when I tried to launch, I had an exception.

Here is my code:

RelativeLayout ll2 = new RelativeLayout(this);
    //ll2.setOrientation(LinearLayout.HORIZONTAL);

    ImageButton go = new ImageButton(this);
    go.setId(cursor.getInt(cursor.getColumnIndex("_id")));
    go.setClickable(true);
    go.setBackgroundResource(R.drawable.go);
    RelativeLayout.LayoutParams params1 = (RelativeLayout.LayoutParams)go.getLayoutParams();
    params1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); // LogCat said I have Null Pointer Exception in this line
    go.setLayoutParams(params1);
    go.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i3 = new Intent(RecipesActivity.this, MedicineActivity.class);
            i3.putExtra(ShowRecipe, v.getId());
            i3.putExtra("Activity", "RecipesActivity");
            RecipesActivity.this.startActivity(i3);
        }
    });
    ll2.addView(go);

Why my app throws an exception? Thanks.


Solution

  • Change this:

    RelativeLayout.LayoutParams params1 = (RelativeLayout.LayoutParams)go.getLayoutParams();
    params1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
    go.setLayoutParams(params1);
    

    for:

    RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    params1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
    go.setLayoutParams(params1);
    

    When you create a View programatically it doesn't have any LayoutParams, that's why you are getting NullPointerException. If you inflate the view from XML, the view is coming now with LayoutParams.