Reputation: 3
I am trying to get EditText value through below code. The activity is used for adding two strings. In the layout, I already put onSave and onCancel method. But when I press button linked to onSave, it shows null pointer exception error.
Activity:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class AddTimeActivity extends Activity {
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.time_item);
}
public void onCancel(View view){
this.setResult(RESULT_CANCELED);
finish();
}
public void onSave(View view){
Intent intent = getIntent();
EditText timeView = (EditText)view.findViewById(R.id.time_view);
String time = timeView.getText().toString();
intent.putExtra(TimeTrackerActivity.TIME_KEY, time);
EditText notesView = (EditText)view.findViewById(R.id.notes_view);
String notes = notesView.getText().toString();
intent.putExtra(TimeTrackerActivity.NOTES_KEY, notes);
this.setResult(RESULT_OK, intent);
finish();
}
}
Layout:
...
<EditText
android:id="@+id/timeView"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</EditText>
<EditText
android:id="@+id/notes_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:gravity="top"
android:layout_weight="1"
android:layout_marginBottom="10dp"/>
...
<Button
android:onClick="onSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save" />
<Button
android:onClick="onCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel" />
...
Error Message from Debugger
E/AndroidRuntime(1123): Caused by: java.lang.NullPointerException
E/AndroidRuntime(1123): at com.timetracker.AddTimeActivity.onSave(AddTimeActivity.java:34)
I tried to check and the value of timeView through debugger and it is null.
Could anybody help?
Upvotes: 0
Views: 2660
Reputation: 66637
Your xml has
android:id="@+id/timeView"
But your code has
EditText timeView = (EditText)view.findViewById(R.id.time_view);
Change above line to.
EditText timeView = (EditText)view.findViewById(R.id.timeView);
Upvotes: 2
Reputation: 137282
You are looking for the id time_view
(findViewById(R.id.time_view)), but you declare in the XML the ID timeView
(android:id="@+id/timeView"
). Make them the same and it should fix it.
Also, you should not call it on the view, but on the activity, e.g:
EditText timeView = (EditText)findViewById(R.id.time_view);
Upvotes: 3