I have a custom view that I declare in ‘main’ XML File:
<com.app.DrawView
android:id="@+id/my_view"
android:layout_height="match_parent"
android:layout_width="match_parent" />
Then in my activity’s onCreate method:
setContentView(R.layout.main);
Which all works fine for displaying the custom view. But what I need to do is pass values to the custom view. So, I tried making an instance of the custom view class:
DrawView drawView = (DrawView) findViewById(R.id.my_view);
Then, in the DrawView class, I created a method:
public void setUserData(boolean data){
useEraser = data;
}
Now, what my problem is I keep getting a NullPointerExeption when trying to access this method for the DrawView object within my activity, like so:
boolean value = true;
drawView.setUserData(value);
The error points to the “drawView.setUserData(value)” line. What am I doing wrong? I know I must have made a simple mistake but its driving me crazy trying to find it. Any help or suggestions would be great!
EDIT: I accepted an answer which worked correctly, however, I still wanted to know why my original solution did not work. So, I found that, despite the fact that I ordered it correctly in the question, I placed
DrawView drawView = (DrawView)findViewById(R.id.my_view);
before
setContentView(R.layout.main);
I knew it was a simple mistake I was overlooking! Thanks for the answers everyone I appreciate it. And I hope this proves to be useful for anyone faced with a similar problem.
if you want to create new one try this,
put an linearlayout in your xml as a holder
and in oncreate use below
it works there are no problem if you put it in your layout xml.