简体   繁体   中英

How can i get the text of an EditText from another XML file?

I have a activity which has an AlertDialog which calls a xml file where the EditText is, and I want to get that text and use it to create an object with it.

//This code is in Activity2.java/activity2_activity.xml
private Player addPlayer() {
//R.id.txtName and R.id.txtAge are the EditText from another xml file called inputplayer.xml
        txtName =(EditText) findViewById(R.id.txtName);
        txtAge= (EditText)findViewById(R.id.txtAge);

        String name= txtName.getText().toString();
        int age = Integer.valueOf(txtAge.getText().toString());
        
        if (name.length()>20){
            return null;
        }
        if (age < 3 || age > 99){
            return null;
        }
        return new Player(name,age);
    }

Problem is I got an exception when trying to get the Text from both EditText and cant find any solutions. Exception:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference at com.example.juego3enraya.Activity2.addPlayer(Activity2.java:111)

You don't get values in xml files. You get them in Java files. Confusing activities and the java code that runs them with xml files is only going to lead you to be very confused.

You can't search for a view in the root layout if its in the dialog box. What you should do is when the dialog window is closed, use dialog.findViewById(R.id.txtAge).getText() to get the value of the edit text when it is closed, and save the value in a variable.

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