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