I am working on a project that containg tables in SQL and shows them in ListViews, i get "column '_id' does not exist" crush when i try to get to the activity containing the listview, i have checked other answers here and they all say i have to have a colum named "_id", and i do, what else could cause this error?
this is my constants class
final static String DB_CLIENTS_ID = "_id";
final static String DB_CLIENTS_NAME = "name";
final static String DB_CLIENTS_BALANCE = "balance";
final static String DB_CLIENTS_IDNUM = "idNum";
final static String DB_CLIENTS_TYPE = "type";
here is the hendler function that gets the curser:
public Cursor queryClients(){
db = dbOpenHelper.getReadableDatabase();
Cursor cursor = db.query(dbConstants.TABLE_NAME_CLIENTS,
null, null, null, null, null,
dbConstants.DB_CLIENTS_NAME+ " ASC");
return cursor;
}
here is the snippet that uses the curser to make the listview:
dbhendler = new dbHendler(this);
Cursor c = dbhendler.queryClients();
startManagingCursor(c);
String[] from = new String[] {dbConstants.DB_CLIENTS_ID, dbConstants.DB_CLIENTS_NAME,dbConstants.DB_CLIENTS_BALANCE};
int[] to = new int[] {R.id.account_list_id_number, R.id.account_list_client_name, R.id.account_list_balance};
adapter = new SimpleCursorAdapter(this, R.layout.account_list_line, c, from, to);
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(adapter);
what could be the problem besides having no colum named "_id"?
edit:
here is the log cat:
01-28 10:00:31.806: E/AndroidRuntime(27937): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ziv.bank_app/com.ziv.bank_app.ClientListActivity}: java.lang.IllegalArgumentException: column '_id' does not exist
edit:
code for creating table:
public void onCreate(SQLiteDatabase db) {
String sql1 = ""
+ "CREATE TABLE "+ dbConstants.TABLE_NAME_CLIENTS+ " ("
+dbConstants.DB_CLIENTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+dbConstants.DB_CLIENTS_NAME + " TEXT,"
+dbConstants.DB_CLIENTS_IDNUM + " INTEGER,"
+dbConstants.DB_CLIENTS_TYPE + " TEXT,"
+dbConstants.DB_CLIENTS_BALANCE + " REAL"
+ ")";
db.execSQL(sql1);
when first seing the problem i saw here that the answer was to have a string named "_id", i changed it in my table creation file, however a new file was never created, it would have been created on a new device/emulator but on mine it still used the one i have created.
create a new database file by simply changing its name in the table creation code, and the problem is solved.
edit:
also raising the version number would do the trick
I had similar problem this is the way I tried it out
You can give it a try :
1) first delete your database from your device or emulator
emulator : within data/data/databases
device :use adb shell and run-as command
2) create a new database with different name(not same as previous one).
Let me know if problem persists
Hope It could help you ...
If i am not wrong then try out this in your queryClients():
Cursor cursor = db.query(dbConstants.TABLE_NAME_CLIENTS, new String[] {"_id","name","balance","idNum","type"},
null, null, null, null, "name ASC ");
or Try this:
Cursor mCursor = db.query(true, dbConstants.TABLE_NAME_CLIENTS,
new String[] {"_id","name","balance","idNum","type"},
null,null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
Related
I want to retrieve a specific user from a SQLite database on Android with a provided username using a Cursor. I've tried this:
String[] fields = new String[] { "username", "email", "dateRegister" };
Cursor c = db.query(tableName, fields, "username ='1234'", null);
But it isn't working. How can I retrieve a specific row with the information of a unique column?
try this
db.query(tableName, null, "username = ?", new String[]{"username"}, null, null, null);
lots of guys asked the same question ,so please search efficient.
String query = "select * from " + tableName + " where "+ KEY_USERNAME + " = '" + uname + "'";
SQLiteDatabase sql = this.getReadableDatabase();
Cursor cur = sql.rawQuery(query, null);
return cur;
i have created the next db file -
String sql = ""
+ "CREATE TABLE "+ Constants.TABLE_NAME + " ("
+ Constants.NAME_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Constants.NAME_PERSON + " TEXT"
+ ")";
db.execSQL(sql);
Now what I would like to know is, how to be able to run on the db and to know if a name already exist sin the db, and if so i would like to get the id of that row.
all i can understand is that i should use the
Cursor c= db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy)
but I don't have a clue what I should do next -
so thanks for any kind of help
you can add this in your DB and call the function passing "to be searched key" as an argument
public boolean checkIfExist(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_INFO, new String[] { KEY_TITLE}, KEY_TITLE + "=?",
new String[] { name }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
if (cursor.moveToFirst()) {
return true;
}else{
return false;
}
}
Where KEY_TITLE is the column name in your table.
Take more example on this:
AndroidSQLite
AndroidSQLite with multi tables
Make a SELECT request. Then check with if(cursor.moveToFirst()) if your name is already existing. (moveToFirst() return true if there is at least 1 value).
So if your value is existing, juste get its id with cursor.getString(cursor.getColumnIndex("_id"));
I try to get all unique values from database coulmn using SELECT DISTINCT sql command.
But i get exception when my activity is loading, i have this error code in logcat:
05-05 09:08:32.637: E/AndroidRuntime(1314): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.workoutlog/com.example.workoutlog.AddWorkOutPage}: android.database.sqlite.SQLiteException: near "SELECT": syntax error (code 1): , while compiling: SELECT * FROM exerciseTable WHERE SELECT DISTINCTexercise_typefromexerciseTable
I think that i have not wrote the command correctly, here is my code:
public String[] getAllExercies() {
String selecet = "SELECT DISTINCT" + COLUMN_EXERCISE + "from" + TABLE_NAME;
Cursor c = ourDatabase.query(TABLE_NAME, null, selecet, null, null, null, null);
int dayExercise = c.getColumnIndex(COLUMN_EXERCISE);
String[] list = new String[c.getCount()-1];
int j = 0;
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
list[j] = c.getString(dayExercise);
j++;
}
return list;
}
I think you should first checkout these answers here and here in order to see the working of .query() function.
Please note that while using ourDatabase.query() function, the parameters are as follows:
String Table Name: The name of the table to run the query against
String [ ] columns: The projection of the query, i.e., the columns to retrieve
String WHERE clause: where clause, if none then pass null
String [ ] selection args: The parameters of the WHERE clause
String Group by: A string specifying group by clause
String Having: A string specifying HAVING clause
String Order By by: A string Order By by clause
So your third variable should be a WHERE clause, something like:
String[] args = { "first string" };
Cursor c = ourDatabase.query("TABLE_NAME", null, "exercise_type=?", args, null, null, null);
Since you don't need a WHERE clause, for your purposes you might want to use rawQuery() method instead.
String selecet = "SELECT DISTINCT " + COLUMN_EXERCISE + " FROM " + TABLE_NAME;
ourDatabase.rawQuery(selecet, null);
Update
Try the answer from here. Do something like this:
Cursor c = ourDatabase.query(true, "exerciseTable", new String[] {"exercise_type"}, null, null, "exercise_type", null, null, null);
int dayExercise = c.getColumnIndex(COLUMN_EXERCISE);
//... continue with your further code
Hope this helps else please comment.
Issue:
you have not maintained the space between the words.
Explaination:
suppose, String COLUMN_EXERCISE = "exercise";
and String TABLE_NAME = "tbl_workout";
then
String selecet = "SELECT DISTINCT" + COLUMN_EXERCISE + "from" + TABLE_NAME;
simply means,SELECT DISTINCTexercisefromtbl_workout
Solution:
String selecet = "SELECT DISTINCT " + COLUMN_EXERCISE + " from " + TABLE_NAME;
Edit:
Kindly use following syntax to fire rawQuery
Cursor c = ourDatabase.rawQuery(selecet,null);
I hope it will be helpful !
You miss all the spaces in your query, you should replace with this:
String selecet = "SELECT DISTINCT " + COLUMN_EXERCISE + " FROM " + TABLE_NAME;
I am trying to put together an SQL database but don't really know how to make it work. The intention is to have multiple columns, some with integers, some with strings in their cells. For this app, I want repetitions to be an integer and exercise to be a string. Here is the relevant parts of the code:
public static final String KEY_ROWID = "_id";
public static final String KEY_DATE = "date";
public static final String KEY_EXERCISE = "exercise";
public static final String KEY_REPS = "repetitions";
private static final String DATABASE_CREATE = "create table " + DATABASE_TABLE + " ("
+ KEY_ROWID + " integer primary key autoincrement, "
+ KEY_DATE + " text not null, "
+ KEY_EXERCISE + " text not null, "
+ KEY_REPS + " int not null, "
public long createExercise(String exercise, int reps) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_DATE, date);
initialValues.put(KEY_EXERCISE, exercise);
initialValues.put(KEY_REPS, reps);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
I put data in this table using test strings. Then I try to pull the data with the following query:
public Cursor graphQuery(String exercise, String workout) {
return mDb.query(DATABASE_TABLE, new String[] {KEY_DATE, KEY_REPS}, null, null,
null, null, null);
From there I try to put the data into a number array but it gives me an error. It tells me to put KEY_REPS as a number when I declared it. But if I declare KEY_REPS as a number it doesn't let me build my databes.
Cursor cursor = mDbHelper.graphQuery(currentexercise, currentworkout);
startManagingCursor(cursor);
Number[] reps = new Number[]{workoutDbAdapter.KEY_REPS}; //error here
I feel like I am missing a key part in how to create my database. Can anyone help?
Code from book I am trying to follow (except using integers) (from comment on first answer)
private void fillData() {
Cursor remindersCursor = mDbHelper.fetchAllReminders();
startManagingCursor(remindersCursor);
// Create an array to specify the fields we want (only the TITLE)
String[] from = new String[]{RemindersDbAdapter.KEY_TITLE};
That being said, if someone knows of a good website that teaches SQLite as it applies to Android that would be awesome. The only ones I have been able to find are generic SQL sites and they aren't very helpful.
Cursor cursor = mDbHelper.graphQuery(currentexercise, currentworkout);
startManagingCursor(cursor);
Number[] reps = new Number[]{WorkoutDbAdapter.KEY_REPS}; //error here
This code here doesn't do what (I think) you want it to. You need to iterate over the cursor and get the data from there. I'm pretty sure, if you followed the Android sample code for using databases that WorkoutDbAdapter.KEY_REPS is a string constant that holds reps column name.
Try doing something like this:
List<Number> allReps = new ArrayList<Number>();
Cursor cursor = mDbHelper.graphQuery(currentexercise, currentworkout);
while (cursor.moveToNext()) {
int reps = cursor.getInt(cursor.getColumnIndexOrThrow(mDbHelper.KEY_REPS));
allReps.add(reps);
}
Number[] repsArray = allReps.toArray(new Number[]{});
// do stuff with repsArray and don't forget to close cursor
Hi all
I create a table like that
private static final String CREATE_TABLE_PRODUCT =
"create table prod (id integer primary key,titre text not null, desc text, is_free integer);";
i update it this way
SQLiteDatabase db = getConnection();
ContentValues updateEvent = new ContentValues();
updateEvent.put("is_free", 1);
int ok = db.update(prod, updateEvent, "id=?",
new String[] { Long.toString(evenement.getId()) });
db.close();
I do see the change in eclipse with DDMS questoid
but when i try to retrieve the value I get nothing ....
Cursor c = db.query(prod, new String[] { "id",
"titre", "desc", "is_free", },
"is_free=?", new String[] {"1"}, null, null,
null);
I've tried some variant like
String query = "SELECT * FROM "+EVENEMENT_TABLE+" WHERE is_free=1;";
Cursor c = sdb.rawQuery(query, null);
with no success
is this problem come from the type (integer) of my column ?
Any help
Do not use reserved keywords like desc in your queries. This probably causes query to fail.
In case you don't know update will not add values to the table. Use insert instead.