开发者

How to import a .csv file to SQLite for Android?

I have never used a database before, so bear with me. I am programming for the Android tablet and don't have one in my possess开发者_运维百科ion yet, but will be getting it within a week. I have a .csv file in Excel whose data I would like to use in my app. I am aware that Androids come with SQLite, but exactly what that is or how to use it is beyond me.

I'm going to work on learning about databases as I go, but first-- How do I get my csv file into SQLite? Can I do that from my PC or do I have to wait and do it on the tablet? What do I need to download to make this happen, what exactly and where do I need to type, etc... I need really basic instructions on doing this and everything I've found online has gone way over my head due to my complete lack of experience.


You can download SQLite to you PC and tinker with it in the meantime. The import doesn't have to happen on the phone.

You can find many ways to do this process in their wiki.


Try something like this:

 ...
 BufferedReader buffer = new BufferedReader(new InputStreamReader(inStream));
 String line = "";
 db.beginTransaction();
        try {
            while ((line = buffer.readLine()) != null) {
            String[] colums = line.split(",");
                if (colums.length != 4) {
                    Log.d("CSVParser", "Skipping Bad CSV Row");
                    continue;
                }
                ContentValues cv = new ContentValues(3);
                cv.put(dbCol0, colums[0].trim());
                cv.put(dbCol1, colums[1].trim());
                cv.put(dbCol2, colums[2].trim());
                cv.put(dbCol4, colums[3].trim());
                db.insert(TABLE, null, cv);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
   db.setTransactionSuccessful();
   db.endTransaction();

How to read the CSV file

Copy file.csv into the assets folder, and read it like this:

String mCSVfile = "file.csv";
AssetManager manager = context.getAssets();
InputStream inStream = null;
try {
     inStream = manager.open(mCSVfile);
    } catch (IOException e) {
     e.printStackTrace();
    }

 BufferedReader buffer = new BufferedReader(new InputStreamReader(inStream));
...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