简体   繁体   中英

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?

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.

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 = new TheTask(); 

And after that use object of theTask like below

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. So you must call edittext.getText() on any event click or button click after actually the text have entered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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