Stavo leggendo di AsyncTask
, e ho provato il semplice programma qui sotto. Ma non sembra funzionare. Come posso farlo funzionare?
public class AsyncTaskActivity extends Activity {
Button btn;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener((OnClickListener) this);
}
public void onClick(View view){
new LongOperation().execute("");
}
private class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
for(int i=0;i<5;i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
TextView txt = (TextView) findViewById(R.id.output);
txt.setText("Executed");
return null;
}
@Override
protected void onPostExecute(String result) {
}
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Void... values) {
}
}
}
Sto solo cercando di cambiare l'etichetta dopo 5 secondi nel processo in background.
Questo è il mio main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:indeterminate="false"
android:max="10"
android:padding="10dip">
</ProgressBar>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Progress" >
</Button>
<TextView android:id="@+id/output"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Replace"/>
</LinearLayout>
Ok, state cercando di accedere alla GUI tramite un altro thread. Questo, in generale, non è una buona pratica.
L'AsyncTask esegue tutto in doInBackground()
all'interno di un altro thread, che non ha accesso alla GUI dove sono le tue viste.
preExecute()
e postExecute()
vi offrono l'accesso alla GUI prima e dopo che il sollevamento pesante avviene in questo nuovo thread, potete anche passare il risultato dell'operazione lunga a postExecute()
per poi mostrare qualsiasi risultato di elaborazione.
Guardate queste linee dove in seguito aggiornerete la TextView:
TextView txt = findViewById(R.id.output);
txt.setText("Executed");
mettile in onPostExecute()
Vedrete quindi il vostro testo TextView aggiornato dopo il completamento del doInBackground
.
EDIT: Ho notato che il tuo listener onClick non controlla quale View è stata selezionata. Trovo che il modo più semplice per farlo sia tramite dichiarazioni di switch. Ho una classe completa modificata qui sotto con tutti i suggerimenti per risparmiare confusione.
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.System;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class AsyncTaskActivity extends Activity implements OnClickListener {
Button btn;
AsyncTask<?, ?, ?> runningTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = findViewById(R.id.button1);
// because we implement OnClickListener we only have to pass "this"
// (much easier)
btn.setOnClickListener(this);
}
@Override
public void onClick(View view) {
// detect the view that was "clicked"
switch (view.getId()) {
case R.id.button1:
if (runningTask != null) runningTask.cancel(true);
runningTask = new LongOperation();
runningTask.execute();
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// cancel running task(s) to avoid memory leaks
if (runningTask != null) runningTask.cancel(true);
}
private final class LongOperation extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// we were cancelled, stop sleeping!
}
}
return "Executed";
}
@Override
protected void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.output);
txt.setText("Executed"); // txt.setText(result);
// might want to change "executed" for the returned string passed
// into onPostExecute() but that is upto you
}
}
}
Sono sicuro che viene eseguito correttamente, ma stai cercando di cambiare gli elementi dell'interfaccia utente nel thread in background e questo non va bene.
Rivedete la vostra chiamata e AsyncTask come segue:
Classe di chiamata
Nota: Personalmente suggerisco di usare onPostExecute()
ovunque eseguiate il vostro thread AsyncTask e non nella classe che estende AsyncTask stesso. Penso che renda il codice più facile da leggere specialmente se avete bisogno dell'AsyncTask in più posti gestendo i risultati in modo leggermente diverso.
new LongThread() {
@Override public void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.output);
txt.setText(result);
}
}.execute("");
Classe LongThread (estende AsyncTask):
@Override
protected String doInBackground(String... params) {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "Executed";
}
Spostare queste due linee:
TextView txt = (TextView) findViewById(R.id.output);
txt.setText("Executed");
fuori dal metodo doInBackground
del tuo AsyncTask e mettile nel metodo onPostExecute
. Il tuo AsyncTask
dovrebbe assomigliare a questo:
private class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
try {
Thread.sleep(5000); // no need for a loop
} catch (InterruptedException e) {
Log.e("LongOperation", "Interrupted", e);
return "Interrupted";
}
return "Executed";
}
@Override
protected void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.output);
txt.setText(result);
}
}