Advertisement
egslava

DBHelper (csv -> sqlite)

Feb 8th, 2015
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.98 KB | None | 0 0
  1. package ru.egslava.tatar_dictionary;
  2.  
  3. import android.content.Context;
  4. import android.database.sqlite.SQLiteDatabase;
  5. import android.database.sqlite.SQLiteOpenHelper;
  6.  
  7. import org.apache.commons.lang3.StringUtils;
  8.  
  9. import java.io.BufferedReader;
  10. import java.io.IOException;
  11. import java.io.InputStream;
  12. import java.io.InputStreamReader;
  13.  
  14. import ru.egslava.tatar_dictionary.R;
  15.  
  16. /**
  17.  * Created by egslava on 29/11/14.
  18.  */
  19. public class DBHelper extends SQLiteOpenHelper {
  20.  
  21.     public static String createTable(String tableName) {
  22.         return String.format(
  23.                 "CREATE TABLE %s ( `_id` INTEGER, `word` CHAR(255), `definition` TEXT, PRIMARY KEY(_id) );",
  24.                 tableName);
  25.     }
  26.  
  27.     public static String insertWord(String tableName) {
  28.         return String.format( "INSERT INTO %s (word,definition) VALUES (?, ?)",
  29.                 tableName);
  30.     }
  31.  
  32.  
  33.     private final Context context;
  34.  
  35.     public DBHelper(Context context) {
  36.         super(context, "db", null, 1);
  37.         this.context = context;
  38.     }
  39.  
  40.     @Override
  41.     public void onCreate(SQLiteDatabase db) {
  42.         fillWords(db, "rus_tatar", R.raw.rus_tatar);
  43.         fillWords(db, "tatar_rus", R.raw.tatar_rus);
  44.  
  45.     }
  46.  
  47.     private void fillWords(SQLiteDatabase db, String tableName, int wordFileResId) {
  48.         try {
  49.             db.execSQL( createTable(tableName));
  50.  
  51.             InputStream inputStream = context.getResources().openRawResource( wordFileResId );
  52.             InputStreamReader reader = new InputStreamReader(inputStream);
  53.             BufferedReader buf = new BufferedReader(reader);
  54.  
  55.             String s;
  56.             while( buf.ready() ){
  57.                 s = buf.readLine();
  58.                 db.execSQL(insertWord( tableName), StringUtils.split(s, '%'));
  59.             }
  60.  
  61.         } catch (IOException e) {
  62.             throw new RuntimeException(e);
  63.         }
  64.     }
  65.  
  66.     @Override
  67.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  68.  
  69.     }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement