简体   繁体   English

从EditText获取字符串

[英]Getting a string from EditText

I'm trying to get the the text written by the user in an edittext view and store it in a String value then set this String value in a class that I created that contains two String Objects but when I run the code it gives me an error with a null pointer exception because the "WrittenSubj" and "WrittenDeta" are equal to null, how can i solve this problem? 我试图获取用户在edittext视图中编写的文本并将其存储在String值中,然后在我创建的包含两个String对象的类中设置此String值,但是当我运行代码时,它给了我一个提示。空指针异常的错误,因为“ WrittenSubj”和“ WrittenDeta”等于空,我该如何解决这个问题?

public class TaskDetails extends AppCompatActivity {
EditText WrittenSubj;
EditText WrittenDeta;
Button SaveBut;
TheTask theTask;
private Database database;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_task_details);
    WrittenSubj=(EditText)findViewById(R.id.thesubject);
    WrittenDeta=(EditText)findViewById(R.id.theDetails);
    SaveBut=(Button)findViewById(R.id.SaveButton);

    String subj=WrittenSubj.getText().toString();
    String deta=WrittenDeta.getText().toString();
    theTask.setSubject(subj);
    theTask.setDetails(deta);

}

I think TheTask is your Beam class, And you have not initialize it. 我认为TheTask是您的Beam类,并且您尚未初始化它。

Initialize this. 初始化它。

theTask = new TheTask();

And use 并使用

theTask.setSubject(subj);
theTask.setDetails(deta);

You have to initialize the TheTask class before using that like below 您必须先初始化TheTask类,然后再使用如下所示的类

TheTask theTask = new TheTask(); 

And after that use object of theTask like below 然后使用如下的Task对象

theTask.setSubject(subj);
theTask.setDetails(deta);

Problem is arrising because you are initializing edittexts and getting its text getText() in method onCreate() and OnCreate() is the method called when activity is created So at the time of creation of activity your edit texts will obviously be having null/empty value. 问题到来是因为您正在初始化edittext,并在方法onCreate()OnCreate()获取其文本getText()是创建活动时调用的方法,因此在创建活动时,您的编辑文本显然将具有null / empty值。 So you must call edittext.getText() on any event click or button click after actually the text have entered. 因此,在实际输入文本之后,您必须在任何事件单击或按钮单击时调用edittext.getText()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM