SherlockFragmentActivity EditText getText()nullpointerexception

时间:2013-10-03 20:13:08

标签: android actionbarsherlock android-edittext

当我从EditTex执行nullpointerexception时出现此错误getText().toString()

public class SendMessActivity extends SherlockFragmentActivity  {    
   private  EditText tEmail;
   private  Button sendButton;
 @Override
 protected void onCreate(final Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.send_mess_layout);
   tEmail = (EditText)findViewById(R.id.editEmailTo);
   sendButton = (Button)findViewById(R.id.btn_sendmess);
   endButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           //String textEmail = tEmail.getText().toString(); //nullpointerexception
           Editable textEmail1Editable = tEmail.getText(); //nullpointerexception
           String textEmail = textEmail1Editable.toString()
           Log.d(DEBUGTAG, "SENDING START::::::::  " + textEmail);
         }
    });

}}

请告诉我该怎么做

更新问题

大卫,谢谢你,因为你的猜测,这个问题真的出现在我错综复杂的布局中 我有4个级别的嵌套LinearLayouts。 在我离开简化方案后,我只有2个级别,所有都开始工作

2 个答案:

答案 0 :(得分:0)

您需要致电setContentView(your_layout.xml),以便知道要使用的布局。如果不设置布局,您尝试在布局中查找视图的所有findViewById(...)调用都将返回null。

public class SendMessActivity extends SherlockFragmentActivity  {     
   private  EditText tEmail;
   private  Button sendButton;
 @Override 
 protected void onCreate(final Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);


   setContentView(your_layout.xml); //set your activity layout here.


   tEmail = (EditText)findViewById(R.id.editEmailTo);
   sendButton = (Button)findViewById(R.id.btn_sendmess);
   endButton.setOnClickListener(new View.OnClickListener() {
        @Override 
        public void onClick(View view) {
           String textEmail = tEmail.getText().toString(); //nullpointerexception
           Log.d(DEBUGTAG, "SENDING START::::::::  " + textEmail);
         } 
    }); 

}} 

答案 1 :(得分:0)

如果您没有指定文本,那么我会假设文本的EditText检索将是一个空条目,并且您正在尝试创建该空条目的字符串。