I want to make a memo which was dated, I input the date with activities in a separate place from the calendar. How do I display all events in the calendar according to the date that I fed?
public List<Foto> getAllFotoList() {
List<Foto> fotoList = new ArrayList<Foto>();
String query_tb_foto = "SELECT * FROM " + TABLE_FOTO;
// SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query_tb_foto, null);
if (cursor.moveToFirst()) {
do {
// Siswa siswa = new Siswa(cursor.getString(0),
// cursor.getString(1));
Foto foto = new Foto(cursor.getString(cursor
.getColumnIndexOrThrow("COL_JUDULFT")),
cursor.getString(cursor
.getColumnIndexOrThrow("COL_IMG")),
cursor.getString(cursor
.getColumnIndexOrThrow("COL_DESFT")),
cursor.getString(cursor
.getColumnIndexOrThrow("COL_STARTDATEFT")),
cursor.getString(cursor
.getColumnIndexOrThrow("COL_STARTTIMEFT")),
cursor.getString(cursor
.getColumnIndexOrThrow("COL_ENDDATEFT")),
cursor.getString(cursor
.getColumnIndexOrThrow("COL_ULANGFT")),
cursor.getString(cursor
.getColumnIndexOrThrow("COL_ALARMFT")));
fotoList.add(foto);
} while (cursor.moveToNext());
return fotoList;
}
return null;
}
Is this true? Thanks for respons.
You need to use something like SELECT * FROM some_table WHERE date('1990-01-01'); (Just insert your custom date). This should return all of the results from your table with the same date value. See this post for further explanation and the SQLite documentation to see what else you can do with dates.
Two answer your second question, using a ListView should be fine. I personally use an ArrayList to populate my ListViews for SQLite results since queries return an arbitrary number of results. An ArrayList makes it easy to store and access those results.
did you sore the date as a GMTTIMESTAMP?
if so
String Q= "SELECT * FROM "+TABLE_FOTO +" ORDER BY GMTTIMESTAMP DESC;";
will put all the rows of the data with the most recent at the front.
or you could reference it by your primary key?
I was always told to make sure you remember to put a semicolon in side the brackets or your leave yourself open to SQL injections.
and you always want to check for null cursors so you should also have
if(cursor!=null&&cursor.moveToFirst()){}
Related
I have setup an application which currently can lookup an input id with one on the database to then give a single result. E.g. user enters id = 1 , database contains a record with an id of 1 then returns the name or number etc...
Now I want to improve the system slightly by querying my database with an arraylist which contains a range of id's e.g. 3, 456, 731 etc... which I want my database to search for. I have also grouped multiple values to certain id's for example the database might search for an id of 3 it will then find 5 results I want it to return the telephone number of each one of those results into another arraylist which I can print to the logs.
I hope I have explained this enough, but please ask questions if you require more information.
The code below demonstrates the modified version of the query used to gain a single result, but I cannot see what I'm doing wrong to gain multiple results.
Activity....
// New array list which is going to be used to store values from the database
ArrayList<String> contactsList;
// This arrayList has been received from another activity and contains my id's
ArrayList<String> contacts = intent.getStringArrayListExtra("groupCode");
// The database which i'm using
ContactDBHandler contactDBHandler = new ContactDBHandler(getApplicationContext(), null, null, 1);
//getAllValues is used to pass my arraylist id's to the database.
contactsList = contactDBHandler.GetAllValues(contacts);
// Simple log statement to loop and display results
for (int i = 0; i < contactsList.size(); i++){
Log.i("Numbers", contactsList.get(i));
}
ContactDBHandler
Query
// I'm telling it to get the contact number from the contact_list
// when the groupcode matches the code recieved.
public ArrayList<String> GetAllValues(ArrayList groupCode)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null;
String alarmName = "";
ArrayList<String> list = new ArrayList<>();
cursor = db.rawQuery("SELECT contact_number FROM contact_list WHERE grp_code=?", new String[]{groupCode+ ""});
if (cursor.moveToFirst())
{
do
{
list.add(cursor.getString(0));
}
while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed())
{
cursor.close();
}
return list;
}
Thanks
Can you see where I have gone wrong?
Try this:
cursor = db.rawQuery("SELECT contact_number FROM contact_list WHERE grp_code IN (" + TextUtils.join(",", Collections.nCopies(groupCode.size(), "?")) + ")", groupCode.toArray(new String[groupCode.size()]));
Your current code fails to pass the list in the sql-format: = does only support single values, for lists you have to use IN.
Your code would result in a query like this:
SELECT contact_number FROM contact_list WHERE grp_code=["some_id","other_id"]
But what you need (and my code produces) is:
SELECT contact_number FROM contact_list WHERE grp_code IN ('some_id','other_id')
References:
SQL query to find rows with at least one of the specified values
WHERE IN clause in Android sqlite?
IN clause and placeholders
https://developer.android.com/reference/android/text/TextUtils.html#join(java.lang.CharSequence,%20java.lang.Iterable)
You cannot pass an ArrayList to an SQLQuery. To check for multiple values in the same field you have to use the 'in' keyword.
Ex:
SELECT * FROM `table1` where column in ( 'element1', 'element2', 'element3')
In your case,
String str = "";
for(String s: groupCode){
str = str+","+"\'"+s+"\'";
}
//to remove the extra ' in the begining
str = str.substring(1);
return str;
cursor = db.rawQuery("SELECT contact_number FROM contact_list WHERE grp_code IN (?)", new String[]{str});
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());
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 have large number of strings, approximately 15,000 that I stored in a SQLite database using the following code:
void addKey(String key, String value, String table) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_KEY, key); // Contact Name
values.put(KEY_VALUE, value); // Contact Phone
// Inserting Row
db.insert(table, null, values);
db.close(); // Closing database connection
}
And then i search through that database using the following method in order to pick out any strings that match the key im looking for:
public String searchKeyString(String key, String table){
String rtn = "";
Log.d("searchKeyString",table);
// Select All Query
String selectQuery = "SELECT * FROM " + table;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Log.d("searchKeyString","searching");
if(cursor.getString(1).equals(key))
rtn = rtn + "," + cursor.getString(2);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
Log.d("searchKeyString","finish search");
return rtn;
}
The goal is to do this in real time as the user is typing on the keep board so response time is key and the way it stands now it takes over a second to run through the search.
I considered reading all of the items into an array list initially and sorting through that which might be faster, but i thought an array list of that size might cause memory issues. What is the best way to search through these entries in my database?
A couple of things you can do...
Change the return to a StringBuilder until the end.
Only use a readable version of the database (that's probably not making much difference though)
Do not get a new instance of the database every time, keep it opened until you don't need it anymore
Query for only what you need with the "WHERE" argument in the SQL query.
See the code below with some changes:
// move this somewhere else in your Activity or such
SQLiteDatabase db = this.getReadableDatabase();
public String searchKeyString(String key, String table){
StringBuilder rtn = new StringBuilder();
Log.d("searchKeyString",table);
// Select All Query
String selectQuery = "SELECT * FROM " + table + " WHERE KEY_KEY=?";
Cursor cursor = db.rawQuery(selectQuery, new String[] {key});
// you can change it to
// db.rawQuery("SELECT * FROM "+table+" WHERE KEY_KEY LIKE ?", new String[] {key+"%"});
// if you want to get everything starting with that key value
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Log.d("searchKeyString","searching");
rtn.append(",").append(cursor.getString(2));
} while (cursor.moveToNext());
}
cursor.close();
Log.d("searchKeyString","finish search");
return rtn.toString();
}
Note even if you want this to happen in "real-time" for the user, you will still need to move this to a separate Thread or ASyncTask or you are going to run into problems....
You should consider using SELECT * FROM your-table LIMIT 50, for example. And you can put two buttons "Back", "Next" on your view. If every page has max 50 items, the user is at page 1, and he taps "Next", then you can use this query:
SELECT * FROM your-table LIMIT 50 OFFSET 50
If your table contains most of text-data, and you want to integrate search deeply into your app, consider using virtual table with FTS.
Let sqlite do the hard lifting.
First off, add an index to the field you're searching for, if you don't have one already. Secondly, don't do a SELECT all with manual table scan, but rather use a query in the form
SELECT column_value
FROM my_table
WHERE column_key LIKE "ABC%"
This returns the least amount of data, and the sql engine uses the index.
i dunno about better but maybe it'd be faster to make queries for the selected strings one by one.
public String searchKeyString(String key, String table){
String rtn = "";
Log.d("searchKeyString",table);
// Select All Query
String selectQuery = "SELECT * FROM " + table + "WHERE column_1 = " + key;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
rtn = rtn + "," + cursor.getString(2);
}
cursor.close();
db.close();
Log.d("searchKeyString","finish search");
return rtn;
}
EDIT:
Well i dunno how those custom keyboard apps do it, but those AutoCompleteTextViews are hooked up to adapters. you could just as easily make a cursorAdapter and hook your auto-complete view to it.
http://www.outofwhatbox.com/blog/2010/11/android-autocompletetextview-sqlite-and-dependent-fields/
http://www.opgenorth.net/blog/2011/09/06/using-autocompletetextview-and-simplecursoradapter-2/
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;
}