Method getText() must be called from the UI Thread (Android Studio)

前端 未结 5 874
花落未央
花落未央 2020-11-30 14:44

I\'m trying to create a login for an application. However I have a problem.

This is my code:

package com.forgetmenot.loginregister;


import java.uti         


        
5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 15:20

    You're accessing the UI thread from a background thread here:

    String username = uname.getText().toString();
    String pass = password.getText().toString();
    

    What you want to do is just pass the username/password strings in to your background task constructor or you could pass them directly to the execute method. I prefer to define them in to the constructor if they are going to be required (like yours are).

    Define your LoginTask like

    String uname;
    String password;
    public Login(String username, String password({
        this.uname = username;
        this.password = password;
    }
    

    Then in doInBackground() you use the members instead.

    List params = new ArrayList();
    params.add(new BasicNameValuePair("u",this.username));
    params.add(new BasicNameValuePair("p",this.pass));
    json = jParser.makeHttpRequest(url_login, "GET", params);
    

    Edit - so then your new Login().execute() call would look more like this

    new Login(uname.getText().toString(), password.getText().toString()).execute();
    

提交回复
热议问题