This question already has answers here:
What's the best way to iterate an Android Cursor?
(10 answers)
Closed 6 years ago.
I have an SQLite Database.
Here's some of the code setting it up:
// Field Names:
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_DESCRIPTION = "description";
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_NAME, KEY_DESCRIPTION};
// Column Numbers for each Field Name:
public static final int COL_ROWID = 0;
public static final int COL_NAME = 1;
public static final int COL_DESCRIPTION = 2;
// DataBase info:
public static final String DATABASE_NAME = "dbMetrics";
public static final String DATABASE_TABLE = "mainMetrics";
public static final int DATABASE_VERSION = 1;
//SQL statement to create database
private static final String DATABASE_CREATE_SQL =
"CREATE TABLE " + DATABASE_TABLE
+ " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_NAME + " TEXT NOT NULL, "
+ KEY_DESCRIPTION + " TEXT"
+ ");";
I want to output one of my columns KEY_NAME as an ArrayList.
To do this, I have so far generated the following code:
public ArrayList<String> getAllStringValues() {
ArrayList<String> myStringValues = new ArrayList<String>();
Cursor result = db.query(true, DATABASE_TABLE,
new String[] {KEY_NAME}, null, null, null, null,
null, null);
**********CODE NEEDED HERE***********
System.out.println(Arrays.toString(myStringValues.toArray()));
return myStringValues ;
}
However, I am not sure how I get the data from the column into an ArrayList from here.
My Question
Can someone give me some assistance as to how to design a loop that will go through each row in the column and put that data in an ArrayList?
I'm pretty sure I will need to at some point use
result.getString(result.getColumnIndex(KEY_NAME))
in order to do this, but again, I'm not sure how.
Any help would be greatly appreciated.
if (Cursor.moveToFirst()) {
do {
keyname.add(Cursor.getString(Cursor.getColumnIndex("keyname")));
key_description.add(Cursor.getString(Cursor.getColumnIndex("key_description")));
} while (Cursor.moveToNext());
}
Cursor.close();
try this code if doesnt work, tell me
Related
it keeps telling me column _id doesn't exist and in my whole code I didn't find the word _id
public static final String TABLE_NAME = "LIST";
public static final String _ID = "_Id";
public static final String PRODUCT_NAME = "Product";
static final String DB_NAME = "LIST.DB";
static final int DB_VERSION = 1;
private SQLiteDatabase database;
private static final String CREATE_TABLE = " CREATE TABLE " + TABLE_NAME + "(" + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + PRODUCT_NAME + " TEXT NOT NULL );";
final String[] from = new String[]
{DatabaseHelper. _ID , DatabaseHelper. PRODUCT_NAME};
final int[] to = new int[]
{R.id._Id , R.id.Product};
adapter = new SimpleCursorAdapter(this ,R.layout.viewrecord , c , from , to , 0);
listView.setAdapter(adapter);
I am new to SQLite queries in android. Trying to run a query. However, app keeps crashing with the following error :
Caused by: java.lang.IllegalStateException: Couldn't read row 1, col
-1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
Below is the extract of Code
public String getOutputData(){
String inputData = "'Vineet'";
Cursor cursorNew = db.rawQuery("SELECT email FROM groupseries INNER JOIN email " +
"ON groupseries.emailid = email._id INNER JOIN user ON " +
"groupseries.userid = user._id WHERE name=" + inputData, null);
cursorNew.moveToFirst ();
StringBuffer buffer = new StringBuffer();
while(cursorNew.moveToNext()){
int index1 = cursorNew.getColumnIndex(DatabaseHelper.KEY_NAME);
int index2 = cursorNew.getColumnIndex(DatabaseHelper.KEY_EMAIL);
String userID = cursorNew.getString(index1);
String emailID = cursorNew.getString(index2);
buffer.append(userID + " " + emailID + "\n");
}
return buffer.toString();
}
Below is the code for table creation I am using. (Open to suggestions to make this less clumsy).
private static final String DATABASE_NAME = "tryDemoDataBase.db";
private static final String TABLE_NAME_USER = "user";
private static final String TABLE_NAME_EMAIL = "email";
private static final String TABLE_NAME_GROUP = "groupseries";
private static final int DATABASE_VERSION = 12;
private static final String KEY_ROWID_USER = "_id";
private static final String KEY_ROWID_EMAIL = "_id";
private static final String KEY_ROWID_GROUP = "_id";
private static final String REFERENCE_USER_ID = "userid";
private static final String REFERENCE_EMAIL_ID = "emailid";
private static final String KEY_NAME="name";
private static final String KEY_EMAIL = "email";
private static final String CREATE_TABLE_USER = "create table "+ TABLE_NAME_USER
+ " ("+ KEY_ROWID_USER+" integer primary key autoincrement, "
+ KEY_NAME + " text)";
private static final String CREATE_TABLE_EMAIL = "create table "+ TABLE_NAME_EMAIL
+ " ("+ KEY_ROWID_EMAIL+" integer primary key autoincrement, "
+ KEY_EMAIL + " text)";
private static final String CREATE_TABLE_GROUP = "create table " + TABLE_NAME_GROUP+ " ("
+ KEY_ROWID_GROUP+" integer primary key autoincrement, "
+ REFERENCE_USER_ID + " integer, " + REFERENCE_EMAIL_ID + " integer)";
First remove this line:
cursorNew.moveToFirst();
because later you use:
while (cursorNew.moveToNext())
so actually you are skipping the 1st (and maybe the only) row of the results.
Then you must include in the selected columns the column name if you want to retrieve it from the Cursor object:
Cursor cursorNew = db.rawQuery("SELECT name, email FROM groupseries INNER JOIN email " +
"ON groupseries.emailid = email._id INNER JOIN user ON " +
"groupseries.userid = user._id WHERE name=" + inputData, null);
And a suggestion to use the recommended and safe way of passing parameters to a query instead of concatenating them directly.
Use ? placeholders:
String inputData = "Vineet"; // no quotes
Cursor cursorNew = db.rawQuery(
"SELECT name, email FROM groupseries INNER JOIN email " +
"ON groupseries.emailid = email._id INNER JOIN user ON " +
"groupseries.userid = user._id WHERE name=?",
new String[] {inputData}
);
I've searched a lot for this question but can't seem to actually find an answer. My quiz app works well, but I realized that 50 questions all at once were too many.
Right now, my app works by people clicking a button that says "Begin" and they enter the quiz. After the quiz, all of the questions that they got wrong are shown with the correct answer. However, what I'd like to do is group these into questions of 10. So, select "Question Set 1" Button, "Question Set 2" Button, etc. Then, I'd still like to show the correct answer to the questions contained in this question set.
I'm not actually sure how to separate the questions and have my logic still work. Below I've included by database helper class. I've exempted most of the questions to shorten it. Thank you so much!
public class DbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "realEstateQuiz";
// tasks table name
private static final String TABLE_QUEST = "quest";
// tasks Table Columns names
private static final String KEY_ID = "questionId";
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_OPTD = "optd"; // option d
private SQLiteDatabase dbase;
public DbHelper(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_OPTD + " TEXT)";
db.execSQL(sql);
addQuestions(db);
// db.close();
}
private void addQuestions(SQLiteDatabase db) {
Question q1 = new Question(
"When a real estate professional exaggerates " + "about a parcel of property, they are likely:",
"Misrepresenting the property", "Guilty of fraud", "Puffing", "All of the above", "Puffing");
this.addQuestion(q1, db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUEST);
// Create tables again
onCreate(db);
}
// Adding new question
public void addQuestion(Question quest, SQLiteDatabase db) {
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_OPTD, quest.getOptd());
// Inserting Row
db.insert(TABLE_QUEST, null, values);
}
public List<Question> getAllQuestions() {
List<Question> quesList = new ArrayList<Question>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_QUEST;
dbase = this.getReadableDatabase();
Cursor cursor = dbase.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Question quest = new Question();
quest.setQuestionId(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));
quest.setOptd(cursor.getString(6));
quesList.add(quest);
} while (cursor.moveToNext());
}
// return quest list
cursor.close();
dbase.close();
return quesList;
}
public int rowcount() {
int row = 0;
String selectQuery = "SELECT * FROM " + TABLE_QUEST;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
row = cursor.getCount();
cursor.close();
return row;
}
}
It seems to me that your Question objects and corresponding table should contain an additional field which indicates which Question Set they belong to. Your DbHelper class should then beable to query Questions by set. Or alternatively you could sort all Questions by their set in the java code, but I would prefer to leave that to the db.
However, If you wish to divide all the questions into sets of 10 you could try something like the following:
List<Set<Question>> questionSets = new ArrayList<Set<Question>>();
Set<Question> questionSet = new HashSet<Question>();
questionSets.add(questionSet);
int counter = 0;
for(Question question : dbHelper.getAllQuestions()){
if(++counter > 10){
counter = 0;
questionSet = new HashSet<Question>();
questionSets.add(questionSet);
}
questionSet.add(question);
}
This will collect ten questions into a Set and the add them to the list of Question Sets. You could then access each question set from that list.
This question already has answers here:
When does SQLiteOpenHelper onCreate() / onUpgrade() run?
(15 answers)
Closed 7 years ago.
I'm trying to update a particular row of a database, and I have the following code
public String CREATE_QUERY = "CREATE TABLE " + TableData.TableInfo.TABLE_NAME +
"(" + TableData.TableInfo.USER_NAME + " TEXT, " + TableData.TableInfo.USER_PIN +
" TEXT, " + TableData.TableInfo.PARTNER_FIRST + " Text, " + TableData.TableInfo.PARTNER_SECOND +
" TEXT, " + TableData.TableInfo.DATE + " TEXT, " + TableData.TableInfo.SIGNATURE_IMAGE + " BLOB, " +
TableData.TableInfo.PARTNER_SIGNATURE + " BLOB);";
And I am getting an error from
ContentValues cv = new ContentValues();
DatabaseOperations DOP = new DatabaseOperations(ctx);
Cursor CR = DOP.getInformation(DOP);
CR.moveToLast();
SQLiteDatabase SQ = DOP.getWritableDatabase();
ContentValues args = new ContentValues();
args.put(TableData.TableInfo.USER_NAME, CR.getString(0));
args.put(TableData.TableInfo.PARTNER_FIRST, partner_name);
SQ.update(TableData.TableInfo.TABLE_NAME, args, "ROWID=?" + id, null);
This is the error:
Caused by: android.database.sqlite.SQLiteException: no such column: partner_first (code 1): , while compiling: UPDATE reg_info SET user_name=?,partner_first=? WHERE ROWID=?54
Here is my table info
public static abstract class TableInfo implements BaseColumns {
public static final String USER_NAME = "user_name";
public static final String USER_PIN = "user_pin";
public static final String PARTNER_FIRST = "partner_first";
public static final String PARTNER_SECOND = "partner_second";
public static final String DATE = "date";
//public static final String LOC = "location";
public static final String SIGNATURE_IMAGE = "signature_image";
public static final String PARTNER_SIGNATURE = "partner_signature";
public static final String DATABASE_NAME = "user_info";
public static final String TABLE_NAME = "reg_info";
}
What am I doing wrong?
Uninstall and rename the database.. This happens frequently when you
change your table name or any change in database.
The problem is in your UPDATE statement - you have a concatenated string and are not passing the "WHERE" arg correctly on this line:
SQ.update(TableData.TableInfo.TABLE_NAME, args, "ROWID=?" + id, null);
simply do this:
SQ.update(TableData.TableInfo.TABLE_NAME, args, "ROWID=" + id, null);
the error is misleading because the SQL statement is wrong altogether.
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.