Karoly S
Karoly S

Reputation: 3258

Android: Setting EditText/TextView text on Button Press

I'm disappointed to have to ask this question because it is something so painfully simply.

On button press, I'm trying to read text from a Time based EditText, perform a calculation, and then set either a second Time based EditText or a TextView to the result of the calculation. Not matter what I try my app continues to crash with the following in the CallStack:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
            at com.timesheethelper.MainActivity.onCalculateClicked(MainActivity.java:48)

My code is below:

public void onCalculateClicked(View view)
{
    //EditText start_ET = (EditText)view.findViewById(R.id.start_editText);
    //EditText end_ET = (EditText)view.findViewById(R.id.end_editText);
    TextView test = (TextView)view.findViewById(R.id.textView);

    test.setText("6:30");
} 

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Calculate"
    android:id="@+id/calculate_button"
    android:layout_below="@+id/end_editText"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="40dp"
    android:onClick="onCalculateClicked" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="Medium Text"
    android:id="@+id/textView"
    android:layout_alignTop="@+id/end_editText"
    android:layout_alignRight="@+id/calculate_button"
    android:layout_alignEnd="@+id/calculate_button" />

I've spent more time trying to figure out my issue than I care to admit and I'm not expecting it to be something huge. I'm fairly new to Android development so I'm sure its a minor oversight. Any help to point me in the right direction is appreciated!

Upvotes: 0

Views: 1238

Answers (1)

Rohit5k2
Rohit5k2

Reputation: 18112

Its because you are doing it wrong! onCalculateClicked is onClick callback for the button calculate_button and the argument passed in that is the reference of it. Here you are trying to get text view test from calculate_button button which is too obviously not inside the button.

I suppose your code is in an activity

Replace

TextView test = (TextView)view.findViewById(R.id.textView);

with

TextView test = (TextView)findViewById(R.id.textView); 

If it is in a fragment then use

TextView test = (TextView)getActivity().findViewById(R.id.textView);

Upvotes: 2

Related Questions