file.createNewFile();的结果;将SQLite数据库导出到CSV Android Java时被忽略

时间:2019-03-02 21:43:03

标签: android sqlite export-to-csv

我正在尝试使用ExportDatabaseCSVTask将SQLite数据库导出为CSV。

经过多次更正后,结果如下:

在按钮上单击CatalogActivity:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //export data to CSV using method in InventoryProvider via separate java class ExportDatabaseCSVTask
            case  R.id.export_to_csv:
                tryExporting();
              return true;
        }
        return super.onOptionsItemSelected(item);
    }


    public void tryExporting() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
            return;
        }
        new ExportDatabaseCSVTask(this).execute();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String permissions[], @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_READ_EXTERNAL_STORAGE: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    new ExportDatabaseCSVTask(this).execute();
                }
            }
        }

这是被触发的类

            public class ExportDatabaseCSVTask extends AsyncTask<String, String, Boolean> {
        SQLiteDatabase database;
        private Context context;
        private ProgressDialog dialog;
        InventoryProvider iProvider;
        InventoryDbHelper mDbHelper;

        public ExportDatabaseCSVTask(Context context) {
            this.context = context;
        }

        @Override
        protected void onPreExecute() {

            if (dialog == null) {
                dialog = new ProgressDialog(context);
                dialog.setMessage("Downloading Files... Please Wait...");
                dialog.show();
            }

        }



        @TargetApi(Build.VERSION_CODES.O)
        protected Boolean doInBackground(final String... args) {
            File exportDir = new File(Environment.getExternalStorageDirectory(), "/codesss/");

        if (!exportDir.exists()) { exportDir.mkdirs();
            if(!exportDir.mkdirs()) {
                Log.e("mDebug", "Couldn't get the directory"); 
            }
        }
                File file = new File(exportDir, "inventory.csv");
                try {
                    file.createNewFile();
                    if(!file.createNewFile()) {
                        Log.e("mDebug", "Couldn't create the file"); --> ERROR HERE result is ignored error
                    }


CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
                    database = this.mDbHelper.getWritableDatabase();
                    database = this.mDbHelper.getReadableDatabase();
                    Cursor curCSV = database.rawQuery("SELECT * FROM inventory", null);


                    csvWrite.writeNext(curCSV.getColumnNames());
                    while (curCSV.moveToNext()) {
                        String arrStr[] = null;
                        String[] mySecondStringArray = new String[curCSV.getColumnNames().length];
                        for (int i = 0; i < curCSV.getColumnNames().length; i++) {
                            mySecondStringArray[i] = curCSV.getString(i);
                        }
                        csvWrite.writeNext(mySecondStringArray);
                    }

                    csvWrite.close();
                    curCSV.close();
                    return true;
                } catch (IOException e) {
                    return false;
                }
            }



        protected void onPostExecute(final Boolean success) {
            if (dialog != null) {
                if (dialog.isShowing()) { dialog.dismiss();
                 dialog = null;
                }
            }
          // if ((dialog != null)) { this.dialog.dismiss(); }
           if (success) {
               Toast.makeText(context, "Export successful!", Toast.LENGTH_SHORT).show();
     ShareFile();
            } else {
                Toast.makeText(context, "Export failed", Toast.LENGTH_SHORT).show();
           }
        }

     private void ShareFile() {
            File exportDir = new File(Environment.getExternalStorageDirectory(), "/codesss/");
            String fileName = "inventory.csv";
            File sharingGifFile = new File(exportDir, fileName);
            Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
            shareIntent.setType("application/csv");
            Uri uri = Uri.fromFile(sharingGifFile);
            shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
            context.startActivity(Intent.createChooser(shareIntent, "Share CSV"));
        }
    }

已添加权限

   <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

更新

因此,现在的错误在于创建文件。 file.createNewFile();的结果;被忽略

调试显示已创建文件夹-D / myAppName:文件夹存在:/ storage / emulated / 0 / codesss 但是,它为空,不存在文件夹。

为此新问题创建了单独的问题-Exporting SQLite Database to csv file in android

1 个答案:

答案 0 :(得分:0)

onPreExecute()中更改为:

if (dialog == null) {
    dialog = new ProgressDialog(context);
    dialog.setMessage("Downloading Files... Please Wait...");
}

,这样您就不必每次都创建一个新的对话框。
再次在onPostExecute()中检查null

if (dialog != null) {
    if (dialog.isShowing()) { 
        dialog.dismiss(); 
        dialog = null;
    }
}

此外,由于此对话框ID是使用CatalogActivity的上下文创建的,因此请确保在显示对话框时未关闭此活动。
同时更改所有内容:

Toast.makeText(CatalogActivity.getApplicationContext...

Toast.makeText(context....