简体   繁体   中英

how to import CSV file in SQLite data in android?

public class MainActivity extends Activity {
    Context context;
    SQLiteDatabase db;
    public static final String CONTACTS_TABLE_NAME = "contacts";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        db.execSQL(
            "create table contacts " +
            "(id integer primary key, name text,dt1 text,dt2 text, dt3 text,)"
        );

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

        BufferedReader br = new BufferedReader(new InputStreamReader(inStream));
        Log.e("shashank br ", "" + br);
        String line = "";
        String tableName = "contacts";
        String columns = "id, name, phone, email, discipline,place";
        String str1 = "INSERT INTO " + tableName + " (" + columns + ") values(";
        String str2 = ");";
        Log.e("shashank ", "" + str1);
        Log.e("shashank ", "" + str2);

        db.beginTransaction();
        try {
            while ((line = br.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();
        } catch (IOException e) {
        }
    }
}

Beginner in android. I want to import CSV file and upload in SQLIte database .please can u suggest me.how should I create a database in this class.

get this link in this post how to create db.this SQLiteDatabase db;????

There is an extra comma in your create table contacts statement.

And your column names are not matching with the column names in INSERT INTO query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM