Pooja Roy
Pooja Roy

Reputation: 545

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 ?

Upvotes: 3

Views: 983

Answers (4)

Lucifer
Lucifer

Reputation: 29632

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.

Upvotes: 2

user3531909
user3531909

Reputation: 109

Please replace your below line

String setMsg=msg.getText().toString();

with

String setMsg = String.valueOf(msg.getText());

Please try above line. Your problem will be solved.

Upvotes: 2

Rupesh
Rupesh

Reputation: 3505

see.. what you are doing.. immediately after obtaining and EditText's object you are calling getText() on it.. think logically.. obviously there is nothing (it should return blank though not sure why it is returing null) in the EditText unless you have it from the xml.. something like this;

<EditText
    ...
    android:text="Hey there"
    ...
/>

try this.. or move getText() call under some button click..

Upvotes: 2

No_Rulz
No_Rulz

Reputation: 2719

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);
    }

}
} 

Upvotes: 2

Related Questions