简体   繁体   English

Android导出为CSV,同时显示进度对话框不写入文件(空白文件)

[英]Android Export to CSV While Showing Progress Dialog not Writing to Files (Blank Files)

Am using the opencsv library to export data from sqlite to csv. 我使用opencsv库将数据从sqlite导出到csv。 The code shown below works well when used in activity but the same is not working while implemented using a progress dialog. 下面显示的代码在活动中使用时效果很好但在使用进度对话框实现时却无法正常工作。 The files are created but are empty. 文件已创建但为空。 Seems like the thread am running the export from is unable to access 好像从运行导出的线程无法访问

Here is the code: 这是代码:

package com.octagon.easyweigh;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import au.com.bytecode.opencsv.CSVWriter;

public class ExportDataDialog {
    ProgressDialog barProgressDialog;
    Handler updateBarHandler = new Handler();

    private Context _ctx;
    private int _maxCount;
    private String _exportDate;
    private int progressStatus = 0;

    private Double retrievedNetWeight = null;
    private String formatedNetWeight = null;

    private int lastUsedBatch = 0,gotConsignmentNo = 0;

    DbAdapter mDbHelper;

    private static   String TAG = "ExportDataDialog";

    SharedPreferences mSharedPrefs;
    private static   String MY_DB = "com.octagon.easyweigh_preferences";

    CSVWriter csvWriteDispatch = null;

    public ExportDataDialog(Context ctx, String exportDate) {
        _ctx = ctx;
        _exportDate = exportDate;

        mSharedPrefs = _ctx.getSharedPreferences(MY_DB,
                Context.MODE_PRIVATE);

        mDbHelper = new DbAdapter(_ctx);
        mDbHelper.open();

        Log.i(TAG, "Am here where?");
    }

    public void launchBarDialog() {
        barProgressDialog = new ProgressDialog(_ctx);

        barProgressDialog.setTitle("Data Export ...");
        barProgressDialog.setMessage("Data Export in progress ...");
        barProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        barProgressDialog.setProgress(0);
        barProgressDialog.setCancelable(false);
        barProgressDialog.show();

        try {
            // Here you should write your time consuming task...
            File exportDir = new File(Environment.getExternalStorageDirectory() + "/" + "/Easyweigh/Exports");

            if (!exportDir.exists()){
                exportDir.mkdirs();
            } else {
                //First make sure batch is closed
                //won't apply since batch has just been closed
                /*if(mDbHelper.getAnyOpenConsignment()) {
                                    tvMessage.setVisibility(View.VISIBLE);
                                    tvMessage.setText("Close Open Batch First!");
                                    return;
                                }*/

                //now get data
                lastUsedBatch = gotConsignmentNo;
                if (lastUsedBatch==0){
                    try {
                        lastUsedBatch = mDbHelper.getLastUsedBatch();   
                    } catch (Exception crap){
                        crap.printStackTrace();
                        /*tvMessage.setVisibility(View.VISIBLE);
                                        tvMessage.setText("No Records Found to Export");*/
                        return;
                    }

                    /*if (lastUsedBatch==0) {
                                        //It appears you have never weighed anything
                                        tvMessage.setVisibility(View.VISIBLE);
                                        tvMessage.setText("No Records Found to Export");
                                        return;
                                    }*/
                }
                //Generating file name

                String weighmentsFileName = "", dispatchFileName = "";

                Calendar calendar = Calendar.getInstance();

                Date exportDate = new Date();

                SimpleDateFormat mMonthFormat = new SimpleDateFormat("MM",java.util.Locale.getDefault()); //used to get month number

                //Format is TTTDDMMYYYYXX
                if (String.valueOf(lastUsedBatch).length()==1) { //pad
                    weighmentsFileName = mSharedPrefs.getString("terminalID", "") +  calendar.get(Calendar.DAY_OF_MONTH) + 
                            mMonthFormat.format(exportDate) +
                            calendar.get(Calendar.YEAR) + 
                            StringUtils.leftPad(String.valueOf(lastUsedBatch), 2, "0") +
                            ".txt";

                    dispatchFileName = mSharedPrefs.getString("terminalID", "") +  calendar.get(Calendar.DAY_OF_MONTH) + 
                            mMonthFormat.format(exportDate) +
                            calendar.get(Calendar.YEAR) + 
                            StringUtils.leftPad(String.valueOf(lastUsedBatch), 2, "0") +
                            ".con";

                } else {
                    weighmentsFileName = mSharedPrefs.getString("terminalID", "") +  calendar.get(Calendar.DAY_OF_MONTH) + 
                            mMonthFormat.format(exportDate) +
                            calendar.get(Calendar.YEAR) + 
                            lastUsedBatch + ".txt";

                    dispatchFileName = mSharedPrefs.getString("terminalID", "") +  calendar.get(Calendar.DAY_OF_MONTH) + 
                            mMonthFormat.format(exportDate) +
                            calendar.get(Calendar.YEAR) + 
                            lastUsedBatch + ".con";
                }

                final File weighmentsFile = new File(exportDir,weighmentsFileName);
                final File dispatchFile = new File(exportDir,dispatchFileName);

                try {
                    weighmentsFile.createNewFile();
                    dispatchFile.createNewFile();

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            CSVWriter csvWriteWeighments = null;

                            try {
                                csvWriteWeighments = new CSVWriter(new FileWriter(weighmentsFile), ',', CSVWriter.NO_QUOTE_CHARACTER,"\r\n");
                                csvWriteDispatch = new CSVWriter(new FileWriter(dispatchFile), ',', CSVWriter.NO_QUOTE_CHARACTER,"\r\n");
                            } catch (IOException e1) {
                                e1.printStackTrace();
                            }

                            Cursor records = mDbHelper.getRecordsForExport(_exportDate
                                    ,_exportDate);

                            barProgressDialog.setMax(records.getCount());

                            Cursor dispatchRecords = mDbHelper.getBatchForExport(_exportDate + " 00:00:01",
                                    _exportDate  + " 23:59:59");

                            if (dispatchRecords.getCount() <=0) {
                                return;
                            }

                            Log.i(TAG, "Dispacth records for export " + dispatchRecords.getCount());

                            for (dispatchRecords.moveToFirst(); !dispatchRecords.isAfterLast(); dispatchRecords.moveToNext()) {
                                final String items [] = { 
                                        dispatchRecords.getString(1), //consignemnt no
                                        mSharedPrefs.getString("terminalID", ""), //terminal
                                        mSharedPrefs.getString("userIDCache", ""),//clerk id
                                        dispatchRecords.getString(2), //deliverynoteno
                                        dispatchRecords.getString(5), //open time
                                        dispatchRecords.getString(6), //close time
                                        dispatchRecords.getString(8), //product weight
                                        dispatchRecords.getString(11), //dispatch time
                                        dispatchRecords.getString(10), //factory
                                        dispatchRecords.getString(12), //vehicle no
                                        dispatchRecords.getString(13), //trailerno
                                };
                                csvWriteDispatch.writeNext(items);

                            }

                            DecimalFormat df = new DecimalFormat("#.#");
                            df.setRoundingMode(RoundingMode.HALF_EVEN);

                            Log.i(TAG, "Total records for export " + records.getCount());

                            for (records.moveToFirst(); !records.isAfterLast(); records.moveToNext()) {
                                retrievedNetWeight = Double.valueOf(records.getString(10)); //NetWeight
                                formatedNetWeight = df.format(retrievedNetWeight);

                                String arrStr[] = { records.getString(1), //Date 
                                        records.getString(2), //Serial number
                                        records.getString(3), //Time
                                        records.getString(4), //UserID
                                        records.getString(5), //Produce
                                        records.getString(6), //Route
                                        records.getString(7), //Shed
                                        records.getString(8), //Batch No
                                        records.getString(9), //FarmerNo
                                        formatedNetWeight, //NetWeight
                                        records.getString(11),//TareWeight
                                        records.getString(12),//Can Serial
                                        records.getString(13),//Receipt Counter
                                        records.getString(15),//WeighmentNo
                                };
                                csvWriteWeighments.writeNext(arrStr);
                                progressStatus++;
                                while (barProgressDialog.getProgress() <= barProgressDialog.getMax()) {

                                    try {
                                        //csvWriteWeighments.writeNext(arrStr);
                                        Thread.sleep(100);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    } //Make export as fast as possible

                                    updateBarHandler.post(new Runnable() {
                                        public void run() {
                                            barProgressDialog.incrementProgressBy(1);
                                        }
                                    });

                                    Log.i(TAG, "Progress Status is " + progressStatus);
                                    Log.i(TAG, "Record Count is " + records.getCount());
                                    if (progressStatus==records.getCount()){
                                        try {
                                            updateBarHandler.post(new Runnable() {
                                                public void run() {
                                                    barProgressDialog.setMessage("Data Export Complete");
                                                }
                                            });
                                            Thread.sleep(2000);
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                        barProgressDialog.dismiss();
                                    }
                                }
                            }   
                            try {
                                csvWriteWeighments.close();
                                csvWriteDispatch.close();
                            } catch (IOException e1) {
                                e1.printStackTrace();
                            }
                            records.close();
                        }
                    }).start();
                } catch (Exception e) {
                    Log.e(TAG,"Error while creating files");
                    e.printStackTrace();
                    return;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Your help is very much appreciated. 非常感激你的帮助。 Thanks. 谢谢。

I figured it out. 我想到了。 I removed the while clause used to loop through the progress dialogs progress count as below. 我删除了用于循环进度对话框进度计数的while子句,如下所示。 In these I commented it out and it worked like a charm. 在这些中我评论了它,它就像一个魅力。

//while (barProgressDialog.getProgress() <= barProgressDialog.getMax()) {

try {
    //csvWriteWeighments.writeNext(arrStr);
    Thread.sleep(100);
} catch (InterruptedException e) {
    e.printStackTrace();
} //Make export as fast as possible

updateBarHandler.post(new Runnable() {
    public void run() {
        barProgressDialog.incrementProgressBy(1);
    }
});

Log.i(TAG, "Progress Status is " + progressStatus);
Log.i(TAG, "Record Count is " + records.getCount());
if (progressStatus==records.getCount()){
    try {
        updateBarHandler.post(new Runnable() {
            public void run() {
                barProgressDialog.setMessage("Data Export Complete");
            }
        });
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    barProgressDialog.dismiss();
}
//}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM