So I have a SQliteDatabase mDb. It only has one column, and its data are Strings for previously saved inputs. I'm trying to populate all the data from mDb into a String[] for AutoCompleteTextView (so that the autocomplete is based on previous inputs), and here's my code to get all of the String.
public String[] fetchAllSearch() {
ArrayList<String> allSearch = new ArrayList<String>();
Cursor c = mDb.rawQuery("select * from " + DATABASE_TABLE, null);
c.moveToFirst();
if (c.getCount() > 0) {
do {
allSearch.add(c.getString(c.getColumnIndex("KEY")));
} while (c.moveToNext());
}
String[] foo = (String[]) allSearch.toArray();
if (foo == null) {
foo = new String[] {""};
}
return foo;
}
my CREATE_TABLE command is
private static final String DATABASE_CREATE = "create table " + DATABASE_TABLE;
..
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
But for some reason the line mDb.rawQuery(...) is giving me "no such table found" exception, and for the life of me I can't figure out why. Any pointers?
What is the value of DATABASE_TABLE?
If it is just a table name, then the create statement is incomplete because it doesn't specify the columns.
If it is a name plus column definitions, then the select will not work.
So, you need to use different text in the two places you used DATABASE_TABLE
Try using the SQLite3 command line program to try out your SQL. E.g.,
sqlite> create table foo;
Error: near ";": syntax error
sqlite> create table foo(col);
sqlite> select * from foo(col);
Error: near "(": syntax error
sqlite>
Use SELECT column_name FROM table_name.
Avoid using * in the query as it might cause the problem related to primary key.
Related
I have a strings that contains c++ codes.
these codes might contain a single or double inverted quotes and many such thing,
I want to filter out these characters before executing the sql to insert this into the SQLite Database (Android) so, what java code should i run to do that without disturbing/distorting the c++ code, so that when i read the sql database the code should be as before.
You could filter (replace with nothing) when extracting the data using SQL.
e.g. such a query could be :-
SELECT replace(replace(col1,'''',''),'"','') FROM cpluspluscode;
where the respective column is col1 and the table is cpluspluscode.
The following is an example showing how this works:-
DROP TABLE IF EXISTS cpluspluscode;
CREATE TABLE IF NOT EXISTS cpluspluscode (col1 TEXT);
INSERT INTO cpluspluscode VALUES('''mytext'' "other text"');
SELECT * FROM cpluspluscode;
SELECT replace(replace(col1,'''',''),'"','') AS filtered FROM cpluspluscode;
The results from the above are :-
Without filtering :-
Filtered :-
The above takes advantage of the SQLite replace core function replace(X,Y,Z)
Unicode
If you wanted the to do the above using unicode then you could use :-
SELECT replace(replace(col1,char(0034),''),char(39),'') AS filtered FROM cpluspluscode;
This utilises the SQLite char core function (see link above).
The unicode core function can be used to find the unicode for a character (again see link above).
Android Example
Assuming a subclass of SQLiteOpenHelper is DatabaseHelper and this creates the table as per :-
public static final String TABLE_CPLUSPLUSCODE = "cpluspluscode";
public static final String COLUMN1 = "col1";
.........
#Override
public void onCreate(SQLiteDatabase db) {
String crtcpp = "CREATE TABLE IF NOT EXISTS " + TABLE_CPLUSPLUSCODE + "(" +
COLUMN1 + " TEXT" +
")";
db.execSQL(crtcpp);
}
And DatabaseHelper includes the methods :-
public long cppInsert(String value) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN1,value);
return db.insert(TABLE_CPLUSPLUSCODE,null,cv);
}
public Cursor getFiltered() {
SQLiteDatabase db = this.getWritableDatabase();
String[] columns = new String[]{"replace(replace(" + COLUMN1 + ",'''',''),'\"','') AS " + COLUMN1};
return db.query(TABLE_CPLUSPLUSCODE,columns,null,null,null,null,null);
}
public Cursor getUnfiltered() {
SQLiteDatabase db = this.getWritableDatabase();
return db.query(TABLE_CPLUSPLUSCODE,null,null,null,null, null, null);
}
Then using the following (in an Activity) :-
DatabaseHelper mDBHlp = new DatabaseHelper(this);
mDBHlp.cppInsert("''mydata'' \" other data\"");
Cursor csr1 = mDBHlp.getUnfiltered();
while (csr1.moveToNext()) {
Log.d("CSR1DATA",csr1.getString(csr1.getColumnIndex(DatabaseHelper.COLUMN1)));
}
csr1.close();
Cursor csr2 = mDBHlp.getFiltered();
while (csr2.moveToNext()) {
Log.d("CSR2DATA",csr2.getString(csr2.getColumnIndex(DatabaseHelper.COLUMN1)));
}
Results in :-
09-05 04:39:14.003 3471-3471/so52115977.so52115977 D/CSR1DATA: ''mydata'' " other data"
09-05 04:39:14.003 3471-3471/so52115977.so52115977 D/CSR2DATA: mydata other data
i.e. the second line is filtered accordingly.
I have done a lot of research and was unable to find a suitable method to delete all the tables in an SQLite database. Finally, I did a code to get all table names from the database and I tried to delete the tables using the retrieved table names one by one. It didn't work as well.
Please suggest me a method to delete all tables from the database.
This is the code that I used:
public void deleteall(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
do
{
db.delete(c.getString(0),null,null);
}while (c.moveToNext());
}
function deleteall() is called on button click whos code is given as below:
public void ButtonClick(View view)
{
String Button_text;
Button_text = ((Button) view).getText().toString();
if(Button_text.equals("Delete Database"))
{
DatabaseHelper a = new DatabaseHelper(this);
a.deleteall();
Toast.makeText(getApplicationContext(), "Database Deleted Succesfully!", Toast.LENGTH_SHORT).show();
}}
Use DROP TABLE:
// query to obtain the names of all tables in your database
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
List<String> tables = new ArrayList<>();
// iterate over the result set, adding every table name to a list
while (c.moveToNext()) {
tables.add(c.getString(0));
}
// call DROP TABLE on every table name
for (String table : tables) {
String dropQuery = "DROP TABLE IF EXISTS " + table;
db.execSQL(dropQuery);
}
Tim Biegeleisen's answer almost worked for me, but because I used AUTOINCREMENT primary keys in my tables, there was a table called sqlite_sequence. SQLite would crash when the routine tried to drop that table. I couldn't catch the exception either. Looking at https://www.sqlite.org/fileformat.html#internal_schema_objects, I learned that there could be several of these internal schema tables that I shouldn't drop. The documentation says that any of these tables have names beginning with sqlite_ so I wrote this method
private void dropAllUserTables(SQLiteDatabase db) {
Cursor cursor = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
//noinspection TryFinallyCanBeTryWithResources not available with API < 19
try {
List<String> tables = new ArrayList<>(cursor.getCount());
while (cursor.moveToNext()) {
tables.add(cursor.getString(0));
}
for (String table : tables) {
if (table.startsWith("sqlite_")) {
continue;
}
db.execSQL("DROP TABLE IF EXISTS " + table);
Log.v(LOG_TAG, "Dropped table " + table);
}
} finally {
cursor.close();
}
}
delete database instead of deleting tables and then create new with same name if you need. use following code
context.deleteDatabase(DATABASE_NAME);
or
context.deleteDatabase(path);
For me, the working solution is:
Cursor c = db.rawQuery(
"SELECT name FROM sqlite_master WHERE type IS 'table'" +
" AND name NOT IN ('sqlite_master', 'sqlite_sequence')",
null
);
if(c.moveToFirst()){
do{
db.execSQL("DROP TABLE " + c.getString(c.getColumnIndex("name")));
}while(c.moveToNext());
}
I have the following code in a bigger project:
final class DBlifetimeStatisticsHandler{ //implements DBvalueHandler<Cyclist, Double>{
private final String TAG = getClass().getName();
private static final boolean debug = true;
private final DBminMaxAvgHandler dbMinMaxAvgHandler = new DBminMaxAvgHandler();
// table name
private static final String TABLE_LIFETIME_STATISTICS = "lifetime_statistics";
// column names
private static final String KEY_LIFETIME_STATISTICS_ID = "lifetime_statistics_id";
private static final String KEY_MIN_MAX_AVG = "min_max_avg";
// table create statement
private static final String CREATE_TABLE = "CREATE TABLE "
+ TABLE_LIFETIME_STATISTICS + "("
+ KEY_LIFETIME_STATISTICS_ID + " LONG PRIMARY KEY NOT NULL,"
+ KEY_MIN_MAX_AVG + " LONG"
+ ")";
public void onCreateTable(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
public void onUpgrade(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LIFETIME_STATISTICS);
onCreateTable(db);
}
public long addValue(SQLiteDatabase db, Statistics Statistics ) {
ContentValues values = new ContentValues();
long ID = getLatestID(db)+1;
values.put(KEY_STATISTICS_ID, ID);
... //not important to the question
}
private long getLatestID(SQLiteDatabase db){
String selectQuery = "SELECT MAX(" + KEY_STATISTICS_ID +") FROM " + TABLE_STATISTICS;
Cursor c = db.rawQuery(selectQuery, null);
c.moveToFirst();
int id = 0;
Log.e("count", String.valueOf(c.getCount()));
if (c.moveToFirst()){
...
}
return id;
}
}
After I updated the table it is created again. So when I try to add a new value I had problems cause it always jumped into the if clause because c.moveToFirst() always returned true.
So I tried to tried to check if c.getCount() would return true but sadly it does always return 1. So the question is: Why would it return 1 on an empty table? (I do use Questoid SQLite Browser and the table is really empty)
You use aggregate function MAX, so read documentation:
There are two types of simple SELECT statement - aggregate and non-aggregate queries. A simple SELECT statement is an aggregate query if it contains either a GROUP BY clause or one or more aggregate functions in the result-set.
An aggregate query without a GROUP BY clause always returns exactly one row of data, even if there are zero rows of input data.
It might be some kind of a buggy behavior when using MAX. Check this link too Android database (SQLite) returns a non-empty cursor from an empty table
this is my solution
public Boolean isNotEmpty(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_STATISTICS, null);
while (cursor.moveToNext() ) {
return true;
}
return false;
}
You are getting a result with one row in your Cursor because that is what you requested.
The result is a single column called MAX with a value that will be the max id of all the rows in your table. In your case of an empty table, this value is null.
I am using group by to resolve this. Please check my example :
SELECT COUNT(*) FROM " + TABLE_NAME + " WHERE isSynced=0 group by isSynced
I resolve this probme this way:
SELECT COUNT(*) AS numero, MAX(tagua_lagps) as tmp_max_lagps, MAX(tagua_logps) as tmp_max_logps, MIN(tagua_lagps) as tmp_min_lagps, MIN(tagua_logps) as tmp_min_logps FROM TAB_AGUA
On empty table, c.getCount(); gives 1 but values are NULL. But numero (c.getString(c.getColumnIndex("numero")) has a value of 0.
So rather than checking c.getCount() you must check the result of count(*).
I am getting an error with a rawquery on Eclipse on a DB in the assets directory. The DB is 'pre-loaded' with tables and data and the SQL string, first comment line, works in SQLite DB browser. When I copy the SQL string to code and modify to remove quotes it errors. The code below is from the 'standard' public class DataBaseHelper extends SQLiteOpenHelper{ .I am new to android/java and would appreciate any assistance or suggestions.
public Cursor getAllSectionDescriptions( String DBtable, String source){
//Works in DB: SELECT "Description" FROM "SectionProps" WHERE Source = "UK"
//String q = "SELECT Description FROM SectionProps WHERE Source = UK " ; <= errors in code
String q = "SELECT Description FROM " + DBtable + " WHERE Source = " + source + " "; //<== errors in code
//06-24 16:53:03.373: ERROR/AndroidRuntime(1000): Caused by: android.database.sqlite.SQLiteException: no such table: SectionProps: , while compiling: SELECT Description FROM SectionProps WHERE Source = UK
Cursor mCursor = myDataBase.rawQuery(q, null);
mCursor.moveToFirst();
return mCursor;
}//end cursor
Looks like you have to put double quotes around your object names. So you'll want to do this:
String q = "SELECT \"Description\" FROM \"" + DBtable + "\" WHERE Source = \"" + source + "\" ";
Note the double quotes preceded by the escape character '\'
To execute queries, there are two methods: Execute db.rawQuery method Execute db.query method To execute a raw query to retrieve all departments:
Cursor getAllDepts()
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor cur=db.rawQuery("SELECT "+colDeptID+" as _id,
"+colDeptName+" from "+deptTable,new String [] {});
return cur;
}
The rawQuery method has two parameters: String query: The select statement String[] selection args: The arguments if a WHERE clause is included in the select statement Notes The result of a query is returned in Cursor object. In a select statement if the primary key column (the id column) of the table has a name other than _id, then you have to use an alias in the form SELECT [Column Name] as _id cause the Cursor object always expects that the primary key column has the name _id or it will throw an exception .
I am getting inconsistent results between two methods of reading the columns in an Android SQLite database.
First, this is part of a database upgrade routine as per the accepted answer here: Upgrade SQLite database from one version to another?
The technique involves moving the current table away with a temporary name, creating a new table with the new schema, and then copying relevant data from the old table into the new one before deleting the old temporary table.
The particular problem I have is when I remove a column from the schema. So, a particular column exists in the old version of the table, but not the new one.
That answer suggests using a method like this to list the columns in the table:
/**
* Returns a list of the table's column names.
*/
private List<String> getColumns(SQLiteDatabase db, final String tableName) {
List<String> ar = null;
Cursor c = null;
try {
c = db.rawQuery("SELECT * FROM " + tableName + " LIMIT 1", null);
if (c != null) {
ar = new ArrayList<String>(Arrays.asList(c.getColumnNames()));
}
} finally {
if (c != null)
c.close();
}
return ar;
}
That works fine on the old table, before I move it away with a temporary name and replace it. When I run the same query again later, on the newly-created empty table, it still lists the old table schema with the name of the column which no longer exists. It looks as if it's reusing stale cached results for that query.
If I read the columns a different way, using this instead, then it returns the new column list as expected:
private void listColumns(SQLiteDatabase db, final String tableName) {
final String query = "PRAGMA table_info(" + tableName + ");";
Cursor c = db.rawQuery(query, null);
while (c.moveToNext()) {
Log.v("MyApp", "Column: " + c.getString(1));
}
c.close();
}
The complete sequence is:
final String tempTableName = "temp_" + tableName;
table.addToDb(db); // ensure it exists to start with
// get column names of existing table
final List<String> columns = getColumns(db, tableName);
// backup table
db.execSQL("ALTER TABLE " + tableName + " RENAME TO " + tempTableName);
// create new table
table.addToDb(db);
// delete old columns which aren't in the new schema
columns.retainAll(getColumns(db, tableName));
// restore data from old into new table
String columnList = TextUtils.join(",", columns);
db.execSQL(String.format("INSERT INTO %s (%s) SELECT %s from %s", tableName, columnList, columnList,
tempTableName));
// remove backup
db.execSQL(DROP_TABLE + tempTableName);
What's the reason for the different results?
I assume you have done something similar to this:
ALTER TABLE "main"."mytable" RENAME TO "newtable";
CREATE TABLE "main"."mytable" ("key1" text PRIMARY KEY,"key2" text,"key3" text);
INSERT INTO "main"."mytable" SELECT "key1","key2","key3" FROM "main"."newtable";
DROP TABLE "main"."newtable";
If you have, please share the equivalent code, just to rule out any errors with this part.
I never got to the bottom of this. I just ended up using the second method I mentioned, which doesn't exhibit the problem.