0

I am using SQLite database to store few Strings. I am using this code to add those strings when i launch the application for the 1st time.

DatabaseHandler db = new DatabaseHandler(this);
db.addProducts(//lot of strings appended to make a single String);
db.close();

DatabaseHandler is:

public class DatabaseHandler extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "my_db";
    private static final String TABLE_NAME = "products";
    private static final String KEY_NAME = "pname";

    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        String CREATE_PRODUCTS_TABLE = "CREATE TABLE " + TABLE_NAME + "("
                + KEY_NAME + " TEXT" + ")";
        db.execSQL(CREATE_PRODUCTS_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }

    public void addProducts(String product_name) {

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, product_name); // Product Name
        db.insert(TABLE_NAME, null, values);
        db.close();
    }

    public String getProducts() {

        SQLiteDatabase db = this.getReadableDatabase();
        String selectQuery = "SELECT  * FROM " + TABLE_NAME;
        Cursor cursor = db.rawQuery(selectQuery, null);
        String s = "default";
        if (cursor.moveToFirst()) {
            int n = cursor.getCount();
            s = cursor.getString(0);
        }
        cursor.close();
        return s;
    }
}

The problem is if i am not checking whether the table products exists, i will call the db.addProducts(""); every time the application is lauched. And the cursor count increases by 1 everytime and eventually says need to extend db something like that. How can i check if the Table is already present??

I can only find this: How to check if database exists :

public static boolean checkDataBase(String DB_FULL_PATH) {
    SQLiteDatabase checkDB = null;
    try {
        checkDB = SQLiteDatabase.openDatabase(DB_FULL_PATH, null,
                SQLiteDatabase.OPEN_READONLY);
        checkDB.close();
    } catch (SQLiteException e) {
        // database doesn't exist yet.
    }
    return checkDB != null ? true : false;
}

Here i am stuck with the path. How can i get the path of the Database?

Moreover it would be useful if i check whether a Table exists rather than the Database.

Thank You

Archie.bpgc
  • 23,812
  • 38
  • 150
  • 226

4 Answers4

0

use this in the Raw Query CREATE TABLE IF NOT EXISTS "+TABLENAME+"; this wont create a table everytime

Anuj
  • 2,065
  • 22
  • 23
  • But i believe, the cursor count is increasing, because new table is not created but new row is added, I mean the same String is added every time i launch the app – Archie.bpgc Sep 07 '12 at 07:06
  • What you can do for that is, use a `ON DUPLICATE KEY UPDATE` key to update whenever there is a duplicate value in the Table, it would simply update if data matches and inserts if it doesn't match – Anuj Sep 07 '12 at 07:11
  • Let me provide you with a link too , so that you can go in depth regarding the same. [link] http://stackoverflow.com/questions/5930812/insert-into-mysql-database-if-records-already-exists-then-update – Anuj Sep 07 '12 at 07:12
0

You have only one table in your database , first check your database is created or not using this

        private boolean checkDataBase() {
       // TODO Auto-generated method stub
          File dbFile = new File(DB_PATH + DB_NAME);
          return dbFile.exists();
   }

To analyze the Database Use SQlite Database Brouser

Rajendra
  • 1,700
  • 14
  • 17
0

A more elegant solution, in my opinion, would be to have something like a Shared Reference. I'm imagining you want to do this so you can check for something in the ways of "Has the user started the app for the first time?".

You can do something like this:

public void firstRunPreferences(){
            Context mContext = this.getApplicationContext();
            mPrefs = mContext.getSharedPreferences("myAppPrefs", 0);
        }

public void setRunned(){
        SharedPreferences.Editor editor = mPrefs.edit();
        editor.putBoolean("firstRun", false);
        editor.commit();
    }

    public boolean getFirstRun(){
        return mPrefs.getBoolean("firstRun", true);
    }

The first method gets you an instance of your app's sharedPreferences, while the second manipulates and adds a boolean.

You can call the method at any point you like (for instance replacing setRunned with dbCreated when you first instantiate the DB Helper class).

Best of luck coding!

Eugen
  • 1,537
  • 7
  • 29
  • 57
0

I think this would be helpfull for the PATH-Question. Found in the tutorial from: http://www.vogella.com/articles/AndroidSQLite/article.html#sqliteoverview " Access to an SQLite database involves accessing the filesystem. This can be slow. Therefore it is recommended to perform database operations asynchronously, for example inside the AsyncTask class.

If your application creates a database, this database is by default saved in the directory DATA/data/APP_NAME/databases/FILENAME.

The parts of the above directory are constructed based on the following rules. DATA is the path which the Environment.getDataDirectory() method returns. APP_NAME is your application name. FILENAME is the name you specify in your application code for the database. "

So, for one db exists one file in die filesystem. That is /data/data/package.name/databases. package.name is the the packagename of your application. databases is the name of your db.

goojr
  • 230
  • 3
  • 5
  • APP_NAME is the appName i get in String.xml resource right? and what is databases? – Archie.bpgc Sep 07 '12 at 07:53
  • and Environment.getDataDirectory() returns a File should i call toString() on it and use in the PATH? – Archie.bpgc Sep 07 '12 at 08:00
  • Environment.getDataDirectory() returns the data directory. databases is the directory where you find you db. App_Name is the package name of your application. – goojr Sep 07 '12 at 08:50
  • so how to use this "Environment.getDataDirectory()" in the path? call toString(); ??...and are you sure APP_NAME is the Package Name but not the app_name in String.xml resource? – Archie.bpgc Sep 07 '12 at 08:53
  • try to access to the emulator like adb -s emulator-5554 shell. than handle to the directories. for my app i call command "cd /data/data/de.obi.farbfinder/databases". in databases i found my db, for example farbfinder.db. i call command "sqlite3 farbfinder.db". with command ".tables" i get the list of tables. or for your code i use DB_FULL_PATH = Environment.getDataDirectory() + "/data/de.obi.farbfinder/databases/farbfinder.db. the variable checkDB return true. – goojr Sep 07 '12 at 08:57
  • farbfinder.db in my case is my_db.db right?? which i declared in helper class – Archie.bpgc Sep 07 '12 at 09:03
  • I am getting this error when i used your code for DB PATH: sqlite returned: error code = 14, msg = cannot open file at source line ....25467sqlite3_open_v2("/data/data/com.Android.WiC_MobileApp/databases/wic.db", &handle, 1, NULL) failed – Archie.bpgc Sep 07 '12 at 09:06
  • in your case farbfinder.db is my_db.db. you check in the emulator if your db exists in the databases directory? (using console) – goojr Sep 07 '12 at 09:12