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";
Related
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 3 years ago.
Hi I'm making a bill splitting app in android studio 3.3. I've made a database with sqlite and it stores a product's name and cost. As I am trying to get the total cost of the input from the database and store it in a text view the app closes. I've came to the conclusion that the problem is located in the getTotal() method in MyDBHandler.java
public class MyDBHandler extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 6;
private static final String DATABASE_NAME = "productDB.db";
public static final String TABLE_PRODUCTS = "products";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_PRODUCTNAME = "productname";
public static final String COLUMN_PRODUCTCOST = "productcost";
//We need to pass database information along to superclass
public MyDBHandler(Context context, String name,
SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_PRODUCTS + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_PRODUCTNAME + " TEXT " + "," +
COLUMN_PRODUCTCOST + " INTEGER " +
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);
onCreate(db);
}
//Add a new row to the database
public void addProduct(Products product){
ContentValues values = new ContentValues();
values.put(COLUMN_PRODUCTNAME, product.get_productname());
values.put(COLUMN_PRODUCTCOST, product.get_productcost());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_PRODUCTS, null, values);
db.close();
}
//Delete a product from the database
public void deleteProduct(String productName){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_PRODUCTS + " WHERE " +
COLUMN_PRODUCTNAME + "=\"" + productName + "\";");
}
//get the total sum of teh Product_Cost column
//
// TODO: fix this method to display total
// NOTE: THIS IS YOUR PROBLEM
//
//
public int GetTotal(){
int temp;
SQLiteDatabase db = getWritableDatabase();
String query = " SELECT SUM(COLUMN_PRODUCTCOST) FROM " + TABLE_PRODUCTS + ";";
Cursor cursor = db.rawQuery(query , null);
if (cursor.moveToFirst()) {
temp = cursor.getInt(0);
}
else return 0;
cursor.close();
return temp;
}
// converts the elements in the database to a string so you can print the database out.
public String databaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";// why not leave out the WHERE clause?
//Cursor points to a location in your results
Cursor recordSet = db.rawQuery(query, null);
//Move to the first row in your results
recordSet.moveToFirst();
//Position after the last row means the end of the results
while (!recordSet.isAfterLast()) {
// null could happen if we used our empty constructor
if (recordSet.getString(recordSet.getColumnIndex("productname")) != null) {
dbString += recordSet.getString(recordSet.getColumnIndex("productname"));
dbString += "\t $";
dbString += recordSet.getString(recordSet.getColumnIndex("productcost"));
dbString += "\n";
}
recordSet.moveToNext();
}
db.close();
return dbString;
}
}
public class MainActivity extends AppCompatActivity {
EditText userInput;
EditText userInputC;
TextView recordsTextView;
TextView Results;
MyDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userInput = (EditText) findViewById(R.id.user_Input);
userInputC = (EditText) findViewById(R.id.user_InputC);
recordsTextView = (TextView) findViewById(R.id.records_TextView);
Results = (TextView) findViewById(R.id.Results);
/* Can pass nulls because of the constants in the helper.
* the 1 means version 1 so don't run update.
*/
dbHandler = new MyDBHandler(this, null, null, 1);
printDatabase();
}
//Print the database
public void printDatabase(){
String dbString = dbHandler.databaseToString();
recordsTextView.setText(dbString);
userInput.setText("");
userInputC.setText("");
}
/*
//Add a product to the database
public void addButtonClicked(View view){
// dbHandler.add needs an object parameter.
int count = Integer.parseInt(Results.getText().toString());
int num = Integer.parseInt(userInputC.getText().toString());
count = count + num;
String temp = Results.getText().toString();
float temp1 = Float.parseFloat(temp);
//Results.setText(Integer.toString(count));
Results.setText(Float.toString(count));
Products product = new Products(userInput.getText().toString(), temp1);
dbHandler.addProduct(product);
//Results = ;
printDatabase();
}*/
#SuppressLint("SetTextI18n")
public void addButtonClicked(View view){
// dbHandler.add needs an object parameter.
int usersinput = Integer.parseInt(userInputC.getText().toString());
Products product = new Products(userInput.getText().toString(), usersinput);
int temp = dbHandler.GetTotal();
dbHandler.addProduct(product);
Results.setText(Integer.toString(temp));
printDatabase();
}
//Delete items
public void deleteButtonClicked(View view){
// dbHandler delete needs string to find in the db
String inputText = userInput.getText().toString();
dbHandler.deleteProduct(inputText);
printDatabase();
}
}
You should change :-
String query = " SELECT SUM(COLUMN_PRODUCTCOST) FROM " + TABLE_PRODUCTS + ";";
to be
String query = " SELECT SUM(" + COLUMN_PRODUCTCOST + ") FROM " + TABLE_PRODUCTS + ";";
Otherwise the query will fail as there is no column named COLUMN_PRODUCTCOST, instead you want the value when COLUMN_PRODUCTCOST is resolved (i.e. productcost), which is a column name.
You may also wish to consider using the query convenience method rather than using the rawQuery method.
Your code could then be :-
public int GetTotal(){
int temp;
SQLiteDatabase db = getWritableDatabase();
String[] columns = new String[]{"SELECT SUM(" + COLUMN_PRODUCTCOST + ")"}
Cursor cursor = db.query(TABLE_PRODUCTS,columns,null,null,null,null,null);
if (cursor.moveToFirst()) {
temp = cursor.getInt(0);
}
else temp = 0; //<<<<<<<<<< CHANGED not to return as the Cursor would not be closed.
cursor.close();
return temp;
}
Note this closes the Cursor even if there are no rows, which should be the case (you could apply this to your code that uses rawQuery).
This is a bad sql query:
String query = " SELECT SUM(COLUMN_PRODUCTCOST) FROM " + TABLE_PRODUCTS + ";"
Should it be
String query = " SELECT SUM(" + COLUMN_PRODUCTCOST + ") FROM " + TABLE_PRODUCTS + ";"
I got error in following code. I am trying to save my traveled distance in SQLite Database but getting error in SQLite Database. I don't know how to manage the array length. I am getting an error called
java.lang.ArrayIndexOutOfBoundsException: length=3; index=4.
public class ActivityLocationDaoImpl extends Dao implements ActivityLocationDao {
private static final String TABLE_NAME = "activity_location";
private static final String COLUMN_ID = "id";
private static final String COLUMN_LATITUDE = "latitude";
private static final String COLUMN_LONGITUDE = "longitude";
private static final String COLUMN_ACTIVITY = "activity";
private static final String COLUMN_DATE = "date";
private static final String[] COLUMN_ARRAY = new String[]{COLUMN_ID, COLUMN_LATITUDE, COLUMN_LONGITUDE, COLUMN_ACTIVITY, COLUMN_DATE};
public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (\n" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
COLUMN_LATITUDE + " INTEGER NOT NULL,\n" +
COLUMN_LONGITUDE + " INTEGER NOT NULL,\n" +
COLUMN_ACTIVITY + " INTEGER NOT NULL,\n" +
COLUMN_DATE + " INTEGER NOT NULL\n" + ")";
public ActivityLocationDaoImpl(SQLiteDatabase database) {
super(database);
}
#Override
public boolean insert(ActivityLocation activityLocation) {
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_LATITUDE, activityLocation.getLocation().getLatitude());
contentValues.put(COLUMN_LONGITUDE, activityLocation.getLocation().getLongitude());
contentValues.put(COLUMN_ACTIVITY, activityLocation.getActivityType().getIndex());
contentValues.put(COLUMN_DATE, activityLocation.getDate().getTime());
return getDatabase().insert(TABLE_NAME, null, contentValues) != -1;
}
#Override
public List<ActivityLocation> listAll(Date currentDay) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(currentDay);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
currentDay = calendar.getTime();
calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + 1);
Date nextDay = calendar.getTime();
Cursor cursor = getDatabase().query(TABLE_NAME, COLUMN_ARRAY, COLUMN_DATE + " > ? AND " + COLUMN_DATE + " < ?",
new String[]{String.valueOf(currentDay.getTime()), String.valueOf(nextDay.getTime())},
null, null, COLUMN_DATE + " ASC", null);
List<ActivityLocation> activityLocationList = new ArrayList<>();
while (cursor.moveToNext()) {
activityLocationList.add(convertCursorToEntity(cursor));
}
return activityLocationList;
}
#Override
public List<ActivityLocation> listAll(Date startDate, Date finalDate) {
Cursor cursor = getDatabase().query(TABLE_NAME, COLUMN_ARRAY, COLUMN_DATE + " > ? AND " + COLUMN_DATE + " < ?",
new String[]{String.valueOf(startDate.getTime()), String.valueOf(finalDate.getTime())},
null, null, COLUMN_DATE + " ASC", null);
List<ActivityLocation> activityLocationList = new ArrayList<>();
while (cursor.moveToNext()) {
activityLocationList.add(convertCursorToEntity(cursor));
}
return activityLocationList;
}
public ActivityLocation convertCursorToEntity(Cursor cursor) {
ActivityLocation activityLocation = new ActivityLocation();
Location location = new Location();
activityLocation.setId(cursor.getInt(0));
location.setLatitude(cursor.getDouble(1));
location.setLongitude(cursor.getDouble(2));
activityLocation.setLocation(location);
activityLocation.setActivityType(ActivityType.values()[cursor.getInt(3)]);
activityLocation.setDate(new Date(cursor.getLong(4)));
return activityLocation;
}
Getting Error on this line :
activityLocation.setActivityType(ActivityType.values()[cursor.getInt(3)]);
Thanks in advance.
Most probably, the cursor only contains 3 resulting columns. Therefore you can only access 0, 1 and 2.
Shravan, you can't fetch 4th index value from the array when there are only 3 values.
You can access the index values of 0,1,2 only.
Use breakpoint on the crashing line and you will get a clear picture.
Well, you cant access 4th element of an array having just 3 elements. Mostly people confuse this having a little background in C/C++.
This is the difference in C/C++ and JAVA.
Suppose you have something like this:
int arr[] = {1,2,3};
Now, if you do arr[3] in C/C++, it will return some garbage value, whatever is present at the that particular address, but in JAVA , ArrayIndexOutOfBoundsException is thrown.
I have a programm where I create a Table:
//CAR_TABLE COLUMNS
public static final String CAR_COLUMN_ID = "ID";
public static final String CAR_COLUMN_ID_BARCODE = "ID_BARCODE";
public static final String CAR_COLUMN_Hersteller ="Hersteller";
public static final String CAR_COLUMN_KFZTyp = "KFZTyp";
public static final String CAR_COLUMN_Farbe = "Farbe";
public static final String CAR_COLUMN_AbteilungID = "AbteilungID";
public static final String CAR_COLUMN_SONDERAUSSTATTUNG ="Sonderausstattung";
public static final String CAR_COLUMN_Ausgeliefert = "Ausgeliefert";
public static final String CAR_COLUMN_ProgrammID ="ProgrammID";
public void onCreate(SQLiteDatabase db) {
String CREATE_CAR_TABLE = "CREATE TABLE " + TABLE_CARS + "(\n" +
CAR_COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, \n" +
CAR_COLUMN_ID_BARCODE + " TEXT, \n" +
CAR_COLUMN_Hersteller + " TEXT, \n" +
CAR_COLUMN_KFZTyp + " TEXT, \n" +
CAR_COLUMN_Farbe + " TEXT, \n" +
CAR_COLUMN_AbteilungID + " INTEGER, \n" +
CAR_COLUMN_Ausgeliefert + " TEXT, \n" +
CAR_COLUMN_SONDERAUSSTATTUNG + " TEXT, \n" +
CAR_COLUMN_ProgrammID + " INTEGER \n" +
");";
The database is created fine and I am able to add entries normally.
The problem is that, when I want to retrieve a row from the database, it tells me the following
03-11 16:00:00.470: E/CursorWindow(7465): Failed to read row 0, column 8 from a CursorWindow which has 1 rows, 8 columns.
03-11 16:00:00.470: D/AndroidRuntime(7465): Shutting down VM
03-11 16:00:00.470: E/AndroidRuntime(7465): FATAL EXCEPTION: main
03-11 16:00:00.470: E/AndroidRuntime(7465): Process: com.example.prog3, PID: 7465
03-11 16:00:00.470: E/AndroidRuntime(7465): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.prog3/com.example.prog3.ShowCars}: java.lang.IllegalStateException: Couldn't read row 0, col 8 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
My getAllCars Method:
public List<AutoEntry> getAllCars() {
List<AutoEntry> autoentrys = new ArrayList<AutoEntry>();
openDatabase();
Cursor cursor = database.query(TABLE_CARS, allColumnsAuto, null, null, null, null, null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
AutoEntry autoentry = cursorToCar(cursor);
autoentrys.add(autoentry);
cursor.moveToNext();
}
cursor.close();
closeDatabase();
return autoentrys;
}
and this is my Cursor method:
private AutoEntry cursorToCar(Cursor cursor) {
AutoEntry autoentry = new AutoEntry();
autoentry.setFarbe(cursor.getString(1));
autoentry.setHersteller(cursor.getString(2));
autoentry.setName(cursor.getString(3));
autoentry.setSonderaustattung(cursor.getString(4));
autoentry.setAbteilungID(cursor.getLong(5));
autoentry.setProgrammID(cursor.getLong(6));
autoentry.setAusgeliefert(cursor.getString(7));
autoentry.setBarcode(cursor.getInt(8));
return autoentry;
}
For the completness, here is my Insert method:
public void insertCar(String hersteller, String name, String farbe, String sonderausstattung, int abteilungID, String ausgeliefert, int barcode, int programmID) {
ContentValues values = new ContentValues();
values.put(Databasehandler.CAR_COLUMN_Hersteller, hersteller);
values.put(Databasehandler.CAR_COLUMN_KFZTyp, name);
values.put(Databasehandler.CAR_COLUMN_Farbe, farbe);
values.put(Databasehandler.CAR_COLUMN_SONDERAUSSTATTUNG, sonderausstattung);
values.put(Databasehandler.CAR_COLUMN_Ausgeliefert, ausgeliefert);
values.put(Databasehandler.CAR_COLUMN_AbteilungID, abteilungID);
values.put(Databasehandler.CAR_COLUMN_ID_BARCODE, barcode);
values.put(Databasehandler.CAR_COLUMN_ProgrammID, programmID);
try {
openDatabase();
long insertID = database.insert(this.TABLE_CARS, null, values);
Cursor cursor = database.query(this.TABLE_CARS, allColumnsAuto, Databasehandler.CAR_COLUMN_ID + " = " + insertID, null, null, null, null);
cursor.moveToFirst();
AutoEntry autoentry = cursorToCar(cursor);
cursor.close();
closeDatabase();
} catch (Exception ex) {
System.out.println("Error inserting entry!" + ex.toString());
}
}
How am I supposed to fix this that he starts at Row 1 or that my Data is stored at Row 0?
EDIT
private String[] allColumnsAuto = { Databasehandler.CAR_COLUMN_ID,
Databasehandler.CAR_COLUMN_Farbe,
Databasehandler.CAR_COLUMN_ID_BARCODE,
Databasehandler.CAR_COLUMN_Hersteller,
Databasehandler.CAR_COLUMN_KFZTyp,
Databasehandler.CAR_COLUMN_SONDERAUSSTATTUNG,
Databasehandler.CAR_COLUMN_AbteilungID,
Databasehandler.CAR_COLUMN_ProgrammID,
Databasehandler.CAR_COLUMN_Ausgeliefert };
Since column indexes are 0 based (as rows are - and as everything in Java is), you can't reference the non existing column 8.
So simply replace this
private AutoEntry cursorToCar(Cursor cursor) {
AutoEntry autoentry = new AutoEntry();
autoentry.setFarbe(cursor.getString(1));
autoentry.setHersteller(cursor.getString(2));
autoentry.setName(cursor.getString(3));
autoentry.setSonderaustattung(cursor.getString(4));
autoentry.setAbteilungID(cursor.getLong(5));
autoentry.setProgrammID(cursor.getLong(6));
autoentry.setAusgeliefert(cursor.getString(7));
autoentry.setBarcode(cursor.getInt(8));
return autoentry;
}
with this
private AutoEntry cursorToCar(Cursor cursor) {
AutoEntry autoentry = new AutoEntry();
autoentry.setFarbe(cursor.getString(0));
autoentry.setHersteller(cursor.getString(1));
autoentry.setName(cursor.getString(2));
autoentry.setSonderaustattung(cursor.getString(3));
autoentry.setAbteilungID(cursor.getLong(4));
autoentry.setProgrammID(cursor.getLong(5));
autoentry.setAusgeliefert(cursor.getString(6));
autoentry.setBarcode(cursor.getInt(7));
return autoentry;
}
Even better if you reference your columns by column name, instead of by column index
Something like:
cursor.getString(cursor.getColumnIndex("Column_Name"));
in your case:
autoentry.setHersteller(cursor.getString(cursor.getColumnIndex(CAR_COLUMN_Hersteller)));
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"
+ ");";
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.