[英]Android Export to CSV While Showing Progress Dialog not Writing to Files (Blank Files)
我使用opencsv庫將數據從sqlite導出到csv。 下面顯示的代碼在活動中使用時效果很好但在使用進度對話框實現時卻無法正常工作。 文件已創建但為空。 好像從運行導出的線程無法訪問
這是代碼:
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();
}
}
}
非常感激你的幫助。 謝謝。
我想到了。 我刪除了用於循環進度對話框進度計數的while子句,如下所示。 在這些中我評論了它,它就像一個魅力。
//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.