Example usage for android.database.sqlite SQLiteDatabase openOrCreateDatabase

List of usage examples for android.database.sqlite SQLiteDatabase openOrCreateDatabase

Introduction

In this page you can find the example usage for android.database.sqlite SQLiteDatabase openOrCreateDatabase.

Prototype

public static SQLiteDatabase openOrCreateDatabase(@NonNull String path, @Nullable CursorFactory factory) 

Source Link

Document

Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY).

Usage

From source file:Main.java

public static Map<Integer, List> getProvince(File file) {

    String sql = "select provinceid ,province from province ";
    SQLiteDatabase db = null;// w  w  w  . ja va  2s . c  o  m
    Cursor c = null;
    Map<Integer, List> provinceData = new HashMap<Integer, List>();
    //List provinceList = null;
    try {
        db = SQLiteDatabase.openOrCreateDatabase(file, null);
        c = db.rawQuery(sql, null);
        List provinceList1 = new ArrayList();
        List provinceList2 = new ArrayList();
        while (c.moveToNext()) {
            Map provinceMap = new HashMap();
            provinceMap.put(c.getString(1), c.getInt(0));
            provinceList1.add(provinceMap);
            provinceList2.add(c.getString(1));
        }
        provinceData.put(0, provinceList1);
        provinceData.put(1, provinceList2);
    } catch (Exception e) {
        Log.d("WineStock", "getProvince:" + e.getMessage());
    } finally {
        if (c != null) {
            c.close();
        }
        if (db != null) {
            db.close();
        }
    }
    return provinceData;
}

From source file:Main.java

public static Map<Integer, List> getCityByPid(int id, File file) {

    String sql = "select cityid,city  from city where provinceid= " + id;
    SQLiteDatabase db = null;/*from  w w  w  .ja  va  2 s  .  com*/
    Cursor c = null;
    Map<Integer, List> cityData = new HashMap<Integer, List>();
    //List cityList = null;
    try {
        db = SQLiteDatabase.openOrCreateDatabase(file, null);
        c = db.rawQuery(sql, null);
        List cityList1 = new ArrayList();
        List cityList2 = new ArrayList();
        while (c.moveToNext()) {
            Map cityMap = new HashMap();
            cityMap.put(c.getString(1), c.getInt(0));
            cityList1.add(cityMap);
            cityList2.add(c.getString(1));
        }
        cityData.put(0, cityList1);
        cityData.put(1, cityList2);

    } catch (Exception e) {
        Log.d("WineStock", "getCityByPid:" + e.getMessage());
    } finally {
        if (c != null) {
            c.close();
        }
        if (db != null) {
            db.close();
        }
    }
    return cityData;
}

From source file:Main.java

public static Map<Integer, List> getAreaByPid(int id, File file) {

    String sql = "select area,areaid  from area where cityid= " + id;
    SQLiteDatabase db = null;/*from w w  w  .j av a  2s. co m*/
    Cursor c = null;
    List<String> areaList = null;
    List areaIdList = null;
    Map<Integer, List> areaData = new HashMap<Integer, List>();
    try {
        db = SQLiteDatabase.openOrCreateDatabase(file, null);
        c = db.rawQuery(sql, null);
        areaList = new ArrayList<String>();
        areaIdList = new ArrayList<String>();

        while (c.moveToNext()) {
            Map areaMap = new HashMap();
            areaMap.put(c.getString(0), c.getInt(1));
            areaList.add(c.getString(0));
            areaIdList.add(areaMap);
        }
        areaData.put(0, areaList);
        areaData.put(1, areaIdList);
    } catch (Exception e) {
        Log.d("WineStock", "getAreaByPid:" + e.getMessage());
    } finally {
        if (c != null) {
            c.close();
        }
        if (db != null) {
            db.close();
        }
    }
    return areaData;
}

From source file:com.lewa.crazychapter11.DBTest.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.data_base_layout);

    db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString() + "/my.db3", null);
    listView = (ListView) findViewById(R.id.db_show);
    try {//from  www.  ja va2s .co  m
        Cursor cursor = db.rawQuery("select*from news_inf", null);
        inflateList(cursor);
        //}catch(Exception e){
        //Log.i("DBTest","error db load");
    } catch (SQLiteException se) {
        Log.i("DBTest", "SQLiteException error db load");
    } catch (IndexOutOfBoundsException e) {
        //         e.printStackTrace();
        Log.i("DBTest", "IndexOutOfBoundsException error db load");
    }

    bn = (Button) findViewById(R.id.btn_ok);

    bn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View source) {
            String title = ((EditText) findViewById(R.id.db_title)).getText().toString();
            String content = ((EditText) findViewById(R.id.db_content)).getText().toString();
            try {
                Log.i("DBTest", "insert 1111");
                insertData(db, title, content);
                Cursor cursor = db.rawQuery("select*from news_inf", null);
                inflateList(cursor);
            } catch (SQLiteException se) {
                Log.i("DBTest", "insert 22222");
                db.execSQL("create table news_inf(_id integer" + " primary key autoincrement,"
                        + " news_title varchar(50)," + " news_content varchar(255))");
                insertData(db, title, content);
                Cursor cursor = db.rawQuery("select*from news_inf", null);
                inflateList(cursor);
            }
        }
    });
}

From source file:org.ado.minesync.MineSyncDbOpenHelperTest.java

public void setUp() throws Exception {
    context = new RenamingDelegatingContext(getContext(), "test_");
    database = SQLiteDatabase.openOrCreateDatabase(getDatabasePath().getPath(), null);
    unitUnderTest = MineSyncDbOpenHelper.getInstance(context);
}

From source file:io.jawg.osmcontributor.utils.core.database.DatabaseUpgradeTest.java

@Test
public void upgrade() throws Exception {
    System.out.println(new File(".").getAbsolutePath());
    OsmSqliteOpenHelper openHelper = new OsmSqliteOpenHelper(Robolectric.application);

    SQLiteDatabase newDb = SQLiteDatabase.openOrCreateDatabase(newDbFile, null);
    openHelper.onCreate(newDb);/* w  w w.java  2  s  .  c om*/

    SQLiteDatabase upgradedDb = SQLiteDatabase.openDatabase(updatedDbFile.getAbsolutePath(), null,
            SQLiteDatabase.OPEN_READWRITE);
    openHelper.onUpgrade(upgradedDb, 1, OsmSqliteOpenHelper.CURRENT_VERSION);

    openHelper.close();

    Class.forName("org.sqlite.JDBC");
    String baseJdbcUrl = "jdbc:sqlite:";

    Set<String> newContents = extractContent(baseJdbcUrl + newDbFile.getAbsolutePath());
    Set<String> updatedContents = extractContent(baseJdbcUrl + updatedDbFile.getAbsolutePath());

    assertThat(updatedContents).containsAll(newContents);
    assertThat(updatedContents).isEqualTo(newContents);

}

From source file:org.leopub.mat.model.User.java

