[:en]AsyncTask with ListView and ProgressBar
Step 1:
Step 2:
package com.example.cambridge.asynctaskwithlistview; import android.os.AsyncTask; 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.ArrayAdapter; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private String[] names={"John","Simon","Amy","Rose","Joe","Cruise","Tim","Jim","Pete"}; ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView)findViewById(R.id.list_view); listView.setAdapter(new ArrayAdapter(this,android.R.layout.simple_list_item_1,new ArrayList ())); // Call AsyncTask new MyTask().execute(); } class MyTask extends AsyncTask { //Define variables ArrayAdapter adapter; ProgressBar progressBar; int count; @Override protected void onPreExecute() { adapter = (ArrayAdapter )listView.getAdapter(); progressBar = (ProgressBar)findViewById(R.id.progress_bar); // Set parameters progressBar.setMax(9); progressBar.setProgress(0); progressBar.setVisibility(View.VISIBLE); count = 0; } @Override protected String doInBackground(Void... params) { for (String Name : names){ publishProgress(Name); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } return "All the names were added successfully"; } @Override protected void onProgressUpdate(String... values) { // add names to the adapter adapter.add(values[0]); count++; progressBar.setProgress(count); } @Override protected void onPostExecute(String result) { Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show(); progressBar.setVisibility(View.GONE); // Go to next page if you need it. Works! // startActivity(new Intent(MainActivity.this, secondpage.class)); } } }
[:]