bracket not remove when with string formating why? - android

How to remove bracket around sstirng? I'm geting value from database save in arraystring when run database query its show bracket around value what do I do?
I want to remove bracket around stirng [AT] how to do that?
static ArrayList<String> Meal_groupid = new ArrayList<String>();
String formatedString = "[AT]"
.replace("[", "") //remove the right bracket
.replace("]", "");
Log.i("Formating Stirng",""+formatedString);
Meal_groupid.add(mCursor2.getString(mCursor2.getColumnIndex("meal_group_id"))
.replace("[", "").replace("]", ""));
Log.i("MEalGroup ID",""+Meal_groupid);
when see in logcat
in logcat Formating Stirng AT
MEalGroup ID [AT]
when I run query
Cursor mCursor = db.selectQuery("
SELECT m.menu_id, m.title AS menu_title
FROM uss_school_to_menu sm
LEFT JOIN uss_menu m on sm.menu_id = m.menu_id
LEFT JOIN uss_school s on s.school_id = sm.school_id
WHERE s.school_id = '"+ School_ID+"' AND sm.level_id = " +
SchoolLevelId + " AND m.meal_group_code = '"+Meal_groupid.toString()+"'" );
in database it looks like this
SELECT m.menu_id, m.title AS menu_title
FROM uss_school_to_menu sm
LEFT JOIN uss_menu m on sm.menu_id = m.menu_id
LEFT JOIN uss_school s on s.school_id = sm.school_id
WHERE s.school_id = '147' AND sm.level_id = 1 AND m.meal_group_code = '[AT]'
I want to remove bracket around [AT]

You are calling toString() on your ArrayList<String> to get the string out of it, which won't work. If you call toString() on an ArrayList<T>, you typically get an output of
"[" + get(0).toString() + " " + get(1).toString() + " " + get(2).toString() + etc + "]"
You have only one element, so it ends up looking like brackets were added around your string.
Do you really need an array list here? If so, you need to replace Meal_groupid.toString() with Meal_groupid.get(0), except 0 should be replaced with the index of whichever string in the list you need.
If you only need one string at a time, then avoid using the array list altogether, so you can directly plug the string into your database query.
You don't need .replace("[", "").replace("]", ""), because there are no brackets around your actual string.

Related

Variable passed to SQL statement returns nothing, no errors though

I'm passing a variable to an SQL query.
Dim accept As String
accept = Cursor1.GetString("accepted_id")
Msgbox(accept, "")
Cursor1 = SQL1.ExecQuery("SELECT answer FROM answers WHERE accepted_id =" & " 'accept' " )
There's more code but that should be enough. There are no errors and the msgbox shows the correct answer. it all looks good but it's not retrieving any results.
If I hardcode the answer instead of the variable it works, such as,
Dim accept As String
accept = Cursor1.GetString("accepted_id")
Msgbox(accept, "")
Cursor1 = SQL1.ExecQuery("SELECT answer FROM answers WHERE accepted_id =" & " 'CD6028' " )
The msgbox shows CD6028.
The results show show in a listview but nothing.
It seems like you are passing litteral string accept to the variable instead of variable accept itself.
Replace this :
Cursor1 = SQL1.ExecQuery("SELECT answer FROM answers WHERE accepted_id =" & " 'accept' " )
With :
Cursor1 = SQL1.ExecQuery("SELECT answer FROM answers WHERE accepted_id = '" & accept & "'")

How to update column only is its empty in sqlite?

