SQL open a table confusion - android

I needed to store some data related to class periods in an Android project. After looking at my options, I thought a SQL database would be a good choice. Unfortunately, I can't seem to get my statement to actually open a database. My open database statement string goes like this:
"create table "+ DATABASE_PERIOD+" (_id integer primary key autoincrement,"
+KEY_CLASSTITLE+" text not null, "+KEY_PERIOD+" text not null,
"+KEY_XPERIODS+" text not null, "+KEY_DOUBLEPERIODS+" text not null);
I based it off of the Notepad project on the Android website. I just added a few more fields, but it is unable to open the database. If you guys want the error message or some other kind of info, I'll try to get it for you (This is my first time with SQL so I don't really know what is needed to fix this up). Thanks in advance!
The error message I'm getting goes like this:
android.database.sqlite.SQLiteException: no such table: periodData: , while
compiling: SELECT DISTINCT _id, title, period, xPeriods, doublePeriods FROM
periodData WHERE _id = -1
And as it says there, I'm using SQLite.
My code to put some data into the table in my Database Helper class:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_CLASSTITLE, title);
initialValues.put(KEY_PERIOD, period);
initialValues.put(KEY_XPERIODS, xPeriods);
initialValues.put(KEY_DOUBLEPERIODS, doublePeriods);
return mDb.insert(DATABASE_PERIOD, null, initialValues);
I started using private static strings to ensure that my calls aren't incorrect (Thanks Barak for the catch!)

Your issue is the table name (as the error message indicates). From the code you show you created a table called "period". Yet you try to query it using the table name "periodData".
Two ways to fix it:
1) Change the table name in your database to periodData (more difficult as it involves re-creating the db).
2) Change the table name in your query from "periodData" to "period".

Check out the dev topic on http://developer.android.com/guide/topics/data/data-storage.html#db
You'll create a DbHelper class to help you open the database and your code will look something like:
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);
Hope this was helpful.

Related

SQlite raw query for insert stement

I need help how to implement rawquery in sqlite. I need to insert a record in to specific row in table. I searched and found that I can achieve this using raw query. I am new to sqlite and don't know how to implement raw query. I got syntax error.
Here is my code
public void insert (String potision, String total, String curent)
{
SQLiteDatabase db = this.getWritableDatabase();
db.rawQuery("INSERT INTO "+Table_Name2+" VALUES(?,?) WHERE ID = ? ", new String[] {total,curent,potision});
}
Here is my syntax error:
SQLiteException: near "WHERE": syntax error (code 1): , while compiling: INSERT INTO item_counts_2 VALUES(?,?) WHERE ID = ?
Help will be appreciated
You are having a syntax error because you added a where clause to an insert.
When you execute an insert, you are adding a row to the database. There is no sense in specifying a row.
If you were updating a row, then, the where clause would be fine, because you have to tell him what row to update.
Also when deleting rows, the where clause is widely used, so that you don't erase the whole table.
Insert: official docs
Update: official docs
Delete: official docs
Note that the docs refer to SQLite, since you are using Android.
You can use update query with ContentValues to update specific row data in your DB like this
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_1, value1);
values.put(COLUMN_2, value2);
return db.update(TABLE_NAME, values, ID + " = ?",
new String[] { String.valueOf(idValue) });
Hope it will help you out.
Don't use where clause with insert query.
If you are inserting a new row to database then where clause is redundant, remove it and it will work fine.
OR,
If you want to update value already exist in database, use update query instead of insert,
for more information visit here.

Getting unique rows from column sqlite android cursor

Hi I cant get unique rows tried this from the documentation:
public Cursor getcepaUnico(){
return database.query(true, "vino", new String[] {"_id", "cepa"}, null, null, null, null, "cepa", null);}
but shows duplicated rows even if the DISTINCT boolean is changed.
Also tried this:
public Cursor getCepaUnico() {
return database.rawQuery("select DISTINCT cepa from vinos", null);}
And the app crash after calling the method.
Setting distinct to true should have returned distinct results. Is it possible that your code which loops through the cursor is incorrect? You might want to post that also for review.
Regarding your rawQuery, you are using a different table name which is probably what is causing the crash. It should be "select DISTINCT cepa from vino" (not vinos) to match your query statement.
Not sure if this will solve your problem, but sometimes I just pull the db from the emulator (in the DDMS view in Eclipse) and run the query directly using an sqlite editor when my raw queries don't work; if the query shows what you want in the editor then use the query in the rawQuery method.
Firefox has a good sqlite editor.

