دنبال کننده ها

۱۳۹۶ دی ۱۳, چهارشنبه

java - Android findViewById null pointer

[ad_1]



From activity_settings.xml



<EditText android:id="@+id/editText" android:text="text" />
<Button android:id="@+id/button" android:text="button"/>


From MyActivity.java



@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
this.findViewById(R.id.button).setOnClickListener(
new View.OnClickListener()
@Override
public void onClick(View view)
EditText txt = (EditText) view.findViewById(R.id.editText);
Toast.makeText(view.getContext(),txt.getText(), Toast.LENGTH_SHORT).show();

);
...


If I click the button I get



 java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference


Just for test I tried and succeeded



@Override
public void onClick(View view)
EditText txt = (EditText) view.findViewById(R.id.editText);
Toast.makeText(view.getContext(),txt.getText(),Toast.LENGTH_SHORT).show();




I don't get why button is ok but editText is null.




[ad_2]

لینک منبع