Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Ok you are trying to access the GUI via another thread. This, in the main, is not good practice. </p> <p>The AsyncTask executes everything in <code>doInBackground()</code> inside of another thread, which does not have access to the GUI where your views are.</p> <p><code>preExecute()</code> and <code>postExecute()</code> offer you access to GUI before and after the heavy lifting occurs in this new thread, you can even pass the result of the long operation to <code>postExecute()</code> to then show any results of processing.</p> <p>See these lines where you are later updating your TextView:</p> <pre><code>TextView txt = (TextView) findViewById(R.id.output); txt.setText("Executed"); </code></pre> <p>put them in <code>PostExecute()</code></p> <p>You will then see your TextView text updated after the <code>doInBackground</code> completes.</p> <p><strong>EDIT:</strong> I noticed that your onClick listener does not check to see which View has been selected. I find the easiest way to do this is via switch statements. I have a complete class edited below with all suggestions to save confusion.</p> <pre><code>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; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btn = (Button) findViewById(R.id.button1); // because we implement OnClickListener we only have to pass "this" // (much easier) btn.setOnClickListener(this); } public void onClick(View view) { // detect the view that was "clicked" switch (view.getId()) { case R.id.button1: new LongOperation().execute(""); break; } } private class LongOperation extends AsyncTask&lt;String, Void, String&gt; { @Override protected String doInBackground(String... params) { for (int i = 0; i &lt; 5; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.interrupted(); } } 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 } @Override protected void onPreExecute() {} @Override protected void onProgressUpdate(Void... values) {} } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload