Android 应用程序:用户通过 Intent.ACTION_GET_CONTENT 选择 CSV 文件。然后如何将此 CSV 文件导入 sqlite 数据库 table?

Android App: User selects a CSV file through an Intent.ACTION_GET_CONTENT. How can I then import this CSV file into a sqlite database table?

我正在努力构建通过 CSV 文件将数据导入到 Android 应用程序 UI 中的 SQLite 数据库 table 的功能 UI。

有一个带有 OnClickListener 的按钮,允许用户 select 他们想要上传的文件。 select 编辑文件后,它们将返回到 "Import Accounts" 页面,页面底部还有一个 "Import CSV" 按钮。

ImportAccountActivity java OnClickListener 代码:

btn_choose_file.setOnClickListener(new Button.OnClickListener(){
            @Override
            public void onClick(View arg0) {

                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");
                startActivityForResult(intent,PICKFILE_RESULT_CODE);

            }});

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PICKFILE_RESULT_CODE:
                if (resultCode == RESULT_OK) {
                    FilePath = data.getData().getPath();
                    Uri returnUri = data.getData();


                    returnCursor = getContentResolver().query(returnUri, null, 
                            null, null, null);



                    /*
                     * Get the column indexes of the data in the Cursor,
                     * move to the first row in the Cursor, get the data,
                     * and display it.
                     */
                    nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                    returnCursor.moveToFirst();


                    textFile.setText(returnCursor.getString(nameIndex) + " has been selected!");


                }
                break;
   }}


// Import CSV button OnClickListener
        btn_csv_import.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Access Database to be writable
                SQLiteOpenHelper database = new AccountDbHelper(getApplicationContext());
                SQLiteDatabase db = database.getWritableDatabase();


                FileReader file = new FileReader(fileName);
                BufferedReader buffer = new BufferedReader(file);
                String line = "";
                String tableName = AccountLogin.AccountEntry.TABLE_NAME;
                String columns = "_id, account_title, user_name, account_password, account_notes";
                String str1 = "INSERT INTO " + tableName + " (" + columns + ") values(";
                String str2 = ");";

                db.beginTransaction();
                while ((line = buffer.readLine()) != null) {
                    StringBuilder sb = new StringBuilder(str1);
                    String[] str = line.split(",");
                    sb.append("'" + str[0] + "',");
                    sb.append(str[1] + "',");
                    sb.append(str[2] + "',");
                    sb.append(str[3] + "'");
                    sb.append(str[4] + "'");
                    sb.append(str2);
                    db.execSQL(sb.toString());
                }
                db.setTransactionSuccessful();
                db.endTransaction();

            }
        });

我希望用户能够按下 "Import CSV" 按钮并将数据插入 SQLite 数据库 table。但是 - 我在这部分有问题,特别是我在 btn_csv_import.setOnClickListener. 中需要的东西 我试着查看这个 Whosebug question,但我没有非常确定如何为显示 FileReader file = new FileReader(fileName);

的行正确获取行 fileName

或者 - 如果有人有更好的方法将 CSV 文件导入到 SQLite 数据库中,那么我希望得到一些帮助,谢谢!!

让我知道我是否可以添加任何其他详细信息以帮助更清楚地说明这一点。

将继续并关闭此问题。经过一番研究,我解决了这个问题,并采用了稍微不同的方式通过 CSV 将数据导入特定的 sqlite 数据库 table

这是我最终放在 btn_csv_import.setOnClickListener 中的内容:

// CSV Import button to get data from CSV file into database table
        btn_csv_import.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Access Database to be writable
                SQLiteOpenHelper database = new AccountDbHelper(getApplicationContext());
                SQLiteDatabase db = database.getWritableDatabase();


                InputStream inStream = null;
                try {
                    inStream = getContentResolver().openInputStream(returnUri);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    Log.e("ImportAccountActivity", "INPUT STREAM WAS NOT OPENED");
                }
                BufferedReader buffer = new BufferedReader(new InputStreamReader(inStream));
                String line = "";
                db.beginTransaction();
                // Have file skip first row with header columns
                boolean skip = true;
                try {
                    while ((line = buffer.readLine()) != null) {
                        // File skips first row and sets variable to false, so that all other
                        // lines get imported into DB
                        if(skip) {
                            skip = false; // Skip only the first line
                            continue; }



                        String[] colums = line.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);
                        if (colums.length != 5) {
                            Log.e("CSVParser", "Skipping Bad CSV Row");
                            Log.e("CSVParser", "Skipping:" + colums[4].trim());
                            Log.e("CSVParser", "Columns length: " + colums.length);
                            continue;
                        }




                        ContentValues cv = new ContentValues();
                        // ADDED replace for parsing tests
                        // cv.put("_id", colums[0].trim());
                        cv.put("account_title", colums[1].trim().replace('`',','));
                        cv.put("user_name", colums[2].trim().replace('`',','));
                        cv.put("account_password", colums[3].trim().replace('`',','));
                        cv.put("account_notes", colums[4].trim().replace('`',','));
                        db.insert(AccountLogin.AccountEntry.TABLE_NAME, null, cv);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.e("ImportAccountActivity", "DATABASE didn't have a chance to parse");
                    }
                    db.setTransactionSuccessful();
                    db.endTransaction();

                    Toast.makeText(ImportAccountActivity.this, R.string.toast_csv_import_sucessful,
                            Toast.LENGTH_LONG).show();

                // Open intent to go back to account_main.xml
                Intent intent = new Intent(ImportAccountActivity.this, AccountActivity.class);
                startActivity(intent);

希望这对外面的人有帮助!!