private void initDatabase() {
    mDatabase = SQLiteDatabase.openOrCreateDatabase(mConfigure.getSQLitePath(), null);
    // create table contact
    String query = "CREATE TABLE IF NOT EXISTS contact (`id` integer PRIMARY KEY, name varchar(255), name_char varchar(10), type char, unit varchar(10), title varchar(10), `f` integer, `b` integer, `t` integer, timestamp timestamp);";
    mDatabase.execSQL(query);/* w  ww  .  j av a  2  s  . c o m*/
    mDatabase.execSQL("CREATE INDEX IF NOT EXISTS idx_contact_timestamp ON contact (timestamp);");
    mDatabase.execSQL("CREATE INDEX IF NOT EXISTS idx_contact_unit ON contact (unit);");
    mDatabase.execSQL("CREATE INDEX IF NOT EXISTS idx_contact_name_char ON contact (name_char);");
    mDatabase.execSQL("CREATE INDEX IF NOT EXISTS idx_contact_f ON contact (f);");
    mDatabase.execSQL("CREATE INDEX IF NOT EXISTS idx_contact_b ON contact (b);");
    mDatabase.execSQL("CREATE INDEX IF NOT EXISTS idx_contact_t ON contact (t);");
    // create table inbox 
    mDatabase.execSQL(
            "CREATE TABLE IF NOT EXISTS `inbox` (`msg_id` integer PRIMARY KEY, `src_id` integer, `src_title` varchar(40), param integer, `type` integer, `start_time` datetime, `end_time` datetime, place varchar(160), `text` varchar(2048), `status` integer, `timestamp` timestamp);");
    mDatabase.execSQL("CREATE INDEX IF NOT EXISTS idx_inbox_timestamp ON inbox (`timestamp`);");
    mDatabase.execSQL("CREATE INDEX IF NOT EXISTS idx_inbox_status ON inbox(`status`);");
    // create table sent
    mDatabase.execSQL(
            "CREATE TABLE IF NOT EXISTS sent (`msg_id` integer PRIMARY KEY, `dst_str` varchar(300), `dst_title` varchar(300), parsm integer, `type` integer, `start_time` datetime, `end_time` datetime, place varchar(160), `text` varchar(2048), `status` integer, `timestamp` timestamp);");
    mDatabase.execSQL("CREATE INDEX IF NOT EXISTS idx_sent_timestamp ON sent (`timestamp`);");
    mDatabase.execSQL("CREATE INDEX IF NOT EXISTS idx_sent_status ON sent (`status`);");
    // create table confirm
    mDatabase.execSQL(
            "CREATE TABLE IF NOT EXISTS `confirm` (confirm_id integer PRIMARY KEY, `msg_id` integer, dst_id integer, dst_title varchar(40), `status` integer, timestamp timestamp);");
    mDatabase.execSQL("CREATE INDEX IF NOT EXISTS idx_confirm_timestamp ON confirm(`timestamp`);");
    mDatabase.execSQL("CREATE INDEX IF NOT EXISTS idx_confirm_msg ON confirm(`msg_id`);");
    // create table update_record
    mDatabase.execSQL(
            "CREATE TABLE IF NOT EXISTS `sync_record`(`id` integer PRIMARY KEY, timestamp timestamp, length integer, updated integer)");
    mDatabase.execSQL("CREATE INDEX IF NOT EXISTS idx_sync_record_timestamp ON sync_record(`timestamp`);");
    mDatabase.execSQL("CREATE INDEX IF NOT EXISTS idx_sync_record_updated ON sync_record(`updated`);");
}

From source file:com.polyvi.xface.extension.XStorageExt.java

/**
 * ?./*  ww w.  ja  va  2  s.  c om*/
 *
 * @param db
 *            ???
 */
private boolean openDatabase(XIWebContext webContext, String db) {
    if (null != mMyDb) {
        mMyDb.close();
    }

    File dbDir = new File(webContext.getApplication().getDataDir(), DB_DIR_NAME);
    if (!dbDir.exists()) {
        dbDir.mkdirs();
    }
    boolean isValidDbPath = true;
    try {
        // ???openDatabase???null??null???????
        String dbPath = new File(dbDir, db).getCanonicalPath();
        // ?????appData?database
        if (!XFileUtils.isFileAncestorOf(dbDir.getAbsolutePath(), dbPath)) {
            XLog.e(CLASS_NAME, dbPath);
            isValidDbPath = false;
        } else {
            mMyDb = SQLiteDatabase.openOrCreateDatabase(dbPath, null);
        }
    } catch (IOException e) {
        isValidDbPath = false;
        XLog.e(CLASS_NAME, e.toString());
    }
    return isValidDbPath;
}

From source file:course1778.mobileapp.safeMedicare.Main.FamMemFrag.java

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

    InputStream inputStream1 = getResources().openRawResource(R.raw.med_interaction);

    try {//from   www  . j  av a  2 s  . c o m
        med_interaction = SQLiteDatabase.openOrCreateDatabase(stream2file(inputStream1), null);
    } catch (IOException e) {
        System.out.print(e);
    }

    InputStream inputStream2 = getResources().openRawResource(R.raw.med_list);

    try {
        med_list = SQLiteDatabase.openOrCreateDatabase(stream2file(inputStream2), null);
    } catch (IOException e) {
        System.out.print(e);
    }

    setHasOptionsMenu(true);
    setRetainInstance(true);
}

