akkk akkk - 3 months ago 37
Android Question

ProgressBar not showing in AsyncTask

I am loading list in listview using AsyncTask by showing progress bar. But in my code the progressbar is now showing. Cant understand the problem.

I used the same code as in slidenerd but in the video code works but my code doesn't seem to work.

Video Link -

https://www.youtube.com/watch?v=dVwR5Gpw1_E


public class MainActivity extends AppCompatActivity {

ListView listView;
String[] items = {"Ankush", "Kapoor", "Amit", "Kumar", "Shirshak", "Tillu", "Mishra", "Sudeep", "Dey", "Ayon",
"Ankush", "Kapoor", "Amit", "Kumar", "Shirshak", "Tillu", "Mishra", "Sudeep", "Dey", "Ayon",
"Ankush", "Kapoor", "Amit", "Kumar", "Shirshak", "Tillu", "Mishra", "Sudeep", "Dey", "Ayon",
"Ankush", "Kapoor", "Amit", "Kumar", "Shirshak", "Tillu", "Mishra", "Sudeep", "Dey", "Ayon"};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
requestWindowFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new ArrayList<String>());
listView.setAdapter(adapter);
new JSONTask().execute();
}

public class JSONTask extends AsyncTask<Void, String, Void> {

private ArrayAdapter<String> adapter;
private int count = 0;

@Override
protected void onPreExecute() {
adapter = (ArrayAdapter<String>) listView.getAdapter();
setProgressBarIndeterminateVisibility(true);
setProgressBarVisibility(true);
}

@Override
protected Void doInBackground(Void... params) {
for (String i : items) {
publishProgress(i);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}

@Override
protected void onProgressUpdate(String... values) {
adapter.add(values[0]);
count++;
setProgress((int) (((double) count / items.length) * 10000));
}

@Override
protected void onPostExecute(Void aVoid) {
setProgressBarIndeterminateVisibility(false);
setProgressBarVisibility(false);
Toast.makeText(getApplicationContext(), "Done!", Toast.LENGTH_SHORT).show();
}
}
}

Answer

From the documentation of setProgressBarVisibility() and setProgressBarIndeterminateVisibility():

This method was deprecated in API level 24.

No longer supported starting in API 21.

You should use a ProgressDialog instead.