How do I hide null values from being printed? I have one Products table which has 5 columns. ID, Dairy, Fruit, Vegetables, Grains, and Protein.
When I search for dairy it brings up null values. Whats the best way to hide it?
public String dbToStringDairy() {
SQLiteDatabase db = getWritableDatabase();
String dbStringDairy = "";
String query = "SELECT * FROM " + TABLE_NAME + " WHERE 1";
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex(COLUMN_ID)) != null) {
dbStringDairy += " ";
dbStringDairy += c.getString(c.getColumnIndex(COLUMN_PRODUCT_DAIRY));
dbStringDairy += "\n";
}
c.moveToNext();
}
db.close();
return dbStringDairy;
}
The Simplest way to return something else instead of null, using an if else statement to check if the return result is null or not, if it is null store something else so that the program wont return and print null.
Here some simple example:
public String dbToStringDairy()
{
SQLiteDatabase db = getWritableDatabase();
String dbStringDairy = "";
String query = "SELECT * FROM " + TABLE_NAME + " WHERE 1";
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while(!c.isAfterLast())
{
if(c.getString(c.getColumnIndex(COLUMN_ID))!=null)
{
dbStringDairy += " ";
dbStringDairy += c.getString(c.getColumnIndex(COLUMN_PRODUCT_DAIRY));
dbStringDairy += "\n";
}
c.moveToNext();
}
db.close();
//Replace the `null` into other useful information
if(dbStringDairy==null){
dbStringDairy="No Results";
}
return dbStringDairy;
}
There are a lot of way to ensure your program won't print out null value. This method perform in the dbToStringDairy(), there is also way to do it during your Print Implementation.
Anywhere, hope this simple solution could help.
Related
I have an SQL method here. I would like to return the data in a String[] array.
How do I do that exactly?
Thank you!
public String[] getLikedSongs() {
SQLiteDatabase db = this.getReadableDatabase();
String[] LikeSong;
Cursor cursor = db.rawQuery(" SELECT " + COL_4 + " FROM " + Table_Name + " WHERE " + COL_4 + " IS NOT NULL", null);
while (cursor.moveToNext()) {
String note = cursor.getString(0);
}
cursor.close();
db.close();
return LikeSong;
}
You must define the array's length and this can be done only after the Cursor fetches all the rows. Then set its length to the nimber of rows of the Cursor.
Then inside the while loop set the items of the array:
public String[] getLikedSongs() {
String[] LikeSong = null;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT " + COL_4 + " FROM " + Table_Name + " WHERE " + COL_4 + " IS NOT NULL", null);
if (cursor.getCount() > 0) {
LikeSong = new String[cursor.getCount()];
int i = 0;
while (cursor.moveToNext()) {
LikeSong[i] = cursor.getString(0);
i++;
}
}
cursor.close();
db.close();
return LikeSong;
}
I'm trying to query a database for the count of entries that match the given ID, but I can't come up with a working solution.
There are two of each type of account that correspond to the userID of 1, for some reason the first method outputs "1" and the second "0". I can show the mainactivity and the database shchema if needed as well.
public int numberOfDebitAccounts(int userID){
int numOf_accs = 0;
String query = "select count(*) from debitAccount where userID = '" +userID+"'";
openDatabase();
Cursor cursor = db.rawQuery(query,null);
if(cursor.moveToFirst()) {
numOf_accs = cursor.getInt(0);
System.out.println("Number of debit accs: " + numOf_accs);
}
cursor.close();
closeDatabase();
return numOf_accs;
}
public int numberOfCreditAccounts(int userID){
int numOf_accs = 0;
String query = "select count(accountID) from creditAccount where userID = '" +userID+"'";
openDatabase();
Cursor cursor = db.rawQuery(query,null);
if(cursor.moveToFirst()) {
numOf_accs = cursor.getInt(0);
System.out.println("number of credit accounts: " + numOf_accs);
}
closeDatabase();
return numOf_accs;
}
hi i m fetching the all entries of today date i write the query for that but i did not get the correct entries. please solve my issue .below i write my code.thank you.
public ArrayList<groups> fetchByTodayDate(){
String selectQuery = "SELECT * FROM " + DatabaseHelper.TABLE + " WHERE "+ DatabaseHelper.DATETIME + "<=date('now')";
Cursor cursor = database.rawQuery(selectQuery,null);
ArrayList<groups> all = new ArrayList<groups>();
if (cursor != null && cursor.moveToFirst()) {
do {
groups data = new groups();
smsdata.setMsgtext(cursor.getString(cursor.getColumnIndex(DatabaseHelper.TEXTMSG)));
smsdata.setSmsId(cursor.getString(cursor.getColumnIndex(DatabaseHelper._ID)));
all.add(data);
} while (cursor.moveToNext());
}
cursor.close();
return all;
}
("SELECT * FROM " + table_name + " WHERE " + KEY_DATE + "='" + date + "'", null);
Try this solution for today's entries:-
String selectQuery = "SELECT * FROM " + DatabaseHelper.TABLE + " WHERE date(datetime("+ DatabaseHelper.DATETIME+"/1000, 'unixepoch','localtime'))=date('now')";
Try this
public ArrayList<groups> fetchByTodayDate()
{
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<groups> all = new ArrayList<>();
String selectQuery = "SELECT * FROM " + DatabaseHelper.TABLE;
Cursor cursor = db.rawQuery(selectQuery,null);
cursor.moveToFirst ();
while (!cursor.isAfterLast())
{
all.add(new groups (
cursor.getString(cursor.getColumnIndex(DatabaseHelper.TEXTMSG)),
cursor.getString(cursor.getColumnIndex(DatabaseHelper._ID))
));
cursor.moveToNext ();
}
cursor.close();
db.close();
return all;
}
I want to check columns (not value) at agregasi table, if columns exist do something, but if columns does not exist show/print message 'Column does not exist'.
I could run code below while columns exist:
String keywords1={'pesawat','terbang'};
String sql1 = "SELECT " + keywords + " FROM agregasi"; //columns exist at agregasi table
Cursor c1 = myDbHelper.rawQuery(sql1, null);
if (c1.moveToFirst()) {
// i can do something (no problem)
}
But i have problem when columns name i change on purpose (to check). What should i do to print error message (in android/java way)?
**String keywords2={'psawat','terang'};**
String sql2 = "SELECT " + keywords + " FROM agregasi"; //columns does not exist at table
Cursor c2 = myDbHelper.rawQuery(sql2, null);
// what should i do get error message and show/print using toast
You're looking for getColumnIndex(String columnName).
int index = c2.getColumnIndex("someColumnName");
if (index == -1) {
// Column doesn't exist
} else {
...
}
Here's a general method you can use to check whether a particular column exists in a particular table:
public boolean isColumnExists(SQLiteDatabase sqliteDatabase,
String tableName,
String columnToFind) {
Cursor cursor = null;
try {
cursor = sqLiteDatabase.rawQuery(
"PRAGMA table_info(" + tableName + ")",
null
);
int nameColumnIndex = cursor.getColumnIndexOrThrow("name");
while (cursor.moveToNext()) {
String name = cursor.getString(nameColumnIndex);
if (name.equals(columnToFind)) {
return true;
}
}
return false;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
Try this it works fine :)
Cursor res = db.rawQuery("PRAGMA table_info("+tableName+")",null);
int value = res.getColumnIndex(fieldName);
I am trying to make a simple login System. And This is the coed in database class. Is my Method correct? It should return true if both username and password are correct and false if either one of them is wrong or not in the database(not registered)? Is there any simpler way to code this method?
public boolean getAccount(String name, String password) {
int test = 0;
database = getReadableDatabase();
String sql = "SELECT * FROM tbl_account WHERE username='name' AND password='password'";
Cursor c = database.rawQuery(sql, null);
if (c.moveToFirst()) {
do {
if (c.getString(0).isEmpty()) {
test = 0;
}
else if (c.getString(0).isEmpty() == false) {
if (name.equals(c.getString(0))) {
if (c.getString(1).isEmpty()) {
test = 0;
}
else if (password.equals(c.getString(1))) {
test = 1;
}
}
}
} while (c.moveToNext());
}
if (test == 0) {
return false;
} else {
return true;
}
}
Best practice is to use ? placeholders with selection arguments where you can:
String sql = "SELECT * FROM tbl_account WHERE username = ? AND password = ?";
Cursor c = database.rawQuery(sql, new String[] {name, password});
This avoids problems where the arguments themselves contain characters such as quotes and apostophes that could otherwise break your constructed SQL string.
I think your sql should be:
String sql = "SELECT * FROM tbl_account WHERE username='" + name +
"' AND password='" + password + "'";
try this sql. hope it will help.