GetText() error related questions.

Asked 2 years ago, Updated 2 years ago, 112 views

private class HttpAsyncTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {

        person = new Person();
        person.setName(etName.getText().toString(); //etName.getText() error
        person.setCountry(etCountry.getText().toString(); //etCountry.getText()Error
        person.setTwitter(etTwitter.getText().toString(); //etTwitter.getText()Error

        return POST(urls[0], person);
    }

    // // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
    }
}

There's a code like this. In the class named person, the name, country, and Twitter variables are specified. An error occurs in the details of .set. Method getText must be called from the UI thread, currently inferred thread is worker less... They give me that message, but this is not the code I made, but I tried to take the existing project and do it You get this error message. The page I wanted to refer to is http://hmkcode.com/android-send-json-data-to-server/ I want to know why.

gettext user-interface thread json

2022-09-22 08:22

1 Answers

Error caused by the getText() function in EditText being called in the Work thread. Processing related to the UI on Android must be invoked within the UI thread. In other words, the Android UI is not secure from threads, so if you operate View outside of the UI thread, the above error occurs.

For more information, please read the threads topic in the following document.

Try changing the code as follows.

// The part where you run HttpAsyncTask
new HttpAsyncTask().execute(
    etName.getText().toString(), 
    etCountry.getText().toString(), 
    etTwitter.getText().toString(), 
    "http://hmkcode.appspot.com/jsonservlet");

...

// doInBackground function 
@Override
protected String doInBackground(String... args) {
    person = new Person();
    person.setName(args[0]);    
    person.setCountry(args[1]); 
    person.setTwitter(args[2]); 

    return POST(args[3], person);
}


2022-09-22 08:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.