Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Got Null String while get data From EditText in android

I got null data while fetch data from text Box.

My Code is:

EditText msg=(EditText)findViewById(R.id.Et_Msg);
String setMsg=msg.getText().toString();
Log.v("Messge","Message::"+setMsg);

Please tell me where I am wrong ?

like image 810
Pooja Roy Avatar asked Jan 22 '26 23:01

Pooja Roy


2 Answers

This is your code,

EditText msg=(EditText)findViewById(R.id.Et_Msg);
String setMsg=msg.getText().toString();
Log.v("Messge","Message::"+setMsg);
  • The first line is initializing the EditText. When it does by default there is no value ( string ) in the edittext.
  • In the second line you are trying to fetch a string from a blank edittext, that's why it is giving you NullPointerException.

Solution : I suggest you to move your line String setMsg=msg.getText().toString(); to somewhere else where you are actually going to use the value of EditText.

like image 116
Lucifer Avatar answered Jan 24 '26 12:01

Lucifer


While getting your data from EditText, you must create a listener orelse you get the value as null for an example button click listener.. For an example:

 public class A extends Activity implements OnClickListener{
    Button btn;
    EditText edt;
    @Override
    public void onCreate(Bundle saved){
    super.onCreate(saved);
    edt = (EditText) findViewById(R.id.your_id);
    btn = (Button) findViewById(R.id.your_id);
    btn.setOnClickListener(this);
    }
    @Override
    public void onClick(View v){
    if(v == btn){
    String setMsg=edt.getText().toString();
    Log.v("Messge","Message::"+setMsg);
    }

}
} 
like image 28
No_Rulz Avatar answered Jan 24 '26 13:01

No_Rulz