ProgressBar未在AsyncTask中显示

时间:2016-08-12 16:04:13

标签: android android-asynctask android-progressbar

我正在使用ListView通过显示AsyncTaskProgressBar中加载列表。但是在我的代码中,ProgressBar现在正在显示。无法理解这个问题。

我使用与slidenerd中相同的代码,但在视频代码中有效,但我的代码似乎不起作用。

Video Link

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();
        }
    }
}

2 个答案:

答案 0 :(得分:0)

来自setProgressBarVisibility()setProgressBarIndeterminateVisibility()的{​​{3}}:

  

此方法在API级别24中已弃用。

     

不再支持   从API 21开始。

您应该使用ProgressDialog代替。

答案 1 :(得分:0)

你应该使用简单的ProgressDialog 例如:

ProgressDialog myPd = ProgressDialog.show(context, "Please wait", "Uploading Database to Cloud...", true);
myPd.setCancelable(false);