Android database utility library - java

Rather than have to rewrite a class that extends SQLiteOpenHelper every time I want an app with a database component, I'm trying to make a database utility library project. Is this possible?
I call the class DBUtil. It extends SQLiteOpenHelper, overrides onCreate & onUpgrade, and has functions for inserting and selecting rows. It compiles to a jar file.
I include this jar file in another app, DBUtilTests, wherein I create the database, specifying the database name, give it table names and column names for each table. When I get to the part where I insert rows and then do a select to verify the rows are there, nothing is returned.
In the select function in DBUtil, the cursor object is always null for some reason. I've tried creating it both of the following ways:
1:
String tableName="whatever";
//getColumnNamesForTable is a local function that returns the column names
// for a given table in an ArrayList of Strings
final ArrayList<String> columnNamesForTable = getColumnNamesForTable(tableName);
final String[] columns = columnNamesForTable.toArray(new String[columnNamesForTable.size()]);
SQLiteDatabase database = this.getReadableDatabase();
Cursor cursor = database.query(tableName, columns, null, null, "", "", "");
2:
String selectQuery = "SELECT * FROM " + tableName;
Cursor cursor = database.rawQuery(selectQuery, null);
Is there anything wrong in the above code, and if not, is what I'm trying to do possible?

Related

Android update SQLite table entry

I have a local SQLite Database in may App. I create and open the Database like this:
CookieClickerBase = getBaseContext().openOrCreateDatabase(CookieBase, MODE_PRIVATE, null);
CookieClickerBase.execSQL("CREATE TABLE IF NOT EXISTS cookiedata(what TEXT, data LONG)");
I insert some thin into the table link this:
CookieClickerBase.execSQL("INSERT INTO cookiedata VALUES ('Image','3')");
But now I wont to change the data from 3 to 9 in the table entry, where what = Image.
How can I do that?
THANKS!
You could use an UPDATE statement with execSQL():
CookieClickerBase.execSQL("UPDATE cookiedata SET data = 9 WHERE what ='Image'");
or use the recommended method which is update() with ContentValues:
ContentValues cv = new ContentValues();
cv.put("data", "9");
int rows = CookieClickerBase.update("cookiedata", cv, "what = ?", new String[] {"Image"});
The variable rows will contain the number of updated rows.

Retrieving Data from multiple tables from Database

I have some tables in a database. They have some particular pattern. For example, consider I have table employee, then some other table with same pattern like:
table 1:employee
table 2:employee_X
table 3:employee_Y
I want to check if these tables contain data or not and if they do then I have to call some method for each table. I am using following code to retrieve.
DatabaseMetaData meta = con.getMetaData();
ResultSet res = meta.getTables(null, null, "My_Table_Name", new String[] {"TABLE"});
while (res.next()) {
if(rs.getStrin(3).equals(employee)){
//my code to write data of this table to a file
}
if(rs.getString(3).equals(employee_X)){
//my code to write data to the same file
}
if(rs.getString(3).equals(employee_Y)){
//code to write data to the same file from this table
}
}
The code is working fine, but how I can retrieve data from all these tables at once instead of using three checks. If any of these table contains data I want to write it to my file. How I can perform this operation in less lines of code and efficiently?
It would be great if anyone can suggest way to check each of these table either contain data or not in a single statement and then I can call my code to write data to file.
You can use UNION statement in your complex query. Please, check example:
SELECT id, name FROM employee WHERE id = ?
UNION
SELECT id, name FROM employee_x WHERE id = ?
UNION
...
Also you can use UNION ALL statement instead of UNION. The main difference that UNION returns unique result set without duplicates, UNION ALL allows duplicates. Please, check this link https://www.w3schools.com/sql/sql_union.asp for detailed explanation about union statement.
If you need create UNION query with custom filtered tables, please check example:
Set<String> requiredTables = new HashSet<>();
// fill set with required tables for result query
requiredTables.add("employee");
ResultSet res = meta.getTables(null, null, "My_Table_Name",
new String[] {"TABLE"});
List<String> existentTables = new LinkedList<>();
while(res.next()) {
if (requiredTables.contains(res.getString(3)) {
existentTables.add(res.getString(3));
}
}
String query = existentTables.stream().map(table -> String.format("SELECT * FROM %s", table)).collect(Collectors.joinning(" UNION "));

Codename One SQL database storing wrong values

I am used to developing desktop applications with Java. Now I am trying Codename One to develop my first mobile app.
Trying to replicate my experiences with SQL databases I am running into a very odd storage behavior, which I cannot explain.
The database is created, but when I change the table input value, the new value gets ignored and just the old value is added. To save the new value, I have to delete the database.
I like the interface and any kind help would be appreciated.
Database db = Display.getInstance().openOrCreate("MyDB.db");
db.execute("CREATE TABLE IF NOT EXISTS Persons (Date NOT NULL,Event NOT NULL)");
String sql = "INSERT INTO Persons (DATE , Event) " + "VALUES ( 'John', '10000.00' );";
db.execute (sql);
// adds "John" to the database every time I click the button
// then I change the from "John" to "James"
// I am not adding the lines twice, just change the input
String sql = "INSERT INTO Persons (DATE , Event) " + "VALUES ( 'James', '10000.00' );";
db.execute (sql);
//keeps adding "John" to the database, even though value has been changed to "James"
Cursor cur = db.executeQuery("select * from Persons;");
Row currentRow= cur.getRow();
String dataText = currentRow.getString(0);
while (cur.next()) {
System.out.println(dataText);
}
You're not fetching the next row into dataText in your while() loop, so you're just repeatedly printing out the text from the first row.
It should be:
Cursor cur = db.executeQuery("select * from Persons;");
while (cur.next()) {
Row currentRow = cur.getRow();
String dataText = currentRow.getString("Date");
System.out.println(dataText);
}
If you examine the table with a separate query tool, like PhpMyAdmin, you should see that it contains both rows.
I hope I got the syntax right. I'm not a Java programmer and I got it from a tutorial.

How count the frequency of occurence of each value in a column in Table "A" and insert in a Table "B" using SQLitein an android app

I have a simple app that contains an Sqlite database containing 2 tables:
TABLE_CHAP that contains:
_id
Chapter_title
Number_of_flashcards
TABLE_Flash contains:
_id
Chap_id
flashcard content
I upload the content of the database to the assets folder, TABLE_FLASH contains a number of flashcards that belongs to each chapter.
What I'm trying to do is to count the frequency of Chap_id in TABLE_FLASH and insert this number to Number_of_flashcards in TABLE_CHAP and afterward display the number_of_flashcard in front of the concerned Chapter_Title.
the Number_of_flashcards is dynamic as the user may add his own flashcards to each chapter.
public void nberOfFlahcards(){
int xy= getChap_tableCount();
ContentValues contentValues = new ContentValues();
database = openHelper.getWritableDatabase();
for(int i=1; i<=xy; i++){
String countQuery = "SELECT * FROM TABLE_CHAP WHERE Chap_ID = " + i;
Cursor cursor = database.rawQuery(countQuery, null);
int total_count=cursor.getCount();
Log.v(TAG, "Nber of Flashcards for chapter"+i+"is: "+total_count);
contentValues.put(KEY_NBER_FLAHCARDS, Integer.toString(total_count));
database.update(TABLE_CHAP,contentValues, KEY_NBER_FLAHCARDS,null );
this code gave me always 0, please check where's the error and if you have better code or better architecture for the database please advise.
This update can be done with a single query
UPDATE TABLE_CHAP SET Number_of_flashcards =
(SELECT count(*)
FROM TABLE_Flash AS tf
WHERE tf.Chap_id=TABLE_CHAP._id)
But I'd better have a method int getNumberOfFlashcards(int chap_id) which computes the count for the given chap_id.

how to update a varchar in the sqlite database in java

I have a problem with to update a varchar in the sqlite database in java.
when I run this source, than I get a error.
I want String a to update to String b.
This is my source:
public void onClick (View v){
String a = "Test1";
String b = "Test2";
db = openOrCreateDatabase("MyDB", MODE_PRIVATE, null);
ContentValues values = new ContentValues();
values.put("Level1", b);
db.update("Game", values, a, null);
db.close();
}
And this is my Error:
Error updating Level1=Test2 using update Game SET Level1=? WHERE Test1.
can someone help me?
Thanks!
I'm not 100% sure what you are trying to achieve, however, you added a as a where clause and did not provide any arguments, so consequently you got the SQL statement shown in the error.
From the API:
public int update (String table, ContentValues values,
String whereClause, String[] whereArgs)
This one works ...
db = openOrCreateDatabase("MyDB", MODE_PRIVATE, null);
ContentValues values = new ContentValues();
values.put("Level1", b);
db.update("Game", values, "Level1=?", new String[] {a} );
db.close();
... if this is the resulting SQL you want to execute:
update Game SET Level1=? WHERE Level1 = 'Test1'
update Game SET Level1=? WHERE Test1.
Where Test1 is.. what? Where is the conditional part of your update statement. It's expecting something like:
update Game SET Level1=? WHERE ColumnName='Test1'
Taken from this website:
If the UPDATE statement does not have a WHERE clause, all rows in the table are modified by the UPDATE. Otherwise, the UPDATE affects only those rows for which the result of evaluating the WHERE clause expression as a boolean expression is true.
A String on it's own is in no way a boolean expression.

Categories