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

问题描述 投票:0回答:1

我正在构建通过CSV文件将数据导入Android应用程序用户界面内的SQLite数据库表的功​​能。

[带有一个带有OnClickListener的按钮,该按钮允许用户选择要上传的文件。选择文件后,它们将返回到“导入帐户”页面,该页面底部还有一个“导入CSV”按钮。

OnClickListener的ImportAccountActivity Java代码:

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();

            }
        });

我希望用户随后能够按下“导入CSV”按钮,并将数据插入到SQLite数据库表中。但是-我在这部分上遇到了问题,特别是我需要在btn_csv_import.setOnClickListener。中拥有的内容。我尝试查看此StackOverflow question,但是我不太确定如何获取行fileName 正确显示FileReader file = new FileReader(fileName);

的行

或者-如果有人有更好的方法将CSV文件导入SQLite数据库,那么我很乐意提供帮助,谢谢!!

让我知道是否可以添加其他详细信息以帮助您更清楚地了解这一点。

android csv android-sqlite
1个回答
0
投票

将继续并结束这个问题。经过研究后,我得以解决该问题,并采取了略有不同的途径,以通过CSV将数据导入到特定的sqlite数据库表中。

这是我最终放入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);

希望这可以帮助某人!

© www.soinside.com 2019 - 2024. All rights reserved.