Error: “Method getText() must be called from the UI thread, currently inferred thread is worker.”

前端 未结 1 863
小蘑菇
小蘑菇 2021-01-22 03:45

While working on the project i get an error on following Activity. 1. Login.java on following Line of code.

Line: \"String username = user.getText().toString();\" Error

相关标签:
1条回答
  • 2021-01-22 04:07

    Unless something has changed that I'm not aware of, that shouldn't be a problem. UI elements can't be updated from the background but accessing their getters has never been an issue.

    Anyway, you can get around this by adding a constructor to your AsyncTask which would take the two Strings then send them when creating your task.

    private class Login extends AsyncTask<String, String, String>{
    
    // member variables of the task class
    String uName, pwd
    public AttemptLogin(String userName, String password) {
        uName = userName;
        pwd = password;
    }
    
    @Override
    protected String doInBackground(String... args) {...}
    

    and pass them in your onClick()

    case R.id.login:
     // execute method invokes doInBackground() where we open a Http URL connection using the given Servlet URL
     //and get output response from InputStream and return it.
    
     // pass them here
    
        new AttemptLogin(uname.getText().toString(), password.getText().toString()).execute();
                    break;
    
    0 讨论(0)
提交回复
热议问题