Display data from Database in ListView - java

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.

Related

Can I use an SQLite View as parameter to a rawQuery

I'm attempting to add a few reports to my Android app. First, I defined them as Views in my SQLite database to make sure they work correctly. Here's one of them:
CREATE VIEW r3_DNFs AS SELECT Epreuve, Dossard, STRFTIME('%H:%M:%S %d',TempsPassage) AS "Temps" FROM Coureurs WHERE Statut is "DNF" ORDER BY SUBSTR(Epreuve, 5) + 0 DESC, Dossard;
Can I use the following to simplify my coding?
Cursor c = db.rawQuery("SELECT Epreuve, Dossard, Temps FROM r3_DNFs",null);
With rawQuery you can use any valid sqlite's statement but it should not be terminated (which doesn't contain the ; symbol).

Java: resultSet update does not update database

I am developing a Java app, as a learning tool for myself mainly, using a java database tutorial, and for some reason, the resultSet update is not actually updating my database.
Details about the project: I am using the Netbeans IDE and connecting to a Derby database with 5 tables (each with between 3 and 6 columns). The database viewer window is supposed to load all of the records into resultSet's and set the text in each blank in the window to those stored records. This process and the buttons to move the cursor to First, Previous, Next, and Last all work perfectly. The part I am currently working on is making the Update button get the text in the blanks and update the records in the database, accordingly.
Now to the problem: the records don't update. When I run the project and change a value, then press Update, the value doesn't revert back to the original value or anything (since I'm not setting the text again in the updateButton method), but when I click next and then previous, the text is back to its original value. Additionally, the values are not updated when I close the application and query the records in the database. I also don't get any exceptions, and Netbeans tells me the build is successful.
Relevant code for the update method (and yes, I'm aware it's probably inefficient, but I'm trying to just get it working before I break it trying to make it look better):
private void btnUpdateRecordActionPerformed(java.awt.event.ActionEvent evt) {
try {
// get text from fields and convert to appropriate data type
// in times
String wakeTime = fieldWakeTime.getText();
Time wakeTimeTm = java.sql.Time.valueOf(wakeTime);
String outTime = fieldOutTime.getText();
Time outTimeTm = java.sql.Time.valueOf(outTime);
String inTime = fieldOutTime.getText();
Time inTimeTm = java.sql.Time.valueOf(inTime);
String sleepTime = fieldOutTime.getText();
Time sleepTimeTm = java.sql.Time.valueOf(sleepTime);
// in weights
String morningPre = fieldPreWeight.getText();
double morningPreDoub = Double.parseDouble(morningPre);
String morningPost = fieldPostWeight.getText();
double morningPostDoub = Double.parseDouble(morningPost);
String nightWeight = FieldNightWeight.getText();
double nightWeightDoub = Double.parseDouble(nightWeight);
// in meals
String fullMeals = fieldFullMeals.getText();
int fullMealsInt = Integer.parseInt(fullMeals);
String snacks = fieldSnacks.getText();
int snacksInt = Integer.parseInt(snacks);
String sodas = fieldSodas.getText();
int sodasInt = Integer.parseInt(sodas);
String alcohol = fieldAlcohol.getText();
double alcoholDoub = Double.parseDouble(alcohol);
String desserts = fieldDesserts.getText();
int dessertsInt = Integer.parseInt(desserts);
// in ratings
String morningMood = fieldMorningMood.getText();
double morningMoodDoub = Double.parseDouble(morningMood);
String nightMood = fieldNightMood.getText();
double nightMoodDoub = Double.parseDouble(nightMood);
String activityRating = fieldActivityRating.getText();
double activityRatingDoub = Double.parseDouble(activityRating);
// uses rs's to update db columns
// in times
rsTimes.updateTime("WAKE_TIME", wakeTimeTm);
rsTimes.updateTime("OUT_TIME", outTimeTm);
rsTimes.updateTime("IN_TIME", inTimeTm);
rsTimes.updateTime("SLEEP_TIME", sleepTimeTm);
// in weights
rsWeights.updateDouble("MORNING_PRE", morningPreDoub);
rsWeights.updateDouble("MORNING_POST", morningPostDoub);
rsWeights.updateDouble("NIGHT_WEIGHT", nightWeightDoub);
// in meals
rsMeals.updateInt("FULL_MEALS", fullMealsInt);
rsMeals.updateInt("SNACKS", snacksInt);
rsMeals.updateInt("SODAS", sodasInt);
rsMeals.updateDouble("ALCOHOL", alcoholDoub);
rsMeals.updateInt("DESSERTS", dessertsInt);
// in ratings
rsRatings.updateDouble("MORNING_MOOD", morningMoodDoub);
rsRatings.updateDouble("NIGHT_MOOD", nightMoodDoub);
rsRatings.updateDouble("ACTIVITY_RATING", activityRatingDoub);
// updates rows
rsTimes.updateRow();
rsRatings.updateRow();
rsWeights.updateRow();
rsMeals.updateRow();
} catch (SQLException err) {
JOptionPane.showMessageDialog(this, err.getMessage());
}
}
When searching out solutions to this problem I've come across a great deal of variations on suggestions to con.setAutoCommit(false); and then commit the changes at the end of the method block, which I have tried, as well as explicitly con.setAutoCommit(true); to see if it wasn't defaulting to that for some reason, neither of which worked. (For reference, I did an earlier version of this app using, following the tutorial much more closely and using just 1 of the resultSet's and 1 of my tables and was able to get the update button working.) Also, my prepared statements have the resultSet's set to TYPE_SCROLL_INSENSITIVE and CONCUR_UPDATABLE, which I believe to be the correct options.
Link to the github repository of the project: link. The relevant file is MetrikaViewer.java, not DataManip.java, and the README (if you happened to need more information I didn't give you or like self-deprecating snark) is in the master branch, which is not where the rest of the code is (the Metrika branch) because of some problems I had using git (with an almost 100% chance of being caused by my own stupidity).
Really, as a still very new Java learner, I would not be at all surprised if this was caused by some weird misunderstanding of how something works on my part, but after a week of scratching my head, I just can't seem to find it.
Edit: As per Axel, I added updateRow's to the method. Now the changes update within the app while running, but it does not update the database. (I've updated the code above, accordingly, and the github repo should reflect the changes made.)
I have never used these updateXXX() methods, but as I understand the documentation, you have to issue a call to either rs.updateRow() or rs.insertRow() after updating the columns.
Also, you have to make sure to create your statement with ResultSet.CONCUR_UPDATABLE (since by default, readonly is used).

Android-Quiz App with SqliteAssetHelper

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.

SQLite query - Stop returning rows from database once a specific item has been found

I am creating an Android app to help actors rehearse from a script. The user can select a character from the script to rehearse as. The script will then be shown to the user up until his selected character's first line. When the user decides to proceed, their current line will appear, as well as the rest of the script up to their next line. The user can proceed again and so on.
I have the whole play stored in an SQLite database and I populate custom ListViews by executing queries on the database.
My question is how can we execute a query on the database, but stop returning items once we have found a certain item (e.g. the character's name)? I store the results into a Cursor then populate the ListView with the following method:
private void fillData() {
mFrom = new String[] { PlayDbAdapter.KEY_CHARACTER,
PlayDbAdapter.KEY_LINE };
mTo = new int[] { R.id.textCharacter, R.id.textLine };
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.play_list_layout, mCursor, mFrom, mTo);
setListAdapter(adapter);
}
If you require anymore information or code, please let me know.
Thank you!
It's far more efficient to return chunks of the script in a Cursor and then search the Cursor for the actor's first line.
Another way to do it would be to return line "context" for a character. Have the database store an index into the lines. Return a Cursor containing only the character's lines, then do a second query that returns 10 lines before and after the character's lines.

Android db.update not work if use db.delete first

I have a strange problem to update a table in my database...forgive me if I can not explain well but I'm a bit confused...
The problem is this:
I created a table with values, I read this values in my listview..everything works for now..insert and delete values works without problem..now created a loop in a service why do I need to make a comparison between a value and a string of my database and when this comparison is true, I need to change a value in my table..
The real problem is this: my db.update works only if not use ... never, the command db.delete... if use it, the db.update not work anymore ..and to make it work again, i need to make a new AVD.
how is it possible?
my db.delete and id is this:
item.getMenuInfo();
id = getListAdapter().getItemId(info.position);
public void deleteReg(SQLiteDatabase db ,long id)
{
db.delete(TabRegistry.TABLE_NAME, TabRegistry._ID + "=" + id, null);
}
on activity:
databaseHelper.deleteReg(db, id);
my db.update is this: (positions is a value of getPositions(),for locate a positions with a cursor(always works, even when fails db.update))
public void updateReg(SQLiteDatabase db,int positions, String stat)
{
ContentValues v = new ContentValues();
v.put(TabRegistry.STATUS, stat);
db.update(TabRegistry.TABLE_NAME, v, TabRegistry._ID + " = " + positions, null);
}
on service:
databaseHelper.updateReg(db, positions, "SUCCESS");
if you need more code, tell me what I add now..thanks in advance
The SQLite api you are using is based off of CRUD operations (you should read this).
You are DELETE-ing the record from the database, therefore there is nothing to UPDATE when you attempt to update it. If you want to create a new record, or recreate the one you deleted then you would perform an INSERT instead of an UPDATE.
EDIT:
It also appears you are passing in position number to the update and delete. I assume that you are also using this value to place the record in your table? Is it possible that when you delete the record from the table and the database, that the other records now have an invalid position because they haven't been updated also? It's just a shot in the dark, figured I might as well ask.

Categories