在运行代码时显示进度对话框时出现问题

时间:2019-04-14 07:38:13

标签: android sqlite android-asynctask progressdialog

我试图在执行长时间运行的代码时显示带有百分比的进度对话框,我为此目的使用了AsyncTask,但是它没有用,功能如下:我得到了所有图库图像的数组路径,然后我处理这些图像并提取每个图像的描述符向量,并将其转换为JSON字符串,然后将这些字符串存储到sqlite中,但是我的代码花费大量时间(几分钟),所以我需要显示一个进度对话框,其中包含百分比为了知道任务的开始和结束,我需要在按下按钮时启动该任务。下面是我的代码:

public void FillDataBase(){

    ArrayList<String> paths = getFilePaths();
    for (int i = 0; i < paths.size(); i++) {

        Mat mat = new Mat();

        BitmapFactory.Options bmOptions1 = new BitmapFactory.Options();
        //bmOptions1.inSampleSize=4;
        Bitmap bitmap0 = BitmapFactory.decodeFile(paths.get(i).toString(), bmOptions1);

        Bitmap bitmap = getRotated(bitmap0, paths.get(i).toString());

        //Utils.bitmapToMat(bitmap, mat);

        Mat matRGB = new Mat();
        Utils.bitmapToMat(bitmap, matRGB);
        Imgproc.cvtColor(matRGB, mat, Imgproc.COLOR_RGB2GRAY);

        org.opencv.core.Size s2 = new Size(3, 3);
        Imgproc.GaussianBlur(mat, mat, s2, 2);


        FeatureDetector detector2 = FeatureDetector.create(FeatureDetector.ORB);
        MatOfKeyPoint keypoints2 = new MatOfKeyPoint();
        detector2.detect(mat, keypoints2);


        DescriptorExtractor extractor2 = DescriptorExtractor.create(DescriptorExtractor.ORB);
        Mat descriptors2 = new Mat();
        extractor2.compute(mat, keypoints2, descriptors2);


        // String matimage = matToJson(mat);
        String matkeys= keypointsToJson(keypoints2);
        String desc = matToJson(descriptors2);

        mat m = new mat(desc, matkeys);
        DataBaseHandler db = new DataBaseHandler(getApplicationContext());
        db.addmat(m);

    }

异步任务代码(我在线程的公共无效运行中调用FillDatabase()):

private class ProgressTask extends AsyncTask<Void,Void,Void>{
    private int progressStatus=0;
    private Handler handler = new Handler();

    // Initialize a new instance of progress dialog
    private ProgressDialog pd = new ProgressDialog(RGBtoGrey.this);

    @Override
    protected void onPreExecute(){
        super.onPreExecute();
        pd.setIndeterminate(false);

        // Set progress style horizontal
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

        // Set the progress dialog background color
        pd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.YELLOW));

        // Make the progress dialog cancellable
        pd.setCancelable(true);
        // Set the maximum value of progress
        pd.setMax(100);
        // Finally, show the progress dialog
        pd.show();
    }

    @Override
    protected Void doInBackground(Void...args){
        // Set the progress status zero on each button click
        progressStatus = 0;

        // Start the lengthy operation in a background thread
        new Thread(new Runnable() {
            @Override
            public void run() {

                FillDataBase();

                while(progressStatus < 100){

                    // Update the progress status
                    progressStatus +=1;

                    // Try to sleep the thread for 20 milliseconds

                        try{
                            Thread.sleep(20);

                        }catch(InterruptedException e){
                            e.printStackTrace();
                        }


                    // Update the progress bar
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            // Update the progress status
                            pd.setProgress(progressStatus);
                            // If task execution completed
                            if(progressStatus == 100){
                                // Dismiss/hide the progress dialog
                                pd.dismiss();
                            }
                        }
                    });
                }
            }
        }).start(); // Start the operation

        return null;
    }

    protected void onPostExecute(){
        // do something after async task completed.
    }

最后,我这样调用Asynctask:

testButton0.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        new ProgressTask().execute();

                }

    });

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

private static class InsertAllPersonsToFirebaseTask extends AsyncTask<Void, Float, Void> {

    private List<Person> personList;
    private ElasticDownloadView mElasticDownloadView;
    private DatabaseReference mDatabase, pushedKey;
    private Person person;

    public InsertAllPersonsToFirebaseTask(List<Person> personList, ElasticDownloadView mElasticDownloadView) {
        this.personList = personList;
        this.mElasticDownloadView = mElasticDownloadView;

    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        if (mElasticDownloadView != null) {
            this.mElasticDownloadView.setVisibility(View.VISIBLE);
            this.mElasticDownloadView.startIntro();
        }
    }

    @Override
    protected Void doInBackground(Void... voids) {
        mDatabase = FirebaseDatabase.getInstance().getReference();

        for (int i = 0; i < personList.size(); i++){
            pushedKey = mDatabase.child("Persons").push();
            person = new Person();
            person.setPersonId(System.currentTimeMillis());
            person.setName(personList.get(i).getName());

            pushedKey.setValue(person);

            //This line is for update the onProgressUpdate() method
            publishProgress(((i+1)/(float)personList.size()* 100));

            if (isCancelled()){
                break;
            }
        }

        return null;
    }

    @Override
    protected void onProgressUpdate(Float... progress) {

        if (mElasticDownloadView != null){
            mElasticDownloadView.setProgress(progress[0]);
        }

    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);

        if (mElasticDownloadView != null){
            mElasticDownloadView.setVisibility(View.GONE);
        }
    }
}

您可以使用任何类型的进度条。我已经使用过ElasticDownloadview进度条。

然后:

testButton0.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

         new InsertAllPersonsToFirebaseTask(personArrayList,mElasticDownloadView).execute();

                 }

    });