Android Studio错误:必须从UI线程

时间:2017-04-30 17:02:28

标签: java android multithreading

我正在研究显示歌曲歌词的应用程序。我有一个错误:必须从UI线程调用方法getText()。我正在寻找答案,但没有答案帮助解决问题。

public class HomeActivity extends AppCompatActivity {

private EditText wykonawca;
private EditText tytul;
private Button pokazTekst;
private TextView tekst;

//String url = "http://www.tekstowo.pl/piosenka,";
String title;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    FindViews();



    tekst.setMovementMethod(new ScrollingMovementMethod()); // mozliwosc scrolowania tekstu

    pokazTekst.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            new SongText().execute();
        }
    });

}

public class SongText extends AsyncTask<Void, Void, Void>{

    String url = "http://www.tekstowo.pl/piosenka,";
    String author;
    String song_name;

    @Override
    protected Void doInBackground(Void... params) {

        try {
            // here is error
            author = wykonawca.getText().toString();
            song_name = tytul.getText().toString();

            url = url + author + "," + song_name + ".html";

            Document doc = Jsoup.connect(url).get();

            title = doc.select("div[class=song-text").text();
        }

        catch (IOException e){
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);

        tekst.setText(title);
    }
}

private void FindViews(){

    // Edit text
    wykonawca = (EditText) findViewById(R.id.wykonawca);
    tytul = (EditText) findViewById(R.id.tytul);

    // Buttons
    pokazTekst = (Button) findViewById(R.id.pokazTekst);

    // TextViews
    tekst = (TextView) findViewById(R.id.tekst);

}

}

2 个答案:

答案 0 :(得分:0)

您无法与UI线程中的UI元素进行交互。 doInBackground()在那里的背景上运行,你不能与该线程中的textview进行交互。

答案 1 :(得分:0)

您正在从后台线程访问UI线程:。

author = wykonawca.getText().toString();
song_name = tytul.getText().toString();

检查这个答案 - Method getText() must be called from the UI Thread (Android Studio)