I am trying to set two databases.
After lunch the emulator, and trying to enter data, I have tried to find the exact reason of this error but without success.
I get an error:
05-17 16:23:06.410: E/AndroidRuntime(311): android.database.sqlite.SQLiteException: near "NULLbaby_age_month": syntax error: CREATE TABLE settings ( _id INTEGER PRIMARY KEY AUTOINCREMENT, uri_baby TEXT NOT NULL, baby_name TEXT NOT NULL, baby_gender TEXT NOT NULL, baby_age_year TEXT NOT NULLbaby_age_month TEXT NOT NULLbaby_age_day TEXT NOT NULL);
The Database Code is:
package com.tamar.efrat;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
public class DatBas {
public static final String KEY_ROWID = "_id";
public static final String KEY_SHOURS = "start_hour";
public static final String KEY_SMINUTE = "start_minute";
public static final String KEY_SDATE = "start_date";
public static final String KEY_AMOUNT = "amount";
public static final String KEY_SIDE = "side";
public static final String KEY_KIND = "kind";
public static final String KEY_ROW_BABY_ID = "_id";
public static final String KEY_BABY_IMAGE_PATH = "uri_baby";
public static final String KEY_BABY_NAME = "baby_name";
public static final String KEY_BABY_GENDER = "baby_gender";
public static final String KEY_BABY_BORN_DATE_YEAR = "baby_age_year";
public static final String KEY_BABY_BORN_DATE_MONTH = "baby_age_month";
public static final String KEY_BABY_BORN_DATE_DAY = "baby_age_day";
private static final String DATABASE_NAME = "TamatDB";
private static final String DATABASE_TABLE = "stop_watch_records";
private static final String DATABASE_TABLE_SETTINGS = "settings";
private static final int DATABASE_VERSION = 20;
private TamarDatabase thdb;
private static Context tcontext;
private SQLiteDatabase tdb;
private static class TamarDatabase extends SQLiteOpenHelper {
public TamarDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String ctData = "CREATE TABLE " + DATABASE_TABLE + " ( "
+ KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_SHOURS + " TEXT NOT NULL, " + KEY_SMINUTE
+ " TEXT NOT NULL, " + KEY_SDATE + " TEXT NOT NULL, "
+ KEY_AMOUNT + " TEXT NOT NULL, " + KEY_SIDE
+ " TEXT NOT NULL, " + KEY_KIND + " TEXT NOT NULL );";
db.execSQL(ctData);
String ctSettings = "CREATE TABLE " + DATABASE_TABLE_SETTINGS
+ " ( " + KEY_ROW_BABY_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_BABY_IMAGE_PATH + " TEXT NOT NULL, " + KEY_BABY_NAME
+ " TEXT NOT NULL, " + KEY_BABY_GENDER + " TEXT NOT NULL, "
+ KEY_BABY_BORN_DATE_YEAR + " TEXT NOT NULL"
+ KEY_BABY_BORN_DATE_MONTH + " TEXT NOT NULL"
+ KEY_BABY_BORN_DATE_DAY + " TEXT NOT NULL);";
db.execSQL(ctSettings);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_SETTINGS);
onCreate(db);
}
}
public DatBas(Context c) {
tcontext = c;
}
public DatBas open() throws SQLiteException {
thdb = new TamarDatabase(tcontext);
tdb = thdb.getWritableDatabase();
return this;
}
public void close() {
thdb.close();
}
public long createEntry(String sh, String sm, String sd, String at,
String tside, String tkind) {
ContentValues cv = new ContentValues();
cv.put(KEY_SHOURS, sh);
cv.put(KEY_SMINUTE, sm);
cv.put(KEY_SDATE, sd);
cv.put(KEY_AMOUNT, at);
cv.put(KEY_SIDE, tside);
return tdb.insert(DATABASE_TABLE, null, cv);
}
public long createEntrySettings(String bbdy, String bbdm, String bbdd,
String pt, String bg, String bfName) {
ContentValues cv2 = new ContentValues();
cv2.put(KEY_BABY_IMAGE_PATH, pt);
cv2.put(KEY_BABY_NAME, bfName);
cv2.put(KEY_BABY_GENDER, bg);
cv2.put(KEY_BABY_BORN_DATE_YEAR, bbdy);
cv2.put(KEY_BABY_BORN_DATE_MONTH, bbdm);
cv2.put(KEY_BABY_BORN_DATE_DAY, bbdd);
return tdb.insert(DATABASE_TABLE_SETTINGS, null, cv2);
}
public String getData() {
String[] columns = new String[] { KEY_ROWID, KEY_SHOURS, KEY_SMINUTE,
KEY_SDATE, KEY_AMOUNT, KEY_SIDE, KEY_KIND };
Cursor c = tdb.query(DATABASE_TABLE, columns, null, null, null, null,
null);
String results = "";
int iRaw = c.getColumnIndex(KEY_ROWID);
int iShours = c.getColumnIndex(KEY_SHOURS);
int iSminute = c.getColumnIndex(KEY_SMINUTE);
int iDate = c.getColumnIndex(KEY_SDATE);
int iAmount = c.getColumnIndex(KEY_AMOUNT);
int iSide = c.getColumnIndex(KEY_SIDE);
int iKind = c.getColumnIndex(KEY_KIND);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
results = results + "the id is " + c.getString(iRaw)
+ " the sart hour is " + " " + c.getString(iShours)
+ " the start minute is " + " " + c.getString(iSminute)
+ " the start date is " + " " + c.getString(iDate)
+ " the amount is " + " " + c.getString(iAmount)
+ " the side is " + " " + c.getString(iSide)
+ " the kind is " + " " + c.getString(iKind) + "\n";
}
return results;
}
public String getDataSettings() {
String[] columns = new String[] { KEY_ROW_BABY_ID, KEY_BABY_IMAGE_PATH,
KEY_BABY_NAME, KEY_BABY_GENDER, KEY_BABY_BORN_DATE_YEAR,
KEY_BABY_BORN_DATE_MONTH, KEY_BABY_BORN_DATE_DAY };
Cursor c = tdb.query(DATABASE_TABLE_SETTINGS, columns, null, null,
null, null, null);
String results = "";
int iRawBabyId = c.getColumnIndex(KEY_ROW_BABY_ID);
int iBIPath = c.getColumnIndex(KEY_BABY_IMAGE_PATH);
int iBName = c.getColumnIndex(KEY_BABY_NAME);
int iGender = c.getColumnIndex(KEY_BABY_GENDER);
int iBBDateYear = c.getColumnIndex(KEY_BABY_BORN_DATE_YEAR);
int iBBDateMonth = c.getColumnIndex(KEY_BABY_BORN_DATE_MONTH);
int iBBDateDay = c.getColumnIndex(KEY_BABY_BORN_DATE_DAY);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
results = results + " the kind is " + " " + c.getString(iRawBabyId)
+ " the kind is " + " " + c.getString(iBIPath)
+ " the kind is " + " " + c.getString(iBName)
+ " the kind is " + " " + c.getString(iGender)
+ " the kind is " + " " + c.getString(iBBDateYear)
+ " the kind is " + " " + c.getString(iBBDateMonth)
+ " the kind is " + " " + c.getString(iBBDateDay) + "\n";
}
return results;
}
public DatBas delete() {
tdb.delete(DATABASE_TABLE, null, null);
tdb.delete(DATABASE_TABLE_SETTINGS, null, null);
return null;
}
}
forget to add , in query ...
TEXT NOT NULL,baby_age_month
AND
TEXT NOT NULL,baby_age_day
CREATE TABLE settings ( _id INTEGER PRIMARY KEY AUTOINCREMENT, uri_baby TEXT NOT NULL, baby_name TEXT NOT NULL, baby_gender TEXT NOT NULL, baby_age_year TEXT NOT NULL,baby_age_month TEXT NOT NULL,baby_age_day TEXT NOT NULL);
having small error : forgetted ( , )separater
CREATE TABLE settings ( _id INTEGER PRIMARY KEY AUTOINCREMENT, uri_baby TEXT NOT NULL,
baby_name TEXT NOT NULL, baby_gender TEXT NOT NULL, baby_age_year TEXT NOT
NULL, baby_age_month TEXT NOT NULL,baby_age_day TEXT NOT NULL);
Related
So I have been trying to query in my sqlite database for my android app. However, it seems like my cursor is not working like it is supposed too as I can get any results.
I know that I only have 3 items in my database, but what I put in my query are valid attributes for my 3 items stored. But there is still no result.
Below is my code for the query function and my database model.
// To get data from DB by querying the items selected
public String getData(int firstSelection, int secondSelection, int thirdSelection,
int fourthSelection, int fifthSelection)
{
SQLiteDatabase db = dbHelper.getWritableDatabase();
String firstSelectionStr, secondSelectionStr, thirdSelectionStr, fourthSelectionStr, fifthSelectionStr;
firstSelectionStr = Integer.toString(firstSelection);
secondSelectionStr = Integer.toString(secondSelection);
thirdSelectionStr = Integer.toString(thirdSelection);
fourthSelectionStr = Integer.toString(fourthSelection);
fifthSelectionStr = Integer.toString(fifthSelection);
//String[] columns = {DBHelper.UID,DBHelper.CNAME};
//Cursor cursor = db.query(DBHelper.TABLE_NAME,columns,null,null,null,null,null);
String selectQuery = "SELECT * FROM "+ DBHelper.TABLE_NAME + " WHERE " + DBHelper.FIRST_ATTRIBUTE + "=? "
+ " AND " + DBHelper.SECOND_ATTRIBUTE + "=? " + " AND " + DBHelper.THIRD_ATTRIBUTE + "=? " + " AND " + DBHelper.FOURTH_ATTRIBUTE + "=? "
+ " AND " + DBHelper.FIFTH_ATTRIBUTE + "=?";
Cursor cursor=db.rawQuery(selectQuery, new String[] {firstSelectionStr, secondSelectionStr, thirdSelectionStr,
fourthSelectionStr, fifthSelectionStr});
StringBuilder buffer = new StringBuilder();
cursor.moveToFirst();
if (cursor != null) {
int tresult = cursor.getCount();
// Append every data together
do {
//int cursorID = cursor.getInt(cursor.getColumnIndex(DBHelper.UID));
String chosenItem = cursor.getString(cursor.getColumnIndex(DBHelper.CNAME));
buffer.append(chosenItem + " ");
} while (cursor.moveToNext());
/*while (cursor.moveToNext())
{
//int cursorID = cursor.getInt(cursor.getColumnIndex(DBHelper.UID));
String chosenItem = cursor.getString(cursor.getColumnIndex(DBHelper.CNAME));
buffer.append(chosenItem + " ");
}*/
}
return buffer.toString();
}
static class DBHelper extends SQLiteOpenHelper
{
private static final String DATABASE_NAME = "CraftsAppDatabase.db"; // Database Name
private static final String TABLE_NAME = "CraftTools"; // Table Name
private static final String RESULT_TABLE = "Result"; // Table Name
private static final int DATABASE_Version = 1; // Database Version
private static final String UID="_id"; // Column I (Primary Key)
private static final String CNAME = "Craft_Name"; //Column II
private static final String RESULT = "Result_Name"; //Column II
private static final String FIRST_ATTRIBUTE = "First_Attribute"; //Column III
private static final String SECOND_ATTRIBUTE = "Second_Attribute"; //Column IV
private static final String THIRD_ATTRIBUTE = "Third_Attribute"; //Column V
private static final String FOURTH_ATTRIBUTE = "Fourth_Attribute"; //Column VI
private static final String FIFTH_ATTRIBUTE = "Fifth_Attribute"; //Column VII
private static final String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME+
" ("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+CNAME+" VARCHAR(255)" +
", "+FIRST_ATTRIBUTE+" VARCHAR(255), "+SECOND_ATTRIBUTE+" VARCHAR(255)" +
", "+THIRD_ATTRIBUTE+" VARCHAR(255), "+FOURTH_ATTRIBUTE+" VARCHAR(255)" +
", "+FIFTH_ATTRIBUTE+" VARCHAR(255));";
private static final String CREATE_OTHER_TABLE = "CREATE TABLE "+RESULT_TABLE+
" ("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+RESULT+" VARCHAR(255));";
private static final String DROP_TABLE ="DROP TABLE IF EXISTS "+RESULT_TABLE;
private Context context;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_Version);
this.context=context;
}
/*public void deleteTable(SQLiteDatabase db) {
db = getWritableDatabase();
db.execSQL("DROP TABLE IF EXISTS CraftTools");
}*/
public void onCreate(SQLiteDatabase db) {
db.execSQL(DROP_TABLE);
db.execSQL(CREATE_OTHER_TABLE);
db.execSQL(CREATE_TABLE);
db.execSQL("INSERT INTO " + TABLE_NAME + "(Craft_Name, First_Attribute, Second_Attribute, Third_Attribute, Fourth_Attribute, Fifth_Attribute ) " +
"VALUES ('Landscape Drawing', '1', '4','8', '0', '0')");
db.execSQL("INSERT INTO " + TABLE_NAME + "(Craft_Name, First_Attribute, Second_Attribute, Third_Attribute, Fourth_Attribute, Fifth_Attribute ) " +
"VALUES ('Popsicle Sticks House', '2', '3','0', '0', '0')");
db.execSQL("INSERT INTO " + TABLE_NAME + "(Craft_Name, First_Attribute, Second_Attribute, Third_Attribute, Fourth_Attribute, Fifth_Attribute ) " +
"VALUES ('Sunset Painting', '4', '7','10', '0', '0')");
/*try {
db.execSQL(CREATE_TABLE);
} catch (Exception e) {
Message.message(context,""+e);
}*/
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//db.execSQL(DROP_TABLE);
onCreate(db);
if (newVersion > oldVersion) {
db.execSQL("ALTER TABLE CraftTools ADD COLUMN FIRST_ATTRIBUTE INTEGER DEFAULT 0");
db.execSQL("ALTER TABLE CraftTools ADD COLUMN SECOND_ATTRIBUTE INTEGER DEFAULT 0");
db.execSQL("ALTER TABLE CraftTools ADD COLUMN THIRD_ATTRIBUTE INTEGER DEFAULT 0");
db.execSQL("ALTER TABLE CraftTools ADD COLUMN FOURTH_ATTRIBUTE INTEGER DEFAULT 0");
db.execSQL("ALTER TABLE CraftTools ADD COLUMN FIFTH_ATTRIBUTE INTEGER DEFAULT 0");
//onCreate(db);
/*try {
Message.message(context,"OnUpgrade");
db.execSQL(DROP_TABLE);
onCreate(db);
}catch (Exception e) {
Message.message(context,""+e);*/
}
}
}
My logcat for the error is below this line. I am not sure why my result is empty or why nothing is being put in the buffer.
11-27 22:43:28.898 4502-4502/com.example.android.androidcraftsappprototype E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.androidcraftsappprototype, PID: 4502
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:468)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
at com.example.android.androidcraftsappprototype.DBAdapter.getData(DBAdapter.java:86)
at com.example.android.androidcraftsappprototype.SetupPage$2.onClick(SetupPage.java:118)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
i think your course return 0 item according to query..so you should write below condition
cursor.moveToFirst(); <--- instead of this
if(cursor.moveToFirst()){
// here all your code
}
Why is that when i have more than 3 columns the app crashes? I tried debugging it by commenting out one column and it runs perfectly. After debugging it some more I found out that the problem might be on the 'populateListview' because I was able to run the app but now it won't display anything. Why do you think I couldn't run it with more than 3 columns?
Here's my dbAdapter:
// Field Names:
public static final String KEY_ROWID = "_id";
public static final String KEY_INGREDIENTNAME = "ingredientname";
public static final String KEY_IMAGE = "image";
public static final String KEY_DETAILS = "details";
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_INGREDIENTNAME, KEY_IMAGE, KEY_DETAILS};
// Column Numbers for each Field Name:
public static final int COL_ROWID = 0;
public static final int COL_INGREDIENTNAME = 1;
public static final int COL_IMAGE = 2;
public static final int COL_DETAILS = 3;
//SQL statement to create database
private static final String DATABASE_CREATE_SQL =
"CREATE TABLE " + DATABASE_TABLE
+ " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_INGREDIENTNAME + " TEXT NOT NULL, "
+ KEY_IMAGE + " TEXT"
+ KEY_DETAILS + " TEXT"
+ ");";
// Add a new set of values to be inserted into the database.
public long insertRow(String ingredientname, String image, String detailsValue) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_INGREDIENTNAME, ingredientname);
initialValues.put(KEY_IMAGE, image);
initialValues.put(KEY_DETAILS, detailsValue);
// Insert the data into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
Here's my populateListView Code:
private void populateListView() {
Cursor cursor = myDb.getAllRows();
String[] fromFieldNames = new String[] { //DBAdapter.KEY_ROWID,
DBAdapter.KEY_INGREDIENTNAME };
int[] toViewIDs = new int[] { //R.id.textViewItemNumber,
R.id.textViewItemTask };
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(),
R.layout.item_layout, cursor, fromFieldNames, toViewIDs, 0);
ListView myList = (ListView) findViewById(R.id.listViewTask);
myList.setAdapter(myCursorAdapter);
}
You miss a comma, here:
private static final String DATABASE_CREATE_SQL =
"CREATE TABLE " + DATABASE_TABLE
+ " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_INGREDIENTNAME + " TEXT NOT NULL, "
+ KEY_IMAGE + " TEXT"
+ KEY_DETAILS + " TEXT"
+ ");";
It should be
private static final String DATABASE_CREATE_SQL =
"CREATE TABLE " + DATABASE_TABLE
+ " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_INGREDIENTNAME + " TEXT NOT NULL, "
+ KEY_IMAGE + " TEXT,"
+ KEY_DETAILS + " TEXT"
+ ");";
my problem is with very specific query. My SQLite datbase is only 1 table with 11 entries. It creates just fine, but upon execution of this piece of code it crashes. When I change the query to simply:
SELECT * FROM Items
Then it works fine, but I need more narrow results, therefore I modify with the "WHERE" clause. But then it crashes and the application stops. If I comment out the Cursor... it runs fine.
public int findPictureNumber(String itemtitle) {
String query = "SELECT nr_of_pics FROM Items WHERE ItemTitle = \"" + itemtitle + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
...
}
Where is the error? I can't seem to find it even after narrowing it down to those lines of code.
EDIT:
This is a method for adding an item to a database.
public void newItemFuro () {
MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1);
String title = "Furo";
String author = "Fernando Brizio";//í
String category = "Decoracao";//çã
int date = 2012;
String type = "Taca";//ç
String country = "Portugal";
String colour = "Castanho/Cortica";//ç
String material = "Castanho/Cortica";//ç
boolean isFavourite = false;
String imgres = "furoo";
int nr_of_pics = 3;
Item item = new Item(title, author, category, date, type, country, colour, material, isFavourite, imgres, nr_of_pics);
dbHandler.addItem(item);
}
//helper for types
public static final String VARCHAR_TYPE = " VARCHAR(50)";
public static final String BOOL_TYPE = " BOOLEAN";
public static final String INT_TYPE = " INTEGER";
Here it creates the table:
public void onCreate(SQLiteDatabase db) {
String CREATE_ITEMS_TABLE = "CREATE TABLE " + TABLE_ITEMS +
"("
+ COLUMN_ENTRY_ID + INT_TYPE +" PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_TITLE + VARCHAR_TYPE + ","
+ COLUMN_AUTHOR + VARCHAR_TYPE + ","
+ COLUMN_CATEGORY + VARCHAR_TYPE + ","
+ COLUMN_DATE + INT_TYPE + ","
+ COLUMN_TYPE + VARCHAR_TYPE + ","
+ COLUMN_COUNTRY + VARCHAR_TYPE + ","
+ COLUMN_COLOUR + VARCHAR_TYPE + ","
+ COLUMN_MATERIAL + VARCHAR_TYPE + ","
+ COLUMN_FAVOURITE + BOOL_TYPE + ","
+ COLUMN_IMGRES + VARCHAR_TYPE + ","
+ COLUMN_NUMBER_OF_PICS + INT_TYPE +
")";
db.execSQL(CREATE_ITEMS_TABLE);
}
Adding item:
public void addItem(Item item) {
ContentValues values = new ContentValues();
values.put(COLUMN_TITLE, item.getItemTitle());
values.put(COLUMN_AUTHOR, item.getAuthor());
values.put(COLUMN_CATEGORY, item.getCategory());
values.put(COLUMN_DATE, item.getDate());
values.put(COLUMN_TYPE, item.getType());
values.put(COLUMN_COUNTRY, item.getCountry());
values.put(COLUMN_COLOUR, item.getColour());
values.put(COLUMN_MATERIAL, item.getMaterial());
values.put(COLUMN_FAVOURITE, item.getFavourite());
values.put(COLUMN_IMGRES, item.getImgres());
values.put(COLUMN_NUMBER_OF_PICS, item.getNumberOfPics());
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_ITEMS, null, values);
db.close();
}
Here full function for searching nr_of_pics:
public int findPictureNumber(String itemtitle) {
String query = "SELECT nr_of_pics FROM Items WHERE ItemTitle = '" + itemtitle + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
int PicsNumber=0;
if (cursor.moveToFirst()) {
cursor.moveToFirst();
PicsNumber=Integer.parseInt(cursor.getString(0));
cursor.close();
return PicsNumber;
} else {
//wtf?
}
db.close();
return 0;
}
And the errors say as follows:
(1) table Items has no column named imgres
Error inserting colour=Castanho/Cortiça author=Fernando Brízio
imgres=furo category=Decoração title=Furo type=Taça date=2012
nr_of_pics=3 material=Castanho/Cortiça is_favourite=false
country=Portugal
android.database.sqlite.SQLiteException: table Items has no column named imgres (code 1): , while
compiling: INSERT INTO
Items(colour,author,imgres,category,title,type,date,nr_of_pics,material,is_favourite,country)
VALUES (?,?,?,?,?,?,?,?,?,?,?)
You do not give any exception but I think you have error in your SQL. You need to use ' instead of ".
Change your query as below.
String query = "SELECT nr_of_pics FROM Items WHERE ItemTitle = '" + itemtitle + "'";
It is clear that you don't have any column that named "imgres"!
You should modify your query
"INSERT INTO Items(colour,author,imgres,category,title,type,date,nr_of_pics,material,is_favourite,country)
VALUES (?,?,?,?,?,?,?,?,?,?,?)"
I would like to check if any row exists within the Sqlite database.
my java class
public static final String DATABASE_TABLE2 = "receivernumber";
public static final String KEY_ROWID2 = "hpnumberID2";
public static final String KEY_NAME2 = "hpNumber2";
public long insertContact2(String hpNumber2)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME2, hpNumber2);
if(CheckIsDataAlreadyInDBorNot(0) == true) {
return db.update(
DATABASE_TABLE2, initialValues, "SET='"+KEY_NAME2+"'" +"WHERE"+ "KEY_ROWID2="+1, null
) > 0;
}
else {
return db.insert(DATABASE_TABLE2, null, initialValues);
}
//if there is alrdy a record, create a method to reject intake
return 0;
}
public boolean CheckIsDataAlreadyInDBorNot(long hpnumberID) {
Cursor mCursor = db.query(
true, DATABASE_TABLE2, new String[] {KEY_ROWID, KEY_NAME},KEY_ROWID + "=" + hpnumberID, null, null, null, null, null
);
String Query = "Select * from " + DATABASE_TABLE2 + " where " + KEY_ROWID2 + " < " + 0;
SQLiteDatabase sqldb = EGLifeStyleApplication.sqLiteDatabase;
Cursor cursor = sqldb.rawQuery(Query, null);
if(cursor.getCount<=0) return false;
return true;
}
public boolean updateContact2(long hpnumberID2, String hpNumber2)
{
ContentValues args = new ContentValues();
args.put(KEY_NAME2, hpNumber2);
//args.put(KEY_NAME3, Selected);
//return db.update(DATABASE_TABLE2, args, KEY_ROWID2 + "=" + hpnumberID2, null) > 0;
//db.execSQL("UPDATE " + DATABASE_TABLE2 + " SET " + KEY_NAME2 + " WHERE " + KEY_ROWID2 + "=1 ");
return db.update(DATABASE_TABLE2, args, "SET='" + KEY_NAME2 + "'" + "WHERE" + "KEY_ROWID2=" + 1, null) > 0;
}
So my database layout is such that the user can only add a number for the first time. Subsequent times the user wishes to add a number, it would be replaced by an edit function instead. However, there's an error called EGLifeStyleApplication cannot be resolved to a variable. However, as this is an answer from questions solved successfully, they did not really explain what is the function of that EGLifeStyleApplications. So how do I go about doing what I want to achieve? (How do I edit my insert statement) Thanks.
Replace the offending line with
sqldb = ctx.openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);
where ctx is a context you will pass as a parameter to your CheckIsDataAlreadyInDBorNot method. i.e.:
public boolean CheckIsDataAlreadyInDBorNot(Context ctx, long hpnumberID) {
and DB_NAME is a string containing your db name, i.e.:
private final static String DB_NAME = "rec_nums.db";
public static final String DATABASE_TABLE2 = "receivernumber";
public static final String KEY_ROWID2 = "hpnumberID2";
public static final String KEY_NAME2 = "hpNumber2";
I have an SQLite database in an Android app. One database with two tables. simple read in some text and read it out, however, the first of two tables works perfectly and the second table does not and gives errors. I have looked at my code and it seems all correct. I dare anyone to find an error in my code or SQL statements below.
Especially interested in the SQL statements, because my SQL code is PERFECT as far as I know, for both tables, however in the LOGCAT says that a there is no table that I am reading into for table two.
Why would one of my tables work and the other not? Yet they are in the same database and written the same way.
DATABASE OPERATION ON FIRST TABLE; (WORKS PERFECTLY)
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_HITS, hits);
ourDatabase.insert(DATABASE_TABLE_1, null, cv);
public String getData() {
String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_HITS };
Cursor c = ourDatabase.query(DATABASE_TABLE_1, columns, null, null, null,
null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iHits = c.getColumnIndex(KEY_HITS);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result = result + c.getString(iRow) + " " + c.getString(iName)
+ " " + c.getString(iHits) + "\n";
}
return result;
}
ourHelper.close();
DATABASE OPERATION ON SECOND TABLE; (DOES NOT WORK, ERRORS)
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put( KEY_RESULT, result);
return ourDatabase.insert(DATABASE_TABLE_2, null, cv);
public String getData2() {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_ROWID, KEY_RESULT, KEY_TABLET, KEY_DATE };
Cursor c = ourDatabase.query(DATABASE_TABLE_2, columns, null, null, null,
null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iResult = c.getColumnIndex(KEY_RESULT);
int iTablet = c.getColumnIndex(KEY_TABLET);
int iDate = c.getColumnIndex(KEY_DATE);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result = result + c.getString(iRow) + " " + c.getString(iResult)
+ " " + c.getString(iTablet) + " " + c.getString(iDate) + "\n";
}
return result;
}
ourHelper.close();
LOGCAT OUTPUT;
01-31 19:33:01.670: E/AndroidRuntime(6420): FATAL EXCEPTION: main
01-31 19:33:01.670: E/AndroidRuntime(6420):
java.lang.RuntimeException: Unable to start activity ComponentInfo{DBView}:
android.database.sqlite.SQLiteException: no such column: date: , while compiling:
SELECT _id, game_result, tablet_winner, date FROM prizeTable
MORE CODE FOR DETAILS;
public class PlayGame {
public static final String KEY_ROWID="_id";
// for table 1 gameTable
public static final String KEY_NAME="persons_name";
public static final String KEY_HITS="persons_hits";
// for table 2 prizesTable
public static final String KEY_RESULT="game_result";
public static final String KEY_TABLET="tablet_winner";
public static final String KEY_DATE="date";
private static final String DATABASE_NAME="PlayGamesdb";
private static final String DATABASE_TABLE_1="gameTable";
private static final String DATABASE_TABLE_2="prizeTable";
private static final int DATABASE_VERSION = 1;
private static final String CREATE_TABLE_1 = "CREATE TABLE " + DATABASE_TABLE_1 + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_NAME + " TEXT NOT NULL, " + KEY_HITS + " TEXT NOT NULL);";
private static final String CREATE_TABLE_2 = "CREATE TABLE " + DATABASE_TABLE_2 + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_RESULT + " TEXT NOT NULL, " + KEY_TABLET
+ " TEXT NOT NULL, " + KEY_DATE + "TEXT NOT NULL);";
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_1);
db.execSQL(CREATE_TABLE_2);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_1 + "AND" + DATABASE_TABLE_2);
onCreate(db);
}
}
<<< EDIT >>>
Safime's suggestion fixed the crashing, that was adding a space between KEY_DATE and TEXT in the creation of the second table.
However still a problem, no more crashing, but the insert() method is still not working. Getting a -1 return shows that it is not inserting anything, and the the table 2 is still empty after inserting a new row to the table. Got to find out why it is failing to create any new rows in the table. Just like earlier, table one works fine but table two is still not working yet.
You are using Constraint NOT NULL and you are inserting only in one column. You must be getting SQLiteConstraintexception Exception. Try inserting in all columns.
You are missing an empty space after the column KEY_DATE and before TEXT on the creation of the second table.
(...) + KEY_DATE + " TEXT NOT NULL); (...)
Probably you have a problem at the create table statement of your second table. Try to open your db file with the sqlite3 command line tool, and see if this table exits. If not, the problem is in the CREATE statement.