I am using below query to update the column. Now what I want that I want to update these columns only when it is empty or null. How can I achieve this ?
db.execSQL("UPDATE FieldTestDataTemp SET
Image1 = '" + f10.image1 + "',
Image2 = '" + f10.image2 + "',
Image3 = '" + f10.image3 + "',
Image4 = '" + f10.image4 + "',
Image5 = '" + f10.image5 + "',
starRating = '" + starRating1 + "' ");
In mysql we used to use this query
UPDATE table
SET field = 'Your value'
WHERE field
IS NULL
OR LENGTH(field)=0
You have to set multiple query to set multiple column condition.
You can pass parameters like this to a common method that will return you the number of records updated
public int updateRecords(String table, ContentValues values,
String whereClause, String[] whereArgs) {
int a = db.update(table, values, whereClause, whereArgs);
return a;
}
and in this db is SQLiteDatabase object
private SQLiteDatabase db;
According to OP comment
I want to check this for every column in above query.
If I understand you correctly you want to update each column only if this column is empty. For this you need to run separate query for each column.
Sqlite has coalesce function that takes variable number of parameters and returns first not null.
UPDATE field UPDATE FieldTestDataTemp SET Image1 = coalesce(Image1, f10.image1)...
However - this not covers situation with empty fields so you need to carry about them (ex. set to null).
It's also good idea to use prepareStatement() / exec() instead of execSQL(). It allows to use placeholders instead of string concatenation.
You can do a single UPDATE and also check for null/empty:
UPDATE FieldTestDataTemp
SET Image1 = CASE WHEN Image1 IS NULL OR Image1 = ''
THEN f10.image1
ELSE Image1
END,
Image2 = CASE WHEN Image1 IS NULL OR Image2 = ''
THEN f10.image2
ELSE Image2,
...
But this will update every column in the UPDATE statement, even if the base 64 image string already be not null and not empty.
A possibly cleaner way to handle this would be to update each column separately. In this case, we can just add a WHERE clause to only update for empty/null image strings:
UPDATE FieldTestDataTemp
SET Image1 = f10.image1
WHERE COALESCE(Image1, '') <> ''

How to write SQL statement containing 2 conditions in android

I am trying to delete a row from my table if 2 columns equal to what the user entered.
E.g. I have 2 textfields in which the user entered something in both e.g. "chicken" and in the other textfield "car". I want to delete the row in which those 2 values are in a row. I think it will be something like: delete from ~tablename~ where food = chicken AND vehicle = car.
Im not sure how to write that in sqlite in android.
I have my SQLitedatabase object and have called the delete method on it, but not sure what to put in the parameters
EDIT = I've managed to do it. Thanks for the below answers but this is how I've done it:
sqlitedb.delete("Random", "food =? AND vehicle=? ", new String[]{tv.getText.toString(),tv1.getText.toString()});
tv and tv1 are textfields in my case. Random is my table's name.
The sql query will look like -
String sqlQuery = "DELETE FROM <table_name> WHERE food = '"+ <food_name> + "' AND vehicle = '" + <vehicle_name> + "'";
You want something like:
String table_name=~tablename~;
String table_column_one=food;
String table_column_two=vehicle;
database.delete(table_name,
table_column_one + " = ? AND " + table_column_two + " = ?",
new String[] {"chicken", "car"});
Check SQLiteDatabase's documentation on delete function for more info.
SQLite accepts conditionals in the WHERE clause as regular SQL.

Retrieving Data From SQLite Database

I am creating a user login application . I want to show account information of a user when he logs in in textviews of a layout . Here is the image of a layout .
Here is my code for getting data of a user when he logs in :
public Cursor getUserData(String username){
Cursor UserDataCursor = getReadableDatabase().rawQuery(
"SELECT * FROM " + USER_TABLE_NAME + " WHERE " +
USER_NAME + "='" + username+"'", null);
return UserDataCursor;
Here is the code for retrieving data with that class :
String email2 = cursor.getString(cursor.getColumnIndex("email"));
String name2 = cursor.getString(cursor.getColumnIndex("name"));
String pass2 = cursor.getString(cursor.getColumnIndex("pass"));
String gender2 = cursor.getString(cursor.getColumnIndex("gender"));
String date2 = cursor.getString(cursor.getColumnIndex("date"));
String country2 = cursor.getString(cursor.getColumnIndex("country"));
String reg2 = cursor.getString(cursor.getColumnIndex("reg"));
data+=email2+" "+name2+" "+pass2+" "+gender2+" "+date2+" "+country2+" "+reg2+"\n" ;
cursor.moveToNext();
}
It's giving a null pointer exception . What's the problem here ? How can i fix it ?
I think you're making things much harder for yourself by not using the database adapter pattern.
Take a look here for an example of how to set up more abstraction and error handling for your database:
http://www.devx.com/wireless/Article/40842/1954
It is difficult to verify your code, since it is data-dependent. Your column names could be wrong (or one could be missing). Your data type could be wrong. You might be getting a cursor back with NO rows, which you need to check for.
BTW, are you doing cursor.moveToFirst() before starting?
Also, we don't know what's on line 70, where the error occurred, because line numbers are lost in the posting.

SQLite order by 3 fields and return top 1 for each category

public Cursor fetchAllPBs() {
String sql = "SELECT * FROM " + CAPTURES_TABLE + " GROUP BY " + KEY_CAPTURES_SPECIES
+ " ORDER BY " + KEY_CAPTURES_POUNDS + " DESC, " + KEY_CAPTURES_OUNCES + " DESC, " + KEY_CAPTURES_DRAMS + " DESC;";
Cursor c = mDb.rawQuery(sql, null);
if(c != null) {
c.moveToFirst();
}
return c;
}
Hi,
I want the above query to return me the user's personal best for each species, that is, the heaviest item within each species. Testing it properly recently I've realised a problem. I'm still relatively new to SQL with this project...
Say I add a 'Chub' to my database of 7lb 6oz 0drms, then add another of 7lb 2oz 0drms - it will return the more recently added fish as the PB and not the biggest (the 7lb 2oz one). However if I then add another Chub of 8lb 0oz 0drms it will return the 8lb fish - it seems it's not properly ordering them by the Ounces and probably by that I assume the drams too.
Can anyone see what's wrong here and suggest a solution?
Many thanks
First, you need a subquery to determine the heaviest fish per species.
Second, your weight is split in 3 columns, so you need to add them in someway. I choose to just add them with multiplication, should be sufficient for getting the max.
SELECT *
FROM CAPTURES_TABLE AS C1
WHERE (100*Pounds+10*Ounces+Drams) =
(SELECT MAX(100*Pounds+10*Ounces+Drams)
FROM CAPTURES_TABLE AS C2
WHERE C2.SPECIES=C1.SPECIES)
ORDER BY pounds DESC, ounces DESC, drams DESC
More of a comment, but I need more space...
If I simplify your query it looks like:
SELECT * FROM table1 WHERE species = species_id
ORDER BY pounds DESC, ounces DESC, drams DESC LIMIT 1
Provided that species is not a unique field, the query is fine.
It looks like the problem is that when adding a new fish you are not adding, but actually replacing the fish, try and remove the limit 1 and see if all fish show up.
The ordering clauses are definitly correct.

Categories

Resources