Separating a quiz questions into different groups - java

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.

Related

Using Android studio and my application force closes when i click a button [duplicate]

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 + ";"

where clause is not working in sqlite database in android

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;
}

Sql query is not working for SQLite database in android

i am new to android. i want to execute a sql query of selecting data with id 1 to 10.The query i m using is running successfully on DB browser for sqlite but not in the code. ab and bc are static variables of class catogaries.please help.
public class QuizHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION =1;
// 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 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)";
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");
this.addQuestion(q1);
Question q2 = new Question(" Name of the first university of India
?", "Nalanda University", "Takshshila University", "BHU", "Nalanda
University");
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");
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");
this.addQuestion(q4);
Question q5 = new Question("In which town of Punjab the largest grain
market of Asia is Available?", "Bathinda", "Khanna", "Ludhiana",
"Khanna");
this.addQuestion(q5);
Question q6 = new Question("Which is the highest dam in India?",
"Bhakhra Dam", "Hirakud Dam", "Tehri Dam", "Tehri Dam");
this.addQuestion(q6);
Question q7 = new Question("Which Indian state is having longest
coastline ?", "Rajasthan", "Gujrat", "Punjab", "Gujrat");
this.addQuestion(q7);
Question q8 = new Question("Name of the first Country to print books
?", "China", "India", "USA", "China");
this.addQuestion(q8);
Question q9 = new Question("Study of the Universe is known as?",
"Sociology", "Cosmology", "Petology", "Cosmology");
this.addQuestion(q9);
Question q10 = new Question("Big Bang theory explains ?", "Origin of
Universe.", "Origin of Sun", "Laws of physics.", "Origin of
Universe.");
this.addQuestion(q10);
Question q11 = new Question("Which Planet is dwarf planet?",
"Mercury", "Pluto", "Venus", "Pluto");
this.addQuestion(q11);
}
#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 = 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());
// 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_ID + "BETWEEN" + catogaries.bc + "AND" +catogaries.ab;
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.setID(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;
}
Error Log
04-05 15:00:28.452 31300-31300/com.example.chaitanya.myquiz
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.chaitanya.myquiz, PID: 31300
java.lang.RuntimeException: Unable to start activity
ComponentInfo
{com.example.chaitanya.myquiz.QuestionActivity}:
android.database.sqlite.SQLiteException: no such table:
questWHEREqidBETWEEN0AND10 (code 1): , while compiling:
SELECT* FROM questWHEREqidBETWEEN0AND10
at
android.app.ActivityThread.performLaunchActivity
(ActivityThread.java:2305)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2365)
at android.app.ActivityThread.access$800(ActivityThread.java:147)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5237)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:707)
Caused by: android.database.sqlite.SQLiteException: no such table: questWHEREqidBETWEEN0AND10 (code 1): , while compiling: SELECT * FROM questWHEREqidBETWEEN0AND10
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
Focus on the Exception:
no such table: questWHEREqidBETWEEN0AND10
You are missing space between table name , Where clause , And keyword etc . so the query makes it a whole string
use:
String selectQuery = "SELECT * FROM " + TABLE_QUEST + " WHERE " + KEY_ID + " BETWEEN " + catogaries.bc + " AND " +catogaries.ab;

How to output SQLite column to ArrayList? [duplicate]

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

SQLite two tables, one works, the other does not

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.

Categories

Resources