working with custom views and sqlite database-android - android

I m working on password manager app.
in which I have created database with one table.
table_name : entry
fileds : id, title, category, username, password, website, comment.
And the main activity contains views for above fields.
but now I want to add a button called "add filed" through which user can add new view like one more username , or edittext for any other custom entry.
But the problem is...
How can I save those custom entries into database? Because, there may be a possibility that user want to add one custom entry for first password. and two custom entries for second password. so how can I manage those extra custom records into database.
plz help..

Use Alter Table query to add new field in table.
For ex.,
if (!isColumnExistInTableOrNot("entry", "username2" )) {
db.execSQL("ALTER TABLE entry ADD COLUMN username2 varchar");
}
the isColumnExistInTableOrNot() is.
public static boolean isColumnExistInTableOrNot(SQLiteDatabase db,String tableName,
String ColumnName) {
String Query = "select " + ColumnName + " from " + tableName;
try {
Cursor c = db.rawQuery(Query, null);
if (c != null) {
return true;
}
} catch (SQLiteException e) {
return false;
}
return false;
}

Related

Android SQLite add duplicate item

I am working on sqllite. I've created the database successfully, and I can add new items to it.
// Adding new contact
public void Add_Contact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_Tittle, contact.getTitle()); // Contact title
values.put(KEY_Description, contact.getDescription()); // Contact
// description
values.put(KEY_Price, contact.getPrice()); // Contact price
values.put(KEY_Image, contact.getImage()); // Contact image
values.put(KEY_Counter, contact.getCounter()); // Contact counter
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
Log.e("Table Result isss", String.valueOf(values));
db.close(); // Closing database connection
}
This code working perfect, now I want to check if I can also save the same information, for example, if I first save "Hello Android" and in a second time try to save the same information, I want to show for example: Toast message or other.
First make a function like this:
public boolean somethingExists(String x) {
Cursor cursor = database.rawQuery("select 1 from " + TABLE_CONTACTS + " where KEY_Tittle like '%" + x
+ "%'", null);
boolean exists = (cursor.getCount() > 0);
cursor.close();
return exists;
}
And then before every insert call this funcition to return if it exists or not like this:
if (!somethingExists("hello world")) {
//HERE DO INSERTION if it is not already in Table e.g like call AddContact function here for insertion etc
} else {
//Display Toast message here "Record already exists"
}
p.s i just wanted to highlight the logic - your actual table names, schema & logic might be different. Anyways, try this - it should work. The actually working is supposed to follow all database constraints, structure and schema of your design.

SQLite Android Delete database row

I want to delete a row in the sqlite data base. Please refer to the sql datastructure and my current delete method which is not working.
private static final String[] TABLE_MESSAGE_FIELDS = {
FIELD_USERNAME, "CHAR(32) NOT NULL",
FIELD_READED, "INTEGER(1) NOT NULL",
FIELD_SEND, "INTEGER(1) NOT NULL",
FIELD_TIMESTAMP, "INTEGER(64) NOT NULL",
FIELD_CONTENT, "TEXT NOT NULL",
};
//more tables
private static final String[] TABLE_MESSAGE_INDEXS = {
FIELD_USERNAME, FIELD_READED,
};
This is the structure, basically it is an instant messenger (IM) android app, so the user can send and receive message. While the operations like receiving message etc are working, the option to delete is not.
I am looking to delete the whole conversation between a user, in other words not the individual message in a conversation, but the whole conversation itself. I guess the right way is to find out the user name, and delete the entire row. The table TABLE_MESSAGE_FIELDS is contains the 5 columns indicating the message, I want to delete that entire conversation.
This is how I go about it
public boolean deleteMessage(String userName)
{
SQLiteDatabase database = mLocalDatabase.getWritableDatabase();
final String[] COLUMNS = { FIELD_TIMESTAMP, FIELD_CONTENT };
final String SELECTION = FIELD_USERNAME + "=?" ;
//database.beginTransaction();//do i need this?
boolean result= database.delete(TABLE_MESSAGE,SELECTION,new String[]{userName})>=0;
//database.endTransaction();//??
database.close();
return result;
}
Assuming you have correctly declared create query and everything works, your code looks correct so reason why your row(s) are not deleted from database may be that you provided wrong username i.e. each row in database not equal with given userName. Try to print your variable before perform delete action.
Then, you mentioned transaction. If you used it, you need to call
setTransactionSuccessful()
or your changes will be rolled back and database will be back to state before transaction.
boolean result = false;
db.beginTransaction();
result = db.delete(TABLE_MESSAGE, SELECTION, new String[] {userName}) > 0;
db.setTransactionSuccessful();
db.endTransaction();
public boolean deleteMessage(String userName) {
boolean result = false;
if (userName != null && !userName.equals("")) {
userName = userName.trim();
SQLiteDatabase database = mLocalDatabase.getWritableDatabase();
// final String[] COLUMNS = { FIELD_TIMESTAMP, FIELD_CONTENT };
// final String SELECTION = FIELD_USERNAME + "=?" ;
// database.beginTransaction();//do i need this?
String whereCondition = FIELD_USERNAME + "=" + userName;
result = database.delete(TABLE_MESSAGE, whereCondition, null);
// database.endTransaction();//??
database.close();
}
return result;
}