From source file:com.HskPackage.HskNamespace.HSK1ProjectActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);/*from  www  .ja v  a 2 s.  co m*/

    final TextView codice = (TextView) findViewById(R.id.codice);
    final Button carattere = (Button) findViewById(R.id.carattere);
    final TextView fonetica = (TextView) findViewById(R.id.fonetica);
    final TextView significato = (TextView) findViewById(R.id.significato);

    /*********** CREATE A DATABASE ******************************************************/
    final String DB_PATH = "/data/data/com.HskPackage.HskNamespace/";
    final String DB_NAME = "chineseX.db";
    SQLiteDatabase db = null;

    boolean exists = (new File(DB_PATH + DB_NAME)).exists();

    AssetManager assetManager = getAssets();

    if (!exists) {
        try {
            InputStream in = assetManager.open(DB_NAME);
            OutputStream out = new FileOutputStream(DB_PATH + DB_NAME);
            copyFile(in, out);
            in.close();
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        File dbFile = new File(DB_PATH + DB_NAME);
        db = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
    } else {
        File dbFile = new File(DB_PATH + DB_NAME);
        db = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
    }

    final Integer valore = 1;
    //String query = "SELECT * FROM chineseX";
    String query = "SELECT * FROM chineseX where _id = ? ";
    String[] selectionArgs = { valore.toString() };
    Cursor cursor = null;
    cursor = db.rawQuery(query, selectionArgs);
    //cursor = db.rawQuery(query, null);
    int count = cursor.getCount();
    System.out.println("il numero di dati contenuti nel database " + count);
    while (cursor.moveToNext()) {
        long id = cursor.getLong(0);
        System.out.println("Questo  l'ID ====>" + id);
        scodice = cursor.getString(1);
        codice.setText(scodice);
        System.out.println("Questo  il codice ====>" + codice);
        scarattere = cursor.getString(2);
        carattere.setText(scarattere);
        System.out.println("Questo  il carattere ====>" + carattere);
        sfonetica = cursor.getString(3);
        fonetica.setText(sfonetica);
        System.out.println("Questo  il fonet ====>" + fonetica);

        ssignificato = cursor.getString(4);
        significato.setText("?? - Visualizza Significato");
        System.out.println("Questo  il carattere ====>" + ssignificato);
    }
    //fine
    db.close();

    //set up sound button
    final MediaPlayer mpButtonClick = MediaPlayer.create(this, R.raw.hangout_ringtone);

    //final MediaPlayer chword001 = MediaPlayer.create(this, R.raw.ayi001);

    /*
                    
            // set up change Images 
                    
            miaImmagine = (ImageView) findViewById(R.id.Image); 
            // dichiaro  l'oggetto image view
                 
            miaImmagine.setImageResource(R.drawable.uno1);
            // associo l'immagine alla  figura uno
               
            // setto un evento di cattura del click sull'immagine
            miaImmagine.setOnClickListener( new OnClickListener() 
            {
                public void onClick(View arg0) {
                   //chword001.start();
                }       
            }) ;
          */

    final Intent first = new Intent(this, Activity2.class);
    final Intent immagine = new Intent(this, Activity3.class);

    /*
     * Un intent  definito nella javadoc della classe android.content.Intent come una 
     * "descrizione astratta dell'operazione da eseguire".
     * E un intent ESPLICITO perch cosciamo il destinatario.
     * Passiamo come parametri il context attuale ed la classe che identifica l'activity di destinazione.
     * E' importante che la classe sia registrata nell'AndroidManifest.xml
     * */

    Button b = (Button) this.findViewById(R.id.button1);
    Button b2 = (Button) this.findViewById(R.id.button2);
    Button b3 = (Button) this.findViewById(R.id.carattere);

    b.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {
            Integer valore = 1;
            valore = valore + 1;
            if (valore >= 153) {
                valore = 1;
            }

            System.out.println("AVANTI" + valore);
            first.putExtra("AVANTI", valore);
            startActivity(first);
            finish();
            mpButtonClick.start();
        }
    });

    b2.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {

            Integer valore = 153;

            System.out.println("AVANTI == >" + valore);
            first.putExtra("AVANTI", valore);
            startActivity(first);
            finish();
            mpButtonClick.start();
        }
    });

    b3.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {

            Integer valore = 1;

            System.out.println("AVANTI" + valore);

            immagine.putExtra("AVANTI", valore);

            startActivity(immagine);
            finish();
            mpButtonClick.start();
        }
    });
}