kamal
kamal

Reputation: 291

getting null pointer exception in this code

  public class StartDraw extends Activity  {




@Override

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   // setContentView(R.layout.main);
    MyView view1 =new MyView(this);
   // view1.setBackgroundResource(R.drawable.ic_launcher);
    setContentView(view1);



}


 public class MyView extends View implements OnTouchListener{
    RelativeLayout.LayoutParams LP;  
    ViewGroup dlayout; 
      ImageView[] ActionI = new ImageView[4];
      ImageView[] ReciverI = new ImageView[4];
    public MyView(Context c) {
        super(c);
     //  dlayout = new ViewGroup(c); // if i use this then error shown {Cannot instantiate the type ViewGroup}
         LP = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);
       //  ViewGroup dlayout = (ViewGroup)findViewById(R.id.dlayout);
         dlayout.setLayoutParams(LP); // at this position gettting null pointer exception

}

   @Override
    protected void onDraw(Canvas canvas) {
           paint.setStyle(Paint.Style.STROKE);
           paint.setStrokeWidth(2);
           paint.setColor(Color.GREEN);
           canvas.drawColor(Color.BLUE);

           canvas.drawLine(offset_x, offset_y, currentX, currentY, paint);

    }
}

Upvotes: 0

Views: 100

Answers (3)

user2142983
user2142983

Reputation:

setContentView(R.layout.main); remove this comments and enable it

   setContentView(R.layout.main); remove this comments and enable it

setContentView(R.layout.main); remove this comments and enable it

Upvotes: 2

Zelldon
Zelldon

Reputation: 5516

You try to set a Property of an Object which is not initialized

dlayout.setLayoutParams(LP);

Uncomment your code above and the Error should be fixed.

//  ViewGroup dlayout = (ViewGroup)findViewById(R.id.dlayout);

Upvotes: 0

Paul-Jan
Paul-Jan

Reputation: 17278

You have commented out the dlayout initialization. Hence it is null. Causing a NullPointerException in dlayout.setLayoutParams.

If there is something about this cause/effect that you are not understanding, please extend your question to clarify. If, however, you are unsure how to initialize the dlayout variable, make that into a question of it's own.

Upvotes: 0

Related Questions