Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialdlpuxdzztg
8,243 PointsUnknown Class When Assigning Member Fields to Views
Hello.
I seem to be having trouble when I simply try to assign a member variable to a view. It tells me that my member variable is an "unknown class" when I assign it to a view. Could someone explain why it is giving me that error?
public class MainActivity extends AppCompatActivity {
private ImageView mAddItemImage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAddItemImage addItemImage = findViewById(R.id.addAssignmentImage);
}
private void askUserForAssignment() {
NewItemDialogFragment dialog = new NewItemDialogFragment();
dialog.show(getSupportFragmentManager(), "assignment_dialog");
}
}
Thank you.
1 Answer
Seth Kroger
56,413 PointsfindViewById() returns a general View type. If you declare a view variable as a more specific kind of View, like ImageView, you should remember to explicitly downcast.
mAddItemImage = (ImageView) findViewById(R.id.addAssignmentImage);
David Remington
18,326 PointsDavid Remington
18,326 PointsYou have already declared the member variable and its type above, if you want to initialize it and assign it to the view in your layout you would only need something like this:
mAddItemImage = findViewById(R.id.addAssignmentImage);