Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Android

Anoop George
Anoop George
1,147 Points

Extra credit: Getting started with Android

I was trying the extra credit section by creating a new project. When I run in emulator and click the button it crashes. Please help if I am doing something wrong.

The code snippet I used in MainActivity.java for the onclick listener

java
       final TextView editText = (TextView) findViewById(R.id.editText1);
        Button getButton = (Button) findViewById(R.id.button1);
        final TextView showText = (TextView) findViewById(R.id.textView1);

        getButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            //get value from edit text
            String textValue = (String) editText.getText();
            //set value for show text
            showText.setText(textValue);

        }
    });

Thanks in advance

3 Answers

Anoop George
Anoop George
1,147 Points

Hello Kate,

Thank you for your help. I figured out the issue. The changing of the view argument does not matter, it was the way that I used to get the value of the edit text that was causing the app to crash. I was trying to typecast the value from the edit text as String but the correct way was to use the toString() method. Please check the code below

Earlier code

  //get value from edit text
 String textValue = (String) editText.getText();
  //set value for show text
  showText.setText(textValue);

Correct code

 //get value from edit text
 String textValue =  editText.getText().toString();
  //set value for show text
  showText.setText(textValue);
Kate Hrycak
Kate Hrycak
5,542 Points

Hey Anoop,

So, I'm a beginner as well, but maybe instead of onClick(View v) try onClick(View Arg0) I cross-referenced the crystal ball course and what was correct for the onClickListener, as well as this site http://stackoverflow.com/questions/6133236/can-you-use-the-same-onclicklistener-for-different-buttons and it looks like they all use 'View Arg0 and not 'View v.

Let me know if that works!

Kate Hrycak
Kate Hrycak
5,542 Points

Ahhh yes, that'd do it wouldn't it. Thanks for letting me know what ended up working out! I'm doing the entire course first then will go back for the extra credit stuff, so I will be sure to reference this when I get to this extra credit. Thanks!