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.
Related
I have a Person object that I store in a SQLite database.
Person has Age, FirstName, and LastName.
At a given moment, I want to find the youngest person (lowest Age).
How can I do this?
So far I have this:
public Person getYoungest(Cursor c) {
c.moveToFirst();
db.rawQuery("SELECT MIN(" + AGE + ") FROM " + PERSON_TABLE, null);
// Person youngestPerson = ???
// return youngestPerson;
}
However, I'm really confused at what the "rawQuery" does. It doesn't return a person object. Also, I'm not sure whether the query gives me the lowest "age", or the record containing the lowest "age" (which is what I want). I'm very new to SQL, so this is all strange to me.
Any advice?
What you are currently doing is querying for smallest age value from your dataset. If you want to get the whole data row of such you need to use ORDER BY, like
SELECT * FROM ... ORDER BY age ASC LIMIT 1
which would sort the data by Age in ascending order. As you want just one we use LIMIT to ensure this is going that way (and to make things faster), yet note that most likely many records may have the same age (incl. lowest value) so you may extend ORDER BY to fine tune sorting.
SQLite returns strings, numbers, byte arrays.
They are not like java-objects. You have to retrieve your each value and initialize your person in the code using a constructor.
Or use realm database that easily helps to store java-objects using sqlite.
do not forget to improve the performance by using
SELECT * FROM ... LIMIT 1
like Marcin Orlowski said.
to retrieve the data use this:
if (c.moveToFirst()) {
int idColIndex = c.getColumnIndex("id");
int nameColIndex = c.getColumnIndex("name");
int emailColIndex = c.getColumnIndex("email");
int id = c.getInt(idColIndex)
String name = c.getString(nameColIndex)
String email = c.getString(emailColIndex)
to create an object use this:
new Person(<your values>);
db.rawQuery ==> return a Cursor which point to the returned data from select statement so you should make
Cursor cursor = db.rawQuery("SELECT * FROM PERSON_TABLE ORDER BY age ASC , null);
if(cursor.moveToFirst()) //mean find data and point to the samllest
cursor.getString(c.getColumnIndex("field_name"));
this is my query
SELECT *
FROM articles
WHERE id >1
ORDER BY id ASC
LIMIT 1
my requirement is very simple. I just want to select only one record and bind to textViews . This is what I had done so far.
public Article oneRecord()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery("SELECT * FROM articles WHERE id=3;", null);
if(c.moveToFirst()){
Article a= new Article();
a.setId(c.getString(c.getColumnIndex("id")));
a.setImage_url(c.getString(c.getColumnIndex("image_url")));
a.setTitle(c.getString(c.getColumnIndex("title")));
a.setBody(c.getString(c.getColumnIndex("body")));
}
return a;
}
I am not sure I have understood you problem correctly or not. However there is not special thing to do. Just update TextView after getting article from database.
Article a = getOneRecordFromDB();
titleView.setText(a.getTitle());
bodyView.setText(a.getBody());
This is my method to delete a row from the database where appointment_date is equal to a date that was passed in
public void deleteAllAppointments(String date) {
SQLiteDatabase db = this.getWritableDatabase();
String deleteAllQuery = "DELETE FROM " + TABLE_APPOINTMENTS + " WHERE appointment_date = '" + date + "'";
db.rawQuery(deleteAllQuery, null);
Log.d("Query: ", deleteAllQuery);
}
I then use it like this
//Database (DatabaseHandler is the one that contains all database methods)
final DatabaseHandler database = new DatabaseHandler(this);
//This happens when button is clicked, it is tested an executes with every chick,
//#param selectedDate is a string like "18/03/2014"
database.deleteAllAppointments(selectedDate);
It executes and query looks like this
DELETE FROM appointments WHERE appointment_date = '18/03/2014'
However row with appointment_date = '18/03/2014' is not deleted.
I'm sure database is set up correctly as I have working methods with it and all information is received from there in correct format.
NOTE: Adding "*" to "DELETE * FROM..." returns a fatal syntax error.
rawQuery() just compiles the SQL but does not run it. To actually run it, use either execSQL() or call one of the moveTo...() methods on the cursor returned by rawQuery().
For further info, see What is the correct way to do inserts/updates/deletes in Android SQLiteDatabase using a query string?
For tasks such as insert or delete there are really great "convenience methods" like the [delete method](http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#delete(java.lang.String, java.lang.String, java.lang.String[])) already built in to the database.
public int delete (String table, String whereClause, String[] whereArgs)
As to why your current approach would fail, it could be something as simple the format of the column you're trying to delete not matching (e.g. you have created the table as a date value and not a string).
In any case, using the built in delete method is easier because it will notify you when it fails by returning the number of rows affected by the delete. rawQuery just returns a cursor, which you would then have to get the result from to see if it worked.
Are you sure your data value is in European format of day/month/year ala your query value of 18/03/2014 and maybe its not US style of month/day/year: 03/18/2014.
Not trying to be US-centric but that was my first thought.
Otherwise, definitely look at SQLiteDatabase.delete:
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#delete(java.lang.String, java.lang.String, java.lang.String[])
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 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");