[:en]AsyncTask with ProgressBar

Step 1:
Step 2:
package com.example.cambridge.asynctaskwithprogressbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing
textView = (TextView)findViewById(R.id.textView);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Create object MyTask
MyTask myTask = new MyTask(MainActivity.this,textView,button);
myTask.execute();
button.setEnabled(false);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Step 3:
package com.example.cambridge.asynctaskwithprogressbar; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import android.widget.Button; import android.widget.TextView; /** * Created by cambridge on 11/2/16. */ public class MyTask extends AsyncTask{ // define variables Context context; TextView textView; Button button; ProgressDialog progressDialog; // Create constructor MyTask(Context context,TextView textView,Button button){ this.context = context; this.textView = textView; this.button = button; } @Override protected String doInBackground(Void... params) { int i = 0; synchronized (this) { while (i<10) { try { wait(1500); i++; publishProgress(i); } catch (InterruptedException e) { e.printStackTrace(); } } } return "Download completed..."; } @Override protected void onPreExecute() { progressDialog = new ProgressDialog(context); progressDialog.setTitle("Download in progress..."); progressDialog.setMax(10); progressDialog.setProgress(0); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.show(); } @Override protected void onPostExecute(String result) { textView.setText(result); button.setEnabled(true); progressDialog.dismiss(); } @Override protected void onProgressUpdate(Integer... values) { int progress = values[0]; progressDialog.setProgress(progress); textView.setText("Download in progress..."); } }
[:]
