I have a dialog that has 3 buttons (OK, Alterar, Delete) so when i click in Alterar it goes to another activity to alter the values, but i dont know the code to alter it.
I only know 2, which are .put/.insert and .delete .
Now what about alter?
2 rows: nome , telefone
Allright, this is an answer to your edit.
Let's say your table containing your rows has the name Person.
Now you want to change the phone number of the person "MrSmith" to 123456789.
First, enter the new values you want to change.
// Values to insert
ContentValues dataToInsert = new ContentValues();
dataToInsert.put("name", "MrSmith");
dataToInsert.put("phone", 123456789);
Maybe you dont need to put the name back in again, it was some time ago i did this. You can try out yourself :)
Now lets insert these into the database!
// We want to update the row where the name is "MrSmith"
String where = "id=?";
String[] whereArgs = { "MrSmith" };
The ? in where string is replaced with MrSmith when we do db.update(...).
Now SQL knows what row to update and what data it should update it with. Let's commit!
// Update table Person where the row name is "MrSmith" with the values entered
// in ContentValues!
db.update("Person", dataToInsert, where, whereArgs);
I hope this helps! Otherwise you need to check out how SQL Statements are done.
EDIT Function
public void editdata(int id,String name)
{
db.execSQL("update person set name='"+name+"' where id="+id);
}
Call function
editdata(id,"test");
Related
I have created a database in Sqlite Android Application, there are two fields in the table i.e Name and Email. I want to update the contents of the table, the query that i am using is.
db.update(TABLENAME,cv,"id=?",new String[]{String.valueOf(7)});
As this will update the content that have the ID 7, but i want to update the table by matching the name entered.
Add another Parameter like
db.update(TABLENAME,cv,"id=? AND Name=? ",new String[]{String.valueOf(7),NameValue});
Try
String where="id=? and Name=?";
db.update(TABLENAME,cv,where,new String[]{String.valueOf(7),NameValue});
To match the name instead of the ID, just replace the column name in the whereClause:
db.update(TABLENAME, cv, "Name=?", new String[]{"PanKush"});
pass your string array in update method...
public int Upadte(String name_value,String email_value,String new_name) {
ContentValues value = new ContentValues();
value.put("name",new_name);
return _sqliteDB.update(TABLE_NAME ,value," NAME "+"=?"+" and "+" EMAIL "+"=?",new String[]{name_value,email_value});
}
Using SQLite Database, I have a table with 6 columns in each row as the rows are added. The first column is the name of the "person." I have it so when you click on the person in a listview, it brings up a screen with 5 edit texts. You fill them out and submit it and it adds it to another row in the database.
To retrieve that data later on, I am trying to use SELECT by the name to get it, but cannot figure out how this works.
public Cursor getChildRulesInformation(DatabaseOperations dop, String name) {
dop.getReadableDatabase().execSQL("SELECT * FROM "+CHILD_RULES_TABLE_NAME+" WHERE "+CHILD_NAME + "=\""+ name+"\"");
}
What do I do with that to retreive every column inside of that specific row. I am confused on the process to get it out.
Any lead in the write direction would be greatly appreciated. Thanks. If you need any more information please let me know.
Try this,
public Cursor getChildRulesInformation(DatabaseOperations dop, String name) {
return dop.getReadableDatabase().rawQuery("SELECT * FROM "+CHILD_RULES_TABLE_NAME+" WHERE "+CHILD_NAME+" = '"+ name+"' ", null);}
Do not use execSql for getting data, that is only for sending data to the database. Instead, use rawQuery if you want to use the String. So it would be:
public Cursor getChildRulesInformation(DatabaseOperations dop, String name) {
return dop.getReadableDatabase().rawQuery("SELECT * FROM "+CHILD_RULES_TABLE_NAME+" WHERE "+CHILD_NAME + "='"+ name+"'", null);
}
This will return you the cursor object that you are looking for.
I designing a custom ListView ,which has more child view
I have ideas about sorting the ListViewdata in "Asc" or "Desc" order ,that retrieves data directly from database , but in my case I used CustomSimpleCursorAdapter , I requires to sort data in TextView depending upon the values that is:
today
tomorrow
more than 2 days i.e; 354
CustomSimpleCursorAdapter .java
//Days remaining for BirthDay
String year=cursor.getString(cursor.getColumnIndex(BirthdayProvider.EVENT_YEAR));
String month=cursor.getString(cursor.getColumnIndex(BirthdayProvider.EVENT_MONTH));
String date=cursor.getString(cursor.getColumnIndex(BirthdayProvider.EVENT_DATE));
String remainingDays=BirthdayCalculation.getDaysRemainingForNextBirthDay(year, month, date);
Calendar today=Calendar.getInstance();
int CMonth=(today.get(Calendar.MONDAY)+1);
int CDate=(today.get(Calendar.DAY_OF_MONTH));
//checking whether the BD is on TODAY
if (remainingDays.equals("1") && (CDate==Integer.parseInt(date) && (CMonth)==Integer.parseInt(month))) {
viewHolder.txtDaysRemainigValue.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
viewHolder.txtDaysRemainigValue.setTypeface(fontRoboto_Regular);
viewHolder.txtDaysRemainigValue.setTextColor(Color.parseColor("#00CC33"));
remainingDays="today";
}
//checking whether the BD is on TOMORROW
else if (remainingDays.equals("1")) {
viewHolder.txtDaysRemainigValue.setTextSize(TypedValue.COMPLEX_UNIT_SP, 17);
viewHolder.txtDaysRemainigValue.setTextColor(Color.parseColor("#FF0099"));
remainingDays="tomorrow";
viewHolder.txtDaysRemainigValue.setTypeface(fontRoboto_Regular);
}
//checking how many days remaining BD
else{
remainingDays=BirthdayCalculation.getDaysRemainingForNextBirthDay(year, month, date);
viewHolder.txtDaysRemainigValue.setTextSize(TypedValue.COMPLEX_UNIT_SP, 27);
viewHolder.txtDaysRemainigValue.setTextColor(Color.parseColor("#990000"));
}
Here's Screen Shot link
When you query your database, you should use an "order by" clause. For example, this method takes the order by clause as the last argument. I don't know how you store your dates and times in your database, but if it's something SQLite can recognize and provide sorting on, then it should work. The following will query for all columns on a table named "table" with no where clause, no "group by" clause, no "having" clause, and order by the time column descending (use ASC for ascending if you want that instead):
database.query("table", null, null, null, null, null, "time DESC");
EDIT
If you can't store the exact data you want (in this case days remaining until an event), I can only see two options:
1). After getting the cursor, you iterate over the results and compose a new sorted list. You could make some kind of model object in java, read the values into it from the cursor, and sort them with a comparator function. At that point you probably would not use a CursorAdapter any more. It's quite easy to build your own ListAdapter - I recommend you watch The World of Listview
2). Since the query methods take strings, you can actually compose more complicated queries so that SQLite provides you the data you DO want (and still sort it for you as well). If your times are stored as longs, you could do something like this:
long currentTime = System.currentTimeMillis();
String timeAsString = Long.toString(currentTime);
String remainingTimeColumn = "(time_column - " + timeAsString + ") AS remaining_time";
// compose query
String table = "table";
String[] columns = new String[] {"column1", "column2", ..., "columnN", remainingTimeColumn};
String order = "remaining_time ASC";
// query
Cursor cursor = database.query(table, columns, null, null, null, null, order);
// later, get remaining time from cursor row
long remainingTime = cursor.getLong(cursor.getColumnIndex("remaining_time"));
In this case "time_column" is the name of the column that stores the event time. What this is doing is creating an additional column with the name "remaining_time", which is calculated from one of the actual column values. The results are then sorted by that synthesized column. The cursor you get back will contain this column and these values, you just need to have the proper column name to access them.
Since I don't know the details of your data format, I can't say this is exactly how your query should look, but the idea should be clear. You can work out the finer details from here...
If you get the data in database, you can use ASC or DESC and put ArrayList.
another way is you can use Collections.sort(). but you must data class implements comparable and overriding compare method.
I want to delete a specific row in SQLITE data in android.Now, I already try only using only one column data like primary key but now I want to delete an entire row using a column key and column name .How will I do this?help me
Below is the syntax I made to delete, but their nothing happen?
DatabaseHandler.java
public Cursor delete(String id, String name){
SQLiteDatabase data=this.getWritableDatabase();
String selectQuery = "DELETE FROM Criteria WHERE criteria_eventpk ="+"'"+id+"' AND criteria_eventpk ="+"'"+name+"'" ;
Cursor idupdate = data.rawQuery(selectQuery, null);
data.close();
return idupdate;
I use rawQuery because I try db.delete but only one data is only allowed.So I try rawQuery .
Next, the codes in the button delete in my MainActivity
evcri_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
db.delete(evpk.getText().toString(), cripk.getText().toString());
}
});
I think I made a wrong choice to choose cursor, Can anyone help me?I guess a custom query is needed but I need your help.Help me..
I try this ,but still it doesn't work.In their any wrong code I use?
public void delete(Criteria cri, Criteria pk){
SQLiteDatabase data=this.getWritableDatabase();
data.delete(TABLE_CRITERIA,"criteria_name=? AND criteria_eventpk=?", new String[]{String.valueOf(cri.get_criname()),String.valueOf(pk.get_eventpk())});
data.close();
In my delete button
db.delete(evpk.getText().toString(), cripk.getText().toString());
But when I try this code below, it works but only the id is given,I want the given are id and name..
data.delete(TABLE_CRITERIA,"criteria_name=?, new String[]{String.valueOf(cri.get_criname())});
I use rawQuery because I try db.delete but only one data is only allowed.So I try rawQuery .
This information is not correct. The db.delete method allows multiple parameters:
public int delete(String id, String name){
SQLiteDatabase data = this.getWritableDatabase();
String table = "Criteria";
String whereClause = "criteria_eventpk=? AND criteria_eventpk =?" ;
String whereArgs[] = new String[] {id, name};
int count = data.delete(table, whereClause, whereArgs);
data.close();
return count;
}
Try this - I put the single quotes inside the double quotes and it always works for me
String selectQuery = "DELETE FROM Criteria WHERE criteria_eventpk ='"+id+"' AND criteria_eventpk ='"+name+"'" ;
Your statement is of the form:
DELETE FROM Criteria WHERE criteria_eventpk = /id/ AND criteria_eventpk = /name/
So criteria_eventpk has to equal both the value of id and the value of name. That will only be the case where id and name are the same which I imagine is not usually going to be the case?
Did you want to delete where criteria_eventpk is equal to either id or name? If so change the AND to OR. Or do you mean to check two different columns in the row? In which case one of the criteria_eventpk's needs changing.
I would like to create a FIFO table in order to save only the most 50 recent infomations by deleting the oldest elements when a new infomation arrives. I can do it by manipulating ID in the table but I don't think it is the best solution. Any idea of doing it well?
Instead of checking for date time, sorting your items, and whatnot, you can just assume that the first row in your table is the last to be inserted.
In your Content Provider's insert(Uri uri, ContentValues cv), before doing your db.insert call, you can first query the number of items on that table using getCount() and delete the first row if count>50. Then proceed with your insert call.
You dont need to play with IDs in order to create a FIFO logic. The best would be to add another column as DATETIME in your table which automatically inserts current time-stamp that will help you to select records in ascending order with respect to this column. Your new column should be something like:
DateAdded DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
Make sure when ever you insert new record, you must do a COUNT check of total records in this table and if necessary delete the oldest record with respect to DateAdded. Moreover, you can make use of LIMIT and/or MAX in your select-query when it comes to delete the oldest record.
Add a datetime type column to your table if it doesn't contain it yet and set it to 'now' on each insert. Then on each insert select all with limit set to 50 sorted by date. Choose the last item and run a delete query to delete everything older than this last item.
is it must to use sqlite? can you use file handling? you can use simple Queue object and save it to file.
Here is what I did for a list of transactions, and it works okay. When inserting a new entry I check if the count is above 50, if so, I just delete the very last entry:
// Adding new transaction
public void addTransaction(Transaction transaction) {
SQLiteDatabase db = this.getWritableDatabase();
if(getTransactionsCount() > 50){
List<Transaction> allTransactions = getAllTransactions();
Transaction oldestTransaction = allTransactions.get(allTransactions.size()-1);
deleteTransaction(oldestTransaction);
}
ContentValues values = new ContentValues();
values.put(KEY_TRANSACTION_UID, transaction.getUID());
values.put(KEY_TRANSACTION_AMOUNT, transaction.getAmount());
values.put(KEY_TRANSACTION_IS_ADD, transaction.getIsAdd());
// Inserting Row
db.insert(TABLE_TRANSACTIONS, null, values);
db.close(); // Closing database connection
}
And getAllTransactions() returns the list in descending order (based on the id primary key):
// Getting All Transactions
public List<Transaction> getAllTransactions() {
List<Transaction> transactionList = new ArrayList<Transaction>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_TRANSACTIONS + " ORDER BY " + KEY_TRANSACTION_ID + " DESC";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Transaction transaction = new Transaction();
transaction.setID(Integer.parseInt(cursor.getString(0)));
transaction.setUID(cursor.getString(1));
transaction.setAmount(cursor.getString(2));
transaction.setIsAdd(cursor.getString(3));
// Adding contact to list
transactionList.add(transaction);
} while (cursor.moveToNext());
}
// return contact list
return transactionList;
}