How to check if a table exists in Android?

I'm trying to query on a table dormpolicy
String operatorName = "46001";
String selection = "(plmn = '"+operatorName+"')";
URI CONTENT_URI_DORMPOLICY = Uri.parse("content://nwkinfo/nwkinfo/dormpolicy");
cursor = phone.getContext.getContentResolver().query(CONTENT_URI_DORMPOLICY, null, selection, null, null);
I get error log:
SQLiteQuery: exception: no such table: dormpolicy;
query: SELECT * FROM dormpolicy WHERE ((plmn = '46001'))
This issue happen not always in my phone.
It seems that sometimes,when I access the table before the table was created.
Is there any way that before I query the table, I check if the table exist?
And how?
My answer is twofold:
To strictly answer the question, I will redirect you to How does one check if a table exists in an Android SQLite database?
But rather than manually checking for tables' existence, I suggest you use the SQLiteOpenHelper class. This will help you manage your tables in a structured way. That includes handling database upgrades. Have a look at this for a quick start: http://developer.android.com/guide/topics/data/data-storage.html#db

Problems to create new tables when the database already exists

I'm having some strange behaviour.
If the database does not exists, and i execute the following code in my Activity:
listOpenHelper = new ListOpenHelper(ManageListActivity.this);
db = listOpenHelper.getReadableDatabase();
Cursor cursor = db.query(ListOpenHelper.TABLE_NAME, null, null, null, null, null, BaseColumns._ID + " DESC");
The database is create and the table LIST is created, no problem here.
The problem is when i try to execute a similiar block in other Activity:
productListOpenHelper = new ProductListOpenHelper(ProductListActivity.this);
db = productListOpenHelper.getReadableDatabase();
Cursor cursor = db.query(ProductListOpenHelper.TABLE_NAME, null, null, null, null, null, ProductListOpenHelper.NAME + " ASC");
In this case, i get the Exception "android.database.sqlite.SQLiteException: no such table: list: , while compiling: SELECT * FROM list ORDER BY _id DESC"
If i erase the database and execute first the above block, and after the first block, the error will be in the productlist table.
I need to create all my tables in the first execution?
I like to create the tables when the user enter in each of the Activities, there is some good way to do this?
Thanks!
You have two different databases, correct? If not, you probably shouldn't have two different helper classes.
Also, creating helpers as you are may not be ideal. See blog post:
http://www.touchlab.co/blog/single-sqlite-connection/
Please post the code for your helper classes and why you have two different classes.
why you are using two different helpers? i don't think its a good way... You can create the tables in the initially and you can obtain the db whenever you want, with a single helper.

How to import sqlite file into my project?

I am making an sqlight using eclipse outside the android project
what should I add into my android manifest in order to make it work?
thank you Mathias, lets take this q to another project who generate a SQL file using java
assuming this. How can I set the SQLiteDatabase.NO_LOCALIZED_COLLATORS flag when calling SQLiteDatabase.openDatabase()?
my code over there is
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:test.db");
/*
*some code
*/
Statement stat = conn.createStatement();
stat.executeUpdate("drop table if exists "+TABLE_NAME+";");
//stat.executeUpdate("create table "+TABLE_NAME+" (name, occupation);");
stat.executeUpdate("create table "+TABLE_NAME+" ("+VALUE+","+TYPE+","+LETTER+");");
PreparedStatement prep = conn.prepareStatement(
"insert into "+TABLE_NAME+" values (?, ?,?);");
Even when I use:
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
when I use the query :
String s = "Israel";
Cursor cursor = db.query(TABLE_NAME, new String[] {VALUE}
,VALUE + " like " + "'%" + s +"%'", null, null, null, null);
I get an exception .
You don't need to add anything special into the android manifest. You can open the database from anywhere, i.e. also from your sdcard or else. Otherwise, A common place to put the database is in to the assets folder of your application.
When you create the db outside the android project, just make sure you either create the metadata table (as mentioned in the Android docs) or set the SQLiteDatabase.NO_LOCALIZED_COLLATORS flag when calling SQLiteDatabase.openDatabase(). Also you should note that the primary key in all tables is _id. These are the most important things to consider when creating a new DB.
Also helpful regarding the metadata-table might be:
What is the android_metadata table?
No such table android_metadata, what's the problem?
Helpful blog:
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

Categories

Resources