Fastest way to search through strings stored in sqlite database

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/

Android Sqlite query detect when an element doesn't exists in the table

How can I detect when an element doesn't exist in my table? I need because I want to update/insert contacts on it. My problem it's that I want to insert a new contact by using ContentObserver but this element is called multiple times and I'm selecting the last element. So when i insert a new contact, I select the last element, I'm trying to identify if exists on the db and insert it.
use a boolean value to check whether the contact exist or not
boolean contact = myDbHelper.checkidExitsorNot(ur table name,row name , value);
public boolean checkidExitsorNot(String tablename, String rowname, String id) {
String queryf = "select * from " + tablename + " where " + rowname + "='" + Integer.valueOf(id) + "'";
Cursor c = myDataBase.rawQuery(queryf, null);
if (c.getCount() == 0) {
c.close();
return true;
}else {
c.close();
return false;
}
}
if the return is true then it does not exist if false it exist
You can check by using count(*) function in database.

How can I attach a SQLite ID to a Spinner object in android?

I want to pull a couple columns from a database and add those to the spinner, but I want the _id of the row to be hidden in there somewhere too. Take partial sample code below for example:
public void fillProfileSpinner()
{
String query = "SELECT _id,fruit_type,weight,colour FROM fruits;";
SQLiteDatabase profileDatabase = fruitCakes.database.getReadableDatabase();
Cursor cursor = profileDatabase.rawQuery(query, null);
startManagingCursor(cursor);
try {
cursor.moveToFirst();
do
{
String fruitType = cursor.getString(cursor.getColumnIndex("fruit_type"));
double weight = cursor.getString(cursor.getColumnIndex("weight"));
String colour = cursor.getInt(cursor.getColumnIndex("colour"));
fruitAdapter.add(colour + " " + weight + " " + fruit_type);
}
while(cursor.moveToNext());
}
catch(Exception e)
{
e.printStackTrace();
}
cursor.deactivate();
cursor.close();
profileDatabase.close();
}
I believe this is what I'm looking for, however I find it very confusing:
Android Spinners, say I pull spinner selections from SQL, can I also add their SQL _id's to the spinner values?
How can I get the _id column in there somewhere, so that is accessible from some method in the spinner object?
I cannot think of a scenario where your _ID value is not already directly available to you or derivable via the position:
In onListItemClick() of a ListActivity, it is the id parameter
In onItemClick() of a OnItemClickListener, it is the id parameter
Anywhere else that you have a position (e.g., getView() of a ListAdapter), call moveToPosition() on your Cursor and retrieve your _ID that way

Categories

Resources