Delete row in sqlite database - android

I have a sqlite database which store different multiple user's data. I wanted to ask how to delete specific row in the database? I'm not really familiar with database type of stuff. Currently I have a delete function that used to delete one of the user's information in the database. But I'm not really sure how to delete the entire row. (I got emailid, first & last name and ssid in my database. )
public void delete_user(String ssid) {
Log.i(TAG,"delete_user ssid["+ssid+"]...");
String[] valuesWhere = new String[1];
valuesWhere[0] = ssid;
this.getWritableDatabase().delete("user", "ssid=?", valuesWhere);
}
Should I declare every value that I wanted to delete? I wanted to know whether is there another way that able to delete specific row of data. Any comments will be appreciated.

Should I declare every value that I wanted to delete? I wanted to know whether is there another way that able to delete specific row of data.
Your current code will delete every row that matches the ssid passed to delete_user(ssid). If ssid is a unique column (no duplicate values) it will delete one row at most.
But I'm not really sure how to delete the entire row.
Understand that SQLiteDatabase#delete() will never partially delete a row.

Related

SQLite id row not following sequential order after deleting rows

I am trying to make a notes taking app and the way I wrote app to delete specific row is in this way -
FIRST - If a user taps on any cardView from a recyclerView, first activity will forwards cardView position using getAdapterPosition().
SECOND - Second activity receives cardView`s positon, to delete a specific row from SQLite database, I called a method known as 'totalNotes()' which will return total number of rows present in SQLite database. Finally, to delete the row I subtract the number received from 'totalNotes()' method with the getAdapterPosition().
PROBLEM - They way I have programmed it only works if the rows in the database are in sequential order. However, when a user wants to delete a row number 3 and 2 from 5 rows, the remaning rows are 1,4 and 5. How can make the database so auto implement sequential order after row deletion?
I have looked on 'almost' similar problem on the site but they fail when I try to implement in my code. I am new to Android development.
[Demo Picture][2]
How can I assign sequential IDs?
How my app looks like
You should not base on the row number sequential. Almost(if not all) all databases have the same behavior on auto-increment field. When you get data from database you need to get also the ID, and to keep the ID inside the APP so when deleting from DB you will delete base on that ID:
id = note.noteID; /// Selected note (noteID) to be deleted.
--------
dbHandler!!.deleteNote(id);
---------
// Here you bind your note to your viewHolder
fun bindItems(note: UserNotes) {
noteTitle.text = note.noteTitle
noteText.text = note.noteText
noteText.noteId = note.noteID;
}
Using sequential Ids is bad, because when you delete a record with Id = 5, the next record you add to your table is not going to be Id = 5 as well, it's going to be Id = 6, so it's going to cause you problems sooner or later.
The way #Simion suggested is:
You ask for all the data, (i.e. all your notes)
When you select a note you ask for the Id of that note, and save it in a variable.
If the user decides to delete that note you should do deleteNote(noteId), that way you can use anything you want as an Id and you don't rely on the Ids being sequential (which is, as I said before, usually a bad idea)

Search in sqlite database by criterias selected with checkbox

I have in my app a database with two tables : country and rights. Long story short, the db tells me whether a right (there is 10 rights in total) is legal or not in a specific country.
Now, I want the user to be able to search in my db by criterias. I have a layout with checkbox. If the user check a box, it mean he want to see every country in where the right is legal. For exemple, if he check the box "criteria1" and "criteria6", the user want the list of every country where criteria1 and criteria6 are legal, but we don't care wether the other rights are legal or not.
I asigned values to the checkboxs (1 if legal, 0 if illegal, just like in my db) and passes all of them to the activity who display the result of the search.
My problem is, I can't figure out how to search in my database. I need to only get the country where where the selected criters are equal to 1, but I don't know how to formulate my sql request (since I never know which criterias are going to be checked or not). My request need to only be about the criterias who has the value 1.
I had the idea of sending all my values to a function (witch returns a cursor) where I excecute a select statement if the value is equal to one, but I don't know how I could join all the result of my selects in a cursor. I also thought about using "CASE WHEN..." but it doesn't seem to work.
Does anyone have a clue on how I could deal with my search ?
If you need precisions on my problem, please ask.
This guy here (https://www.youtube.com/watch?v=NGRV2qY9ZiU&list=PL200JxfhYIgCrrpH4rCz-uNfBTb5sng1e) has the right idea.
The clip may be a bit slow but it does exactly what you want.
He creates a custom string based on if checkbox is checked and removes it from the string if unchecked.
To get what you want, you need to do a couple of things.
First, create a table with countries as rows, and rights as columns. Add 1 for right is present in country and 0 if not. Get this into an sqlite database (eg import via csv in DB browser for SQLite, free software; don't forget to create the android_metadata table in the sqlite database - search online for this). Import the database in the app (there is plenty of documentation for this online).
Second, change the text inputed in the if/else checkbox part of the script (he writes fruit names, you write for ex. "right1 = 1", or the exact query the checkbox should do on the column right1).
You also need to pay attention to the selection.add and selection.remove (know that selection is an array list which will store all your criteria for search by column).
Third, you need to change the content of his finalSelection (View view).
Delete all he has written and just create two strings:
String final1 = android.text.TextUtils.join(" or ", selection);
String final2 = "select country from table where " + final1;
The string final2 is your key for a cursor with a rawQuery. Just create a cursor in the database and pass the key to it. This can be done easily.
PS the method android.text.TextUtils.join() is amazing :)
You can place the operator of choice there.
If you need more than one operator (and, or etc), you can create different ArrayLists which you fill in the if/else checkbox is filled and join later in the finalSelection.
Oh, btw, if you have too many checkboxes, you will get a warning in the XML file (layout has more than 80 views is bad for performance).
In order to get around that, you need to get to know grid views a bit better. After reading a few tutorials on the basic use of GridViews, a good start for checkboxes inside them is here.
It may seem like a lot, but you need to learn to use holders to get information out of the getView of the modified BaseAdapter.
If you want to understand it better, follow the arrPath.
It is a String[] filled with all the paths of images found inside the cursor (string values from the dataColumnIndex, which contains paths of images).
Within the onClick() listener of the Button, from the arrPath he extracts only the rows of the cursor that were selected by checkbox click (thumbnailsselection[i] is a boolean - with a value TRUE/FALSE for each row in the cursor).
The selected paths are placed in the selectImages String, separated by OR.

Update the database table with the same button that is used to insert

I have a really different situation. I have a form where user fills the data and insert into database. Now in the same form, I need to update his data also. Something like, there is a search user autocomplete text view. When user finds him then the data from database directly fills all the form fields. Now, either he submits data with the same info, if his info has not changed or, if the info has changed, he changes only some of the fields and then press the same button(submit) to update his data. I am doing so because I need to register the user in different particular session. He can register many times with same data. But when his some of the data is changed, I need to update his data but with registering him in the session with new id.
I do not want to provide you my codes here, I just need some technical help, how can I achieve the solution of this problem? If I am not wrong, I am thinking to use TextWatcher. I can implement textwatcher in each edittext form. When the text is changed, somehow the button(submit) that is used to insert get some connection with textwatcher, that it should update the database instead insert.
I am not sure if I am right. Help me please if you have some easy and reliable method to do. Thanks!!
You must have created a method in the Activity or a method in a separate class(I would prefer a separate class for database related methods). And you must keep some registration id or something which should match every time.
Suppose the registration id is named as ID. When you are inserting the data check within that insert method whether this ID matches with any previous records or not. If it matches then do update instead of insert.
Something like:
SQLiteDatabase objSqliteDB = DatabaseHelper.openDataBase();
objSqliteDB.beginTransaction();
SQLiteStatement stmtRecCount = objSqliteDB.compileStatement("select count(*) from ID where ID =?");
stmtRecCount.bindString(1, ID);
long count = stmtRecCount.simpleQueryForLong();
if(count != 0)
{
stmtUpdate.bindString(1, Name);
. . .
stmtUpdate.execute();
}
else
{
stmtInsert.bindString(1, Name);
. . .
stmtInsert.executeInsert();
}
Add whatever other fields you need to update
stmtInsert
&
stmtUpdate
will be yourinsert and update query

Validate for empty row in Android

I have a table in which 5 rows are there. But I have to feed the value of row in the database in which values are filled. It can be 2nd, 3rd or all. So how would I find out and validate the same. The rows are not generating dynamically. The rows are already in layout with some ids. I know it's weird but requirement is this only. Please suggest me how can I do this.
For that you have some alternative,
I think you should insert default record into the field so that will be easy instead of validating, if you think that is good.
When get the result from the DB just put the single condition
String name = Db.get_name().toString();
if(name!=null)
{
Row_TextView.setText(name);
}
else
{
Row_TextView.setText("-"); // or what ever you want to set
}
- Here is database example
Try it i hope it works for you
What you need is a Cursor to read data from the db
Then loop through the fetched data (if 'getCount()>0' then while(!cursor.isAfterLast))
For each row check if the data is present in specific columns in your db and if not then do insert it in the db

Managing a sqlite database using activity list

Ok, I have a database with id column as timestamp
I made an activity list from the db.
I want to manage the db (delete rows) using the list, but the thing is I don't want to
View the whole timestamp, in every row I'll put only the time with some info and
I want to group the list ,as in contacts grouped by alphabet, by the date.
First, how can I make group in an activity list? (Making groups to the output list not the db)
Second, what is the best way to implement this? When user chooses an item and confims delete
I should delete it from the db but I have only patial timestamp...
(My only link to the db is the timestamp - I don't actually know where to store it in the list and I don't want to put it as a string in the text view, do a substring to get it back - is there another way to do this?)
I tried to search tthe web for some examples but I only found a simple ones.
Thnx :-)
?
I think what you're trying to do is create a database of tasks identified by a timestamp. You probably don't want to use a timestamp as a unique ID for the row. Instead, use an integer and qualify it as "PRIMARY KEY" when you create the database.
group the list? I'm not sure why you want to do this in the structure of the database. It's more common to group the list in the output, and leave the db itself in as flat a structure as possible.
Retrieve the primary key when you display a list of tasks. When the user clicks a task, use the primary key to choose the task to delete. You don't have to display the primary key; it serves as a behind-the-scenes "link" between the displayed info and the db row.
http://www.vogella.com/articles/AndroidListView/article.html
I should use cursor adapter for managing db.
And this one for grouping a list:
http://code.google.com/p/android-amazing-listview/
Thnx for the efforts

Categories

Resources