문제

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 ?

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top