I've started to develop a quiz application (multiple and single choice) for android.
The reason why I chose the SqliteAssetHelper library is, that I want a prepopulated database.
I've created a sqlite database with 2 tables (question & answer).
With the following method in my database class I'm getting the question items:
public Cursor getQuestionItems() {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(TABLES.QUESTION);
Cursor questionCursor = qb.query(db, null, null, null, null, null, null);
return questionCursor;
}
In the main class (in onCreate) I'm creating question objects and add them to the arraylist:
Cursor questionCursor = db.getQuestionItems();
while (questionCursor.moveToNext()) {
Question question = new Question();
question.setId(
questionCursor.getString(questionCursor.getColumnIndexOrThrow(MyDatabase.QuestionColumns.ID)));
question.setQuestiontext(questionCursor
.getString(questionCursor.getColumnIndexOrThrow(MyDatabase.QuestionColumns.QUESTIONTEXT)));
question.setQuestiontype(questionCursor
.getInt(questionCursor.getColumnIndexOrThrow(MyDatabase.QuestionColumns.QUESTIONTYPE)));
questionList.add(question);
}
questionCursor.close();
I'm doing the same also for the answer items. Now I want to show a view with a question and the possible answers (for example 4 answers). If the user clicks on the "next"-button the next question with the answers should be displayed.
How can I achieve this efficiently? Is it at all necessary to create question and answer items? I'm not sure if this is the right way.
Thanks in advance!
To follow database rules, we should do like that. One table for questions, one table for answers as per the structure provided by you. Its the better way, because you will follow the database rule and there will not be redudant data. But when displaying the answer, display the data for proper question ID.
Related
I'm new to Java, Swing and programming, but I need to make an application. I'm using NetBeans for development and here's my question:
If I drag and drop the JTable to my frame and select custom code for the table, I get this code:
appView.java
tblViewData = new javax.swing.JTable();
tblViewData.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"ID", "Reference No", "Name", "Description"
}
));
jScrollPane1.setViewportView(tblViewData);
What I want to do is populate new Objects[][] with data that I fetch from the appController using ResultSet and the values I set in the appModel for variables ID, Ref, Name and Desc.
Here's a sample code of an insert I attempted to see if I could display a row of data:
new Object [][] {
{ new Integer(model.getID()), model.getRef(), model.getName(), model.getDesc() }
},
This code returns a 0 in the first column of the row.
Am I approaching this problem wrong?
Thanks for the help.
Well I have no idea what the "appController" or "appModel" are. Maybe these are IDE dependent classes? Instead of using the IDE to generate your SQL code I suggest you write your own code and populate the table yourself.
There are plenty of examples on the forum showing how to load a JTable with data from a ResultSet. Just search for examples using those two class names as your keywords.
Or you can check out Table From Database which shows how you can use the DefaultTableModel to load rows of data from the ResultSet.
final SQLiteDatabase mydb = openOrCreateDatabase("phone_calls",MODE_PRIVATE,null);
mydb.execSQL("CREATE TABLE IF NOT EXISTS Numbers(PhoneNumber VARCHAR,FullName VARCHAR,Cost VARCHAR );");
mydb.execSQL("CREATE TABLE IF NOT EXISTS Calls(FromNum VARCHAR,ToNum VARCHAR,duration VARCHAR );");
Ive created this sqlite in Activity 1. i inserted some data to the first table in first activity.
now i created a second activity and i want to insert data to the other table?what shall i do? create the database again in the second activity and insert in it? or is there any other way?
First of all, you should read the docs - https://developer.android.com/training/basics/data-storage/databases.html
Next, you should try to write simple application in order to use new knowledge.
If it fails, then post the question with more code and Logcat output.
Just create a database helper class which will create all your tables,
then create needed methods like saveObject(YourObject), deleteObject(id),
etc...
Make your helper singleton and initiate it once in Application in onCreate()
and just use it in your activities.
For example you can look here: https://gist.github.com/mikeplate/9173040
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
The following code is a function in my dbhandler. This works fine on android studio emulator but crashes on my actual mobile. If I comment out the line SQLiteDatabase db = this.getWritableDatabase(); then it works fine. What would cause this?
public ArrayList<Integer> getCategories(int ParID){
ArrayList<Integer> catAr = new ArrayList<Integer>();
catAr.add(1);
//loop thru all cats and store id's in catAr
String query = "Select * FROM " + TABLE_PRODUCTS;
SQLiteDatabase db = this.getWritableDatabase();
db.close();
return catAr;
}
Please confirm if the DB exists or not. As mentioned in the docs this method could throw a SQLiteException if the database cannot be opened for writing.
Also please enclose this method use in try/catch block so that it is easier to debug and fails gracefully without crashing the app.
You might change your database, and in emulator it reads from old version. if you change database version(in your custom SQLiteOpenHelper class) then you might see that error in emulator too:
super(context, DB_NAME, null, DB_VERSION);
for example change DB_VERSION from 1 to 2.
This question already has answers here:
Not equal <> != operator on NULL
(10 answers)
Closed 8 years ago.
After hours (basically the entire day) of wriggling around, wrapping my throughts and whatnot, I am baffled as to why my UPDATE statement in SQLite does not want to work.
It concerns the following queries:
sql.Update("UPDATE SAVEGAME SET _id = \"save\" WHERE _id = null");
sql.Update("UPDATE SAVEGAME SET WORLD_ONE = \""+finishedLevels+"\" WHERE _id = 'save'");
I've also tried
sql.Update("UPDATE SAVEGAME SET _id = 'save' WHERE _id = null");
sql.Update("UPDATE SAVEGAME SET WORLD_ONE = '"+finishedLevels+"' WHERE _id = 'save'");
but to no avail.
The function I'm calling is this:
public void Update(String query){
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(query);
db.close();
}
Debugging clearly shows that the functions is being called and stepped through but refuses to work.
Any other SQL function I call (e.g. to create new tables etc.) all have their db.close() call present.
I've also tried looking at a different project where the UDPATE statement does work, but I can't find any differences (instance of my SQLLib class, function calls are the same, etc.)
It would seem so simple to call an UPDATE statement, but it has a fault somewhere.
Where is this fault? Because I'm at a total loss now.
-Zubaja
You are using = null when you need to use is null:
Change:
sql.Update("UPDATE SAVEGAME SET _id = \"save\" WHERE _id = null");
To this:
sql.Update("UPDATE SAVEGAME SET _id = \"save\" WHERE _id is null");
^^^^
Also, you may want to check how you are creating your SQL strings - inserting variables like that leaves your code prone to SQL Injection attacks.
So I've been reading the Android Developer docs and have spent the last few hours reading tutorials online and have downloaded a few samples. Some of them compile, some don't.
The ones that compile use the SQLLiteDatabase in different ways than other samples I downloaded. I'm now totally confused. I was following along with the Training docs on http://developer.android.com/guide/topics/data/data-storage.html#db until I got half way down the page where it just stopped, and said that we can checkout the Note Pad sample. But the Notepad sample uses different code than what I had just read in the docs.
My scenario:
Display ListView that pulls data from SQLiteDatabase in MainActivity.xml
If user presses 'Add entry' button in AddEntryActivity.xml, add the entry to the database
If user presses 'Delete entry' button in DeleteEntryActivity.xml, delete the entry in the database.
So it's pretty simple stuff which I could do in just a couple minutes in C# but I'm new to android and I have absolutely no idea where to start. I started with the documentation, but all it does it go about half way and then refers you to the sample which is just more confusing since it uses different code.
How can I achieve this?
Use SQLiteDatabase class for this
SQLiteDatabase db = openOrCreateDatabase("Database_Name", MODE_PRIVATE, null);
//Create Table
String strsql = "CREATE TABLE IF NOT EXISTS TableName(Name VARCHAR(30),id INT(15) unique) ";
db.execSQL(strsql);
you can fire query as you do in MYSQL(INSERT,UPDATE,DELETE) using db.execSQL()
To Retrive data you can use this
strsql = "SELECT * FROM TableName ";
Cursor c = db.rawQuery(strsql, null);
int count = c.getCount();
c.moveToFirst();
while (k >= 0) {
ListviewContent.add(c.getString(c.getColumnIndex("Name")));
setListAdapter(new ListViewAdapter(this));
c.moveToNext();
k--;
}
//you can set retrived data to list view as shown above.