jarlo
jarlo

Reputation: 11

NullPointerException in Android onClick

ERROR/AndroidRuntime(545):     at no.jarle.f02.myActivity.onClick(myActivity.java:38)


public void onClick( View v )
{
    tvTextView.setText(editText1.getText());   <--- line 38
}


<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".myActivity"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

The TextView should display the text user typed in the EditText when the button is clicked. Instead it obviously crashes and i can't seem to find the problem. Any help is greatly appreciated :)

Upvotes: 1

Views: 529

Answers (3)

kalpana c
kalpana c

Reputation: 2739

Use this:

   if (editText1.getText().toString().trim() > 0)

    tvTextView.setText(editText1.getText().toString());

Upvotes: 1

gugarush
gugarush

Reputation: 118

Maybe your TextView and/or EditText are only instanced on onCreate Method and they don't have "life" on your onClick method.

Is your class something like this?

Class YourClass {

private EditText editText1;

private TextView tvTextView;

public void `onCreate`(Bundle arg) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main)

    editText1 = (EditText) findViewById(R.id.editText1);
    tvTextView = (TextView) findViewById(R.id.tvTextView);
}

public void onClick(View v) {
    tvTextView.setText(editText1.getText());
}

?

if your TextView and EditText are not attribute, you cant manipulate them on onClick.

or you can get the instance of them on onClick method using findViewById before try to setText.

Upvotes: 0

PH7
PH7

Reputation: 3916

My guess is you are having empty editText1 when you click on the button. So before you do setting text, just make sure you have something in the editText1. For example

if (editText1.getText().length>0)
   tvTextView.setText(editText1.getText());

Upvotes: 0

Related Questions