我正在處理顯示歌曲歌詞的應用程序。我有一個錯誤:方法getText()必須從UI線程調用。我正在尋找答案,但沒有答案幫助解決了這個問題。Android Studio錯誤:必須從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);
}
}
你從一個異步線程中調用的getText()。它應該從UI線程中調用。你可以做的是在調用asynctask之前從文本字段獲取值,並從字符串變量中讀取值或將它們傳遞給asynctask構造函數。 – ifiok