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
}
Related
I am working on a Shopping list where you can click on the item in the ListView and a dialog comes up. There you can modify the product name. It works fine, but now i am trying to add details.
Adding to database already works. It is in the third column but now I cant get it out with the onItemClickListener.
Get Data from the second column works fine, so the the product is working fine with ItemOnClick.
I already tried a couple of codes but didnt find a solution.
OnItemClick:
lvProducts.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try {
//DB*********************************
String name = parent.getItemAtPosition(position).toString();
Log.d(TAG, "onItemClick: You Clicked on " + name);
Cursor data = myDB.getItemID(name);
int itemID = -1;
while (data.moveToNext()){
itemID = data.getInt(0);
}
if (itemID > -1){
Log.d(TAG, "onItemClick: The ID is " + itemID);
Intent editScreenIntent = new Intent();
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
selectedID = editScreenIntent.getIntExtra("id",-1);
selectedName = editScreenIntent.getStringExtra("name");
}
showInputBox(arrayList.get(position), position);
} catch (Exception e) {
Toast.makeText(ShoppingActivity.this, "Error#666", Toast.LENGTH_SHORT).show();
}
}
});
DatabaseHelper:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String TABLE_NAME = "myList_data";
public static final String COL1 = "ID";
public static final String COL2 = "ITEM1";
public static final String COL3 = "ITEM2";
public DatabaseHelper(Context context){
super(context, TABLE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + COL2 + " TEXT, " + COL3 + " TEXT )";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
onCreate(db);
}
public boolean addData(String item, String detail){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2,item);
contentValues.put(COL3, detail);
long result = db.insert(TABLE_NAME,null,contentValues);
if (result == -1){
return false;
}else {
return true;
}
}
public Cursor getData(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor data = db.rawQuery(query, null);
return data;
}
public Cursor getItemID(String name){
SQLiteDatabase db = this.getWritableDatabase();
//String query = "SELECT "+ COL1 + " FROM " + TABLE_NAME + " WHERE " + COL2 + " = '" + name + "'";
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME,null);
//Cursor data = db.rawQuery(query, null);
return data;
}
/**
* Updates the name field
* #param newName
* #param id
* #param oldName
*/
public void updateName(String newName,int id,String oldName){
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE " + TABLE_NAME + " SET " + COL2 + " = '" + newName + "' WHERE " + COL1 + " = '" + id + "'" + " AND " + COL2 + " = '" + oldName + "'";
db.execSQL(query);
}
public void deleteName(int id, String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM " + TABLE_NAME + " WHERE " + COL1 + " = '" + id + "'" + " AND " + COL2 + " = '" + name + "'";
db.execSQL(query);
}
public void deleteAll(){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME,null,null);
String query =("DELETE FROM " + TABLE_NAME);
db.execSQL(query);
}
}
Try :-
int itemID = -1;
String item3 = ""; //<<<<<<<<<< ADDED
while (data.moveToNext()){
itemID = data.getInt(0);
item3 = data.getString(data.getColumnIndex(DatabaseHelper.COL3)); //<<<<<<<<<< ADDED
}
Note using getColumnIndex and the column name is more flexible and less prone to mis-calculation of offsets. You may wish to consider changing itemID = data.getInt(0); to itemID = data.getInt(data.getColumnIndex(DatabaseHelper.COL1));
Your getItemId method will, as it stands get all rows not just the row that has the name. You may wish to change from :-
public Cursor getItemID(String name){
SQLiteDatabase db = this.getWritableDatabase();
//String query = "SELECT "+ COL1 + " FROM " + TABLE_NAME + " WHERE " + COL2 + " = '" + name + "'";
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME,null);
//Cursor data = db.rawQuery(query, null);
return data;
}
to :-
public Cursor getItemID(String name){
SQLiteDatabase db = this.getWritableDatabase();
return db.query(TABLE_NAME,null,COL2+"=?",new String[]{name},null,null,null);
}
Note the above is in-principle code. It has not been tested or run and may therefore have some errors.
I added a column named id in the database "quest" by using the OnUpgrade() method.But when i run the app there is no data in the arrayList. I used Log for checking the cursor and ArrayList size,Both are zero. When i ran the app first Time it gaves an error of not having a column named id after that it gaves an error of :
java.lang.RuntimeException: Unable to start activity
ComponentInfo
{com.example.chaitanya.myquiz/
com.example.chaitanya.myquiz.QuestionActivity}:
android.database.sqlite.SQLiteException: no such column: id (code 1):
, while compiling: SELECT * FROM quest where id = '1'
I checked the query many time.When i used Select * from +TABLE_QUEST; there are 5 entries in the list and it works fine but not in this case.please help.
public class QuizHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
// Database Name
private static final String DATABASE_NAME = "bcd";
// tasks table name
private static final String TABLE_QUEST = "quest";
// tasks Table Columns names
private static final String KEY_ID = "qid";
private static final String KEY_QUES = "question";
private static final String KEY_ANSWER = "answer"; // correct option
private static final String KEY_OPTA = "opta"; // option a
private static final String KEY_OPTB = "optb"; // option b
private static final String KEY_OPTC = "optc"; // option c
private static final String KEY_ID2 = "id";
private SQLiteDatabase dbase;
public QuizHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
dbase = db;
String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_QUEST + " ( "
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_QUES
+ " TEXT, " + KEY_ANSWER + " TEXT, " + KEY_OPTA + " TEXT, "
+ KEY_OPTB + " TEXT, " + KEY_OPTC + " TEXT " + KEY_ID2 + "
INTEGER)";
db.execSQL(sql);
addQuestion();
// db.close();
}
private void addQuestion() {
Question q1 = new Question("Who is the president of india ?", "narender
modi", "hamid ansari", "pranab mukherji", "pranab mukherji",1);
this.addQuestion(q1);
Question q2 = new Question(" Name of the first university of India ?",
"Nalanda University", "Takshshila University", "BHU", "Nalanda
University",1);
this.addQuestion(q2);
Question q3 = new Question("Which college is awarded as Outstanding
Engineering Institute North Award�", "Thapar University", "G.N.D.E.C",
"S.L.I.E.T", "G.N.D.E.C",1);
this.addQuestion(q3);
Question q4 = new Question("Name of the first Aircraft Carrier Indian
Ship ?", "Samudragupt", "I.N.S. Vikrant", "I.N.S Virat", "I.N.S.
Vikrant",1);
this.addQuestion(q4);
Question q5 = new Question("In which town of Punjab the largest grain
market of Asia is Available?", "Bathinda", "Khanna", "Ludhiana",
"Khanna",1);
this.addQuestion(q5);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
if (newV > oldV) {
db.execSQL("ALTER TABLE " + TABLE_QUEST + " ADD COLUMN " +
KEY_ID2 + " INTEGER DEFAULT 0");
}
onCreate(db);
}
// Adding new question
public void addQuestion(Question quest) {
// SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_QUES, quest.getQUESTION());
values.put(KEY_ANSWER, quest.getANSWER());
values.put(KEY_OPTA, quest.getOPTA());
values.put(KEY_OPTB, quest.getOPTB());
values.put(KEY_OPTC, quest.getOPTC());
values.put(KEY_ID2,quest.getID());
// Inserting Row
dbase.insert(TABLE_QUEST, null, values);
}
public List<Question> getAllQuestions() {
List<Question> quesList = new ArrayList<Question>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_QUEST + " where " +
KEY_ID2 + " = '1' ";
// + KEY_ID2 + " = 1"
dbase = this.getReadableDatabase();
Cursor cursor = dbase.rawQuery(selectQuery, null);
Log.i("here",cursor.getCount()+"");
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Question quest = new Question();
quest.setID(cursor.getInt(0));
// Log.i("here",cursor.getInt(0)+"");
quest.setQUESTION(cursor.getString(1));
quest.setANSWER(cursor.getString(2));
quest.setOPTA(cursor.getString(3));
quest.setOPTB(cursor.getString(4));
quest.setOPTC(cursor.getString(5));
quesList.add(quest);
} while (cursor.moveToNext());
}
// return quest list
return quesList;
}
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.