Reputation: 21
I have read the other post that are already on here but can't seem to figure out why I am getting this error. The error is in the title and it is also here: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
I tried to add msg = (EditText)v.findViewById(R.id.msgTxt); but that still didn't fix anything.
public class HelpFragment extends Fragment {
Button sendEmail;
EditText msg;
@Nullable
protected void process(View view) {
}
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_help, null);
sendEmail = (Button)v.findViewById(R.id.SendBtn);
sendEmail.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
msg = (EditText)v.findViewById(R.id.msgTxt);
String message = msg.getText().toString();
sendEmail(message);
}
});
return v;
}
protected void sendEmail(String message){
String to= new String("[email protected]");
String subject=("a message from app");
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, message);
emailIntent.setType("message/rfc822");
startActivity(Intent.createChooser(emailIntent, "Email"));
}
}
Upvotes: 1
Views: 859
Reputation: 1835
You reference onClick
's View
. You should implement msg = (EditText)v.findViewById(R.id.msgTxt);
before onClick()
method
You should use editText.getText().toString()
, because editText.getText()
returns Editable
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_help, null);
sendEmail = (Button)v.findViewById(R.id.SendBtn);
msg = (EditText)v.findViewById(R.id.msgTxt);
sendEmail.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
String message = msg.getText().toString();
sendEmail(message);
}
});
return v;
}
Upvotes: 2