Question

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 ?

Was it helpful?

Solution

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.

OTHER TIPS

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

}
} 

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..

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top