【发布时间】:2014-07-03 01:43:12
【问题描述】:
我想将特定的 CSV 文件导入数据库。我正在使用库 aFileChooser 来选择文件,但 CSV 文件中的数据未导入。我哪里错了?谢谢
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case ACTIVITY_CHOOSE_FILE1: {
if (resultCode == RESULT_OK){
Uri uri = data.getData();
File file1 = com.ipaulpro.afilechooser.utils.FileUtils.getFile(uri);
proImportCSV(file1);
}
}
}
}
ricevi_csv= (Button) findViewById(R.id.but_ricevi_csv);
ricevi_csv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent chooseFile;
Intent intent;
chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.setType("application/image");
intent = Intent.createChooser(chooseFile, "Choose a CSV");
startActivityForResult(intent, ACTIVITY_CHOOSE_FILE1);
}
});
}
private void proImportCSV(File from){
File root = Environment.getExternalStorageDirectory();
File exportDir = new File(root.getAbsolutePath());
File csvFile = new File(exportDir, getString(R.string.app_name)+".csv");
try {
ContentValues cv = new ContentValues();
// reading CSV and writing table
CSVReader dataRead = new CSVReader(new FileReader(csvFile));
String[] vv = null;
while((vv = dataRead.readNext())!=null) {
cv.clear();
SimpleDateFormat currFormater = new SimpleDateFormat("dd-MM-yyyy");
SimpleDateFormat postFormater = new SimpleDateFormat("yyyy-MM-dd");
String eDDte;
try {
Date nDate = currFormater.parse(vv[0]);
eDDte = postFormater.format(nDate);
cv.put(Table.DATA,eDDte);
}
catch (Exception e) {
}
cv.put(Table.C,vv[1]);
cv.put(Table.E,vv[2]);
cv.put(Table.U,vv[3]);
cv.put(Table.C,vv[4]);
SQLiteDatabase db = mHelper.getWritableDatabase();
db.insert(Table.TABLE_NAME,null,cv);
} 数据读取.close();
} 捕捉(异常 e){ Log.e("TAG",e.toString());
}
【问题讨论】:
-
您是否遇到任何异常?我能看到的唯一奇怪的事情是你得到的是“应用程序/图像”,而不是使用“文本/csv”和 Intent.ACTION_GET_CONTENT 而不是 Intent.CATEGORY_OPENABLE。您甚至可能想使用“new File(data.getData().getPath())”而不是“com.ipaulpro.afilechooser.utils.FileUtils.getFile(uri);” -- 我昨天刚刚做了这个 CSV 重要的东西,这对我来说似乎工作正常。您的阅读内容看起来不错,尽管您可能希望在进入 while 循环之前调用 dataRead.readNext() 以确保跳过标题行(如果有的话)
-
你能告诉我你的代码吗?
Intent.CATEGORY_OPENABLE不适合我 -
当然,我会把它作为答案发布。请给我一点时间从 github 中提取它
-
我错了删除 ACTION_GET_CONTENT btw
标签: android file csv android-intent