Check whether the column in SQLite NULL or not NULL - java

I have two tables, one is Info and another is WorkDetails.
Table Info: ID(PK), Name, Weather, Date, Status, TimeIn_Info, TimeOut_Info
Table WorkDetails: ID(PK),Project,WorkDescription,Per,TimeIn,TimeOut // 4 row
For the row in WorkDetails, only the row that has value will be inserted. Otherwise, it will not be inserted. Next, the TimeOut_Info in the table Info will used to get the value of TimeOut in the table WorkDetails. It will search from the fourth row, check whether there exists TimeOut value. If not, it will check the third and so on. If TimeOut value found in third row, it will insert the TimeOut value into Table info and will not check for second and first. Same goes to the TimeIn_info, the difference is TimeIn_info start searching from first row, not the fourth row.
Button btn1=(Button)findViewById(R.id.button2);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
AlertDialog.Builder builder=new AlertDialog.Builder(WorkDetailsTable.this);
builder.setTitle("Data Saved");
builder.setMessage("Are you sure you want to save?");
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int ii) {
W1 = txtWork1.getText().toString();
W2 = txtWork2.getText().toString();
W3 = txtWork3.getText().toString();
W4 = txtWork4.getText().toString();
a1 = spinnerTra.getSelectedItem().toString();
a2 = spinnerTra2.getSelectedItem().toString();
a3 = spinnerTra3.getSelectedItem().toString();
a4 = spinnerTra4.getSelectedItem().toString();
P1 = per1.getText().toString();
P2 = per2.getText().toString();
P3 = per3.getText().toString();
P4 = per4.getText().toString();
// long ab = ts.insertTimeSheet(name, weather, date, status);
// long cf= WF.insertWorkForce(subContractors, noPeople, noHours,ab);
if ((TextUtils.isEmpty(W4)) && (TextUtils.isEmpty(P4)) && (TextUtils.isEmpty(h)) && (TextUtils.isEmpty(i))) {
checkRow3(W3, P3, f, g);// check row 3;
checkRow2(W2, P2, d, e1);//check row 2;
checkRow1(W1, P1, b, c);
}
else if (!(TextUtils.isEmpty(i)))
{
WD.insertWorkDetails(a4, W4, P4, h, i);
database = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(MyDatabaseHelper.TimeOut_Info, i);
database.insert(MyDatabaseHelper.TABLE_INFO, null, values);
checkRow3(W3, P3, f, g);// check row 3;
checkRow2(W2, P2, d, e1);//check row 2;
checkRow1(W1, P1, b, c);
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int ii) {
dialog.dismiss();
}
});
builder.show();
}
});
}
public void checkRow3(String a, String b, String c, String d) {
if ((TextUtils.isEmpty(a)) && (TextUtils.isEmpty(b)) && (TextUtils.isEmpty(c)) && (TextUtils.isEmpty(d))) {
}
else if ((!(TextUtils.isEmpty(a)))||(!(TextUtils.isEmpty(b)))||(!(TextUtils.isEmpty(c)))&&((TextUtils.isEmpty(d)))) {
WD.insertWorkDetails(a3, a, b, c, d);
}
else if ((!(TextUtils.isEmpty(a)))||(!(TextUtils.isEmpty(b)))||(!(TextUtils.isEmpty(c)))&&(!(TextUtils.isEmpty(d))))
{
WD.insertWorkDetails(a3, a, b, c, d);
database = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(MyDatabaseHelper.TimeIn_Info, d);
database.insert(MyDatabaseHelper.TABLE_INFO, null, values);
}
return;
}
public void checkRow2(String a, String b, String c, String d)
{
if ((TextUtils.isEmpty(a)) && (TextUtils.isEmpty(b)) && (TextUtils.isEmpty(c)) && (TextUtils.isEmpty(d)))
{
return ;
}
else
{
WD.insertWorkDetails(a2, a, b, c, d);
}
return;
}
public void checkRow1(String a, String b, String c, String d)
{
WD.insertWorkDetails(a1, a, b, c, d);
database = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(MyDatabaseHelper.TimeIn_Info, c);
database.insert(MyDatabaseHelper.TABLE_INFO, null, values);
return;
}
As you can see my code is a little bit confusing. Does it has any method that can search whether the column (TimeOut_info) already has a value?
How can I check whether the column is NULL or NOT NULL? If it is NULL, then TimeOut value will be inserted into TimeOut_Info, otherwise it will not! How can I achieve this?
When I attempt to use this method to check whether the specific column contains value or not, but I get rawQyery cannot be solved.
public void checkRow2(String a, String b, String c, String d)
{
if ((TextUtils.isEmpty(a)) && (TextUtils.isEmpty(b)) && (TextUtils.isEmpty(c)) && (TextUtils.isEmpty(d)))
{
}
else if ((!(TextUtils.isEmpty(a)))||(!(TextUtils.isEmpty(b)))||(!(TextUtils.isEmpty(c)))&&((TextUtils.isEmpty(d)))) {
WD.insertWorkDetails(a3, a, b, c, d);
}
else if ((!(TextUtils.isEmpty(a)))||(!(TextUtils.isEmpty(b)))||(!(TextUtils.isEmpty(c)))||(!(TextUtils.isEmpty(d))))
{
database = dbHelper.getWritableDatabase();
//Cursor mCursor=db.rawQuery("SELECT TimeOut_Info FROM "+MyDatabaseHelper.TABLE_INFO+"WHERE"+MyDatabaseHelper.TimeOut_Info+"=' "+d+"'");
Cursor mCursor = database.rawQuery("SELECT TimeOut_Info FROM " + MyDatabaseHelper.TABLE_INFO + " WHERE " +MyDatabaseHelper.TimeOut_Info + "= '" + d + "'");
if(c==null)
{
}
}
return;
}
Any suggestions? Thanks

There is no overloaded method of rawQuery which takes one parameter.
Change
Cursor mCursor = database.rawQuery("SELECT TimeOut_Info FROM " + MyDatabaseHelper.TABLE_INFO + " WHERE " +MyDatabaseHelper.TimeOut_Info + "= '" + d + "'");
with
Cursor mCursor = database.rawQuery("SELECT TimeOut_Info FROM " + MyDatabaseHelper.TABLE_INFO + " WHERE " +
MyDatabaseHelper.TimeOut_Info + "= '" + d + "'" , null);
you are already providing the selectionArgs, hardcoded in your query. Passing null should be ok in your case. Have a look here

Related

IndexOutOfBoundException when i pass arraylist to DBHelper to update database (Android SQlite)

I am new at android and trying to make managing members app with database. what i want to do here is that when user buys any drink it should change drinks name to "bought" in database, but when i pass Arraylist to db class it shows that my Arraylist is empty.
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at com.shashank.managemembers.DB_Controller.update_available(DB_Controller.java:88)
at com.shashank.managemembers.TempActivity$2.onClick(TempActivity.java:90)
userInputActivity
here user selects drink he/she wants and when he presses done button it should change database with drinks name.
And I'm checking it with Toast message that ArrayList is not empty. Toast message always appears with user's choice but db class throws error.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TempActivity.this, selectedInListView.get(0), Toast.LENGTH_SHORT).show();
dbController.update_available(code, selectedInListView);
onBackPressed();
}
});
here selectedInListView has many items when i am passing it to dbController.update_available.
dbController.java
here I have 9 columns in db starting from DRINK1 to DRINK9.
public void update_available(String memberCode, ArrayList<String> BoughtDrinks) {
Cursor cursor = this.getReadableDatabase().rawQuery("SELECT * FROM MEMBERS WHERE MEMBERCODE = '" + memberCode + "'", null);
int count = cursor.getColumnCount();
while (cursor.moveToNext()) {
for (int i = 5; i < count; i++) {
if (!cursor.getString(i).contains(BoughtDrinks.get(0))) {
this.getReadableDatabase().execSQL("UPDATE MEMBERS SET DRINK"+ i +"='Bought' WHERE DRINK" + i +"='" + BoughtDrinks.get(0) + "'" + "AND MEMBERCODE='" + memberCode + "'");
if(BoughtDrinks.size() > 0 ){
BoughtDrinks.remove(0);
}
}
}
}
cursor.close();
}
I am not understanding why it is throwing an error when I'm passing ArrayList with elements.
You got this error because ,if BoughtDrinks.size()>0 ,your code remove item at 0 then for loop get item at 0.So when you try to get item at 0 after you removed all the item ,you will get index IndexOutOfBoundsException.to avoid that just add if() condition.
public void update_available(String memberCode, ArrayList<String> BoughtDrinks) {
Cursor cursor = this.getReadableDatabase().rawQuery("SELECT * FROM MEMBERS WHERE MEMBERCODE = '" + memberCode + "'", null);
int count = cursor.getColumnCount();
while (cursor.moveToNext()) {
for (int i = 5; i < count; i++) {
if ( BoughtDrinks.size()>0 && !cursor.getString(i).contains(BoughtDrinks.get(0))) {
this.getReadableDatabase().execSQL("UPDATE MEMBERS SET DRINK"+ i +"='Bought' WHERE DRINK" + i +"='" + BoughtDrinks.get(0) + "'" + "AND MEMBERCODE='" + memberCode + "'");
if(BoughtDrinks.size() > 0 ){
BoughtDrinks.remove(0);
}
}
}
}
cursor.close();
}

Android currently index from the arrayList try to update

ArrayList < Titles > atitlename;
ArrayList < Items > aitems;
static int currentListIndex = 0, currentItemIndex = 0;
public void onClick(View button)
{
switch (button.getId())
case R.id.button_update: {
int id = aitems.get(currentListIndex).getItemId();
String newContent = etupdateName.getText().toString();
etupdateName.setText("");
ContentValues values = new ContentValues();
values.put(DBManager.C_ITEM_NAME, newContent);
try {
database = manager.getWritableDatabase();
database.update(DBManager.TABLE_ITEMS, values, DBManager.C_ID + "=" + id, null);
Toast.makeText(this, "you saved: " + newContent, Toast.LENGTH_LONG).show();
database.close();
refreshitem();
} catch (Exception e) {
Log.d(TAG, "Error" + e);
Toast.makeText(this, "error" + e, Toast.LENGTH_LONG).show();
}
break;
}
#Override
public void onItemClick(AdapterView << ? > parent, View view, int position, long id) {
String name = (aitems.get(position).getItemName());
etupdateName.setText(name);
}
try to get the currentListindex from the ArrayList to the id, I set the currentListIndex = 0, cause I don't know how to get the current index, I got the int from the OnItemClick because it passes the int Position from the method, But i can't pass the int Position from the Onclick method.
I want the id = whatever I Click the item from the listview.
When I click the Item in the listview where id = 2, and I try to update it, it always updates the item where index = 0(becasue i set the currentItemIndex= 0).
what I want is to update the item's id = whatever I click the item from the listview which I have done it by using the int Position from the OnItemClick method.
Example:
I click the item from the listview where id = 3, it displays the item name in the EditText Box, then I want to update the item name, it will update the item name where id =3.

text field in jTable something better than ActionPerformed(java.awt.event.ActionEvent evt)!

hi guys hope you all well.. to day i have a question again i am using a text field in jTable to edit a column and i use
model.getValueAt(); from a column and model.setValueAt(); to another column after doing some calculations fanaly when i press enter key the action replays but sometimes does not reply and does not update changing so i have to press again... my code looks something like this:
private void txt_ActionPerformed(java.awt.event.ActionEvent evt){
try {
int viewRow = table.getSelectedRow();
String id = (table.getModel().getValueAt(viewRow, 1).toString());
String sql1 = "SELECT * FROM mydb.mytable_1 where ID1='"+id1+"'";
dm.pst = dm.c.prepareStatement(sql1);
dm.rs = dm.pst.executeQuery();
if (dm.rs.next()) {
float a = dm.rs.getFloat("mycolumn_1");
float b = Float.parseFloat(model.getValueAt(viewRow, model.getColumnCount()-10).toString());
float c = Float.parseFloat(model.getValueAt(viewRow, model.getColumnCount()-9).toString());
String d = model.getValueAt(viewRow, model.getColumnCount()-8).toString();
float e = 0;
switch (d) {
case "U":case "1":e = 0;break;
case "W":case "2":e = 7;break;
case "X":case "3":e = 10;break;
case "Y":case "4":e = 14;break;
case "Z":case "5":e = 20;break;
default:System.err.println("Error..");break;
}
if(b>a){
JOptionPane.showMessageDialog(null, "B is Bigger than A..!!");
}else if(a>=b){
float val_1 = a-b
float val_2 = b * c;
float val_3 = b * (((e / 100) + 1) * c);
model.setValueAt(val_3, viewRow, model.getColumnCount()-6);
model.setValueAt(val_2, viewRow, model.getColumnCount()-7);
model.setValueAt(val_1, viewRow, model.getColumnCount()-11);
String id2 = (table.getModel().getValueAt(viewRow, 0).toString());
String upid = "update mydb.mytable_2 set mycolumn_2='" + b + "'where ID2='" + id2 + "'";
dm.pst = dm.c.prepareStatement(upid);
dm.pst.execute();
}
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
anything else better than action performed?
Note: after i edited my code i would say that i am using JTextField txt_ = new JTextField(); as an editor for my column and i am using model = new DefaultTableModel()
thank in advance
i am using a text field in jTable to edit a column and i use model.getValueAt(); from a column and model.setValueAt(); to another column
Don't use an ActionListener.
Your logic should be defined in your TableModel
#Override
public void setValueAt(Object value, int row, int column)
{
super.setValueAt(...);
if (column == ?)
// add logic here to do calculation and update other column value
}

Sorting SQLite table with "ORDER BY" - Android

I have a SQLite db for my highscores table. Currently I am having trouble checking if the new score makes the highscores and also sorting the highscores table.
When the game is over, Results.java is called.
Results.java
total_score = dh.calculateTotalScore(score, percentage);
low_score = dh.check(score, percentage, total_score);
if(total_score > low_score) {
dh.delete(10);
dh.insert(score, percentage, total_score);
} else {
dh.insert(score, percentage, 9999999);
}
dh.sort();
All the methods being called in Results.java are coming from DatabaseHelper.java.
DatabaseHelper.java
public void sort() {
db.rawQuery("SELECT * FROM " + DB_TABLE + " ORDER BY " + TOTAL_SCORE, null);
}
public long calculateTotalScore(long score, int percentage) {
long i;
return i = (percentage * 1000) + score;
}
public long check(long score, int percentage, long sum) {
Cursor c = db.rawQuery("SELECT " + TOTAL_SCORE + " FROM " + DB_TABLE, null);
long count = c.getCount();
long low_score;
if(count == 10) {
c.moveToLast();
low_score = c.getInt(c.getColumnIndex(TOTAL_SCORE));
return low_score;
} else {
return count;
}
}
public long insert(long score, int percentage, long total_score) {
ContentValues values = new ContentValues();
values.put(SCORE, score);
values.put(PERCENTAGE, percentage);
values.put(TOTAL_SCORE, total_score);
return db.insert(DB_TABLE, null, values);
}
public void delete(int row) {
db.delete(DB_TABLE, RANK + "=" + row, null);
}
The output for TOTAL_SCORE is being displayed as follows:
1
2
40851
1
2
40804
60811
60811
50816
What I desire is for the output to be in numerical order. Like this:
1
1
2
2
40804
40851
50816
60811
60811
The order they are in above is (I think) just the order they were inserted into the db. No errors happen when the program runs and the program does not crash. More code can be provided if needed.
SELECT does not modify anything; your sort function has no effect.
(The rawQuery function returns the sorted list of records, but you ignore it.)
You have to put the ORDER BY clause into the query that is used to display the scores.

Can I make SQLiteDatabase complain about missing parameters?

Recently, I've had a few bugs because of code like this:
Cursor myCursor = myDb.rawQuery(
"SELECT ... " +
" FROM ...complicated join... " +
" WHERE field1 = ? AND (field2 = ? OR field3 = ?) ",
new String[] {myField1, myField2}); // Oops, forgot about field3
When this happens, the query just silently ignores the missing parameter, causing bugs to go unnoticed. Is there some pedantic setting or anything else that I can use to make SQLite scream (at run-time) when the number of placeholders and the number of fields do not match?
I know that I could build my own wrapper, but I'm wondering if there's something built-in...
Android is basically just passing the args unchecked to native sqlite, see http://www.sqlite.org/c3ref/bind_blob.html
If something is not bound it is simply considered to be bound to NULL. Binding too much should result in an error though
I don't know of / have not seen any debug option in Android's source for that kind of checks but you could probably write some code that checks your sql syntax:
SQLiteChecker mDbChecked = new SQLiteChecker(mDb);
Cursor c = mDbChecked.rawQuery("select complicated from table where stuff=?",
new String[] {"one", "two"});
where SQLiteChecker would be something along the lines of
/**
* Simple Delegate for SQLiteDatabase
*/
public class SQLiteChecker {
private final SQLiteDatabase mDbDelegate;
public SQLiteChecker(SQLiteDatabase db) {
mDbDelegate = db;
}
// ------------ Delegate methods --------------------//
public int delete(String table, String whereClause, String[] whereArgs) {
checkSQL(whereClause, whereArgs);
return mDbDelegate.delete(table, whereClause, whereArgs);
}
public int update(String table, ContentValues values, String whereClause, String[] whereArgs) {
checkSQL(whereClause, whereArgs);
return mDbDelegate.update(table, values, whereClause, whereArgs);
}
public void execSQL(String sql, Object[] bindArgs) throws SQLException {
checkSQL(sql, bindArgs);
mDbDelegate.execSQL(sql, bindArgs);
}
public Cursor rawQuery(String sql, String[] selectionArgs) {
checkSQL(sql, selectionArgs);
return mDbDelegate.rawQuery(sql, selectionArgs);
}
// add more if you need
// -------------- checking logic -------------------//
private static void checkSQL(String query, Object[] args) {
// bit unreliable but simple:
// just check if amount of ? matches args.length
int expected = countChar(query, '?');
int actual = args != null ? args.length : 0;
if (expected != actual) {
Log.e("CHECK", "You seem to have messed up [" + query + "]");
Log.e("CHECK", "expected:" + expected + " actual:" + actual);
}
}
private static int countChar(String string, char ch) {
if (string == null) return 0;
int count = 0;
for (int i = 0; i < string.length(); i++) {
if (string.charAt(i) == ch)
count++;
}
return count;
}
}

Categories

Resources