SQLite Android Delete database row - android

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;
}

Related

SQLite Database in Android not returning anything

I am trying to read data from SQLite database that exists and has the required values. For some reason, the cursor doesn't return anything or the execution halts - I don't know what the reason is as there is no error of any sort.
Nothing seems to happen after printing(in logcat) :
TableAllSyncInboxHandlerThread: handleMessage(): reading values from
TABLE_ALL
Code:
db = db_helper.getReadableDatabase();
String[] projection_id = {
BaseColumns._ID,
SpamBusterContract.TABLE_ALL.COLUMN_CORRES_INBOX_ID
};
String selection_id = null;
String[] selection_args = null;
String sort_order = SpamBusterContract.TABLE_ALL.COLUMN_SMS_EPOCH_DATE + " DESC";
Log.d(TAG, "TableAllSyncInboxHandlerThread: handleMessage(): reading values from TABLE_ALL");
------> Cursor cursor_read_id = db.query(SpamBusterContract.TABLE_ALL.TABLE_NAME, // The table to query
projection_id, // The array of columns to return (pass null to get all)
selection_id, // The columns for the WHERE clause
selection_args, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sort_order // The sort order
);
if (!cursor_read_id.moveToFirst()) {
tableall_is_empty = true;
Log.d(TAG, "TableAllSyncInboxHandlerThread: handleMessage(): TABLE_ALL is empty");
} else {
tableall_is_empty = false;
Log.d(TAG, "TableAllSyncInboxHandlerThread: handleMessage(): TABLE_ALL not empty");
}
cursor_read_id.close();
What might be the reason?
EDIT : got the answer. Stupid me! I started a transaction on that table in some other part of my code. I wrote db.beginTransaction() and forgot to end it.

working with custom views and sqlite database-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;
}

Method does not search in database?

Since morning, I've been trying to figure it out a problem that occured me today, and now, close to midnight I found out the problem.. I have 2 methods in a database, one for registering new users and one for login management purposes. Both use the same parameters:
1- user class, 2- var for user class.
The login management gets text from 2 edittexts and compare their values with database ( something like username/password ) and the other have the basic variables.getVariables() -> insert(table,null,variables).
When I call registra_usuario method, translated for register_user it proceeds like it inserted the info into database. But, when I use the second method busca_acesso (search_access) it gives me an OutofBounds error
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0
Does this mean that the database has nothing inside TABLE_USER? Because cursor has a size of 0?
These are my two methods:
public boolean registra_usuario(user user){ <- ***THIS ONE SAYS IT'S NEVER USED***
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
try{
values.put(COLUMN_USER_ENTRY_ID, user.getId());
values.put(COLUMN_USER_USERNAME, user.getUsername());
values.put(COLUMN_USER_PASSWORD, user.getPassword());
values.put(KEY_CREATED_AT , user.getCreated_at());
db.insert(TABLE_USER, null, values);
CharSequence text = "Usuário Cadastrado!!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(null, text, duration);
toast.show();
return true;
}catch (Exception e){
db.close();
return false;
}
}
UPDATED METHOD
public boolean busca_acesso(user user){
SQLiteDatabase db = this.getReadableDatabase();
String [] tabela_user = new String[]{"usuaid","username","password"};
String [] whereargs = new String[]{user.getUsername()};
String compare_user = projeto_db.COLUMN_USER_PASSWORD + " = ?";
Cursor cursor = db.query(TABLE_USER, tabela_user, compare_user, whereargs, null, null, null );
int index = cursor.getColumnIndex(COLUMN_USER_PASSWORD);
cursor.moveToFirst();
while(!cursor.getString(index).equals(user.getPassword())){
cursor.moveToNext();
}
if(cursor.getString(index).equals(user.getPassword())) {
return true;
}else{
return false;
}}
final projeto_db db = new projeto_db(this);
user user = new user(); ***MAIN_ACTIVITY
user.setUsername(username_login);
user.setPassword(password_login);
db.busca_acesso(user);
user user = new user(); ***DIFFERENT ACTIVITY
user.setId();
user.setUsername(editText_username.getText().toString());
user.setPassword(editText_password.getText().toString());
user.setCreated_at(getDateTime());
db.registra_usuario(user);
Both are being called inside onCreate from class and from onClick of Button.
Thanks in advance!

my sqlite cursor returns empty result for a query

I have a small function for checking to see if a records already exists in my sqlite database. There is data in the database that should match the query, i have verified this by opening up the database.But i get an empty result.
Below is the function, it takes in a parameter and uses that as the search parameter. i have also verified that the parameter is correct.
public boolean checkParent(String email)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = null;
try
{
res = db.rawQuery("SELECT * FROM parents WHERE email = ' " + email + " ' ",null);
res.close();
}
catch (Exception ex)
{
Log.e("Error checking parent", ex.toString());
}
if(res == null)
{
return true;
}
else
{
return false;
}
}
Right way to pass argument in rawQuery method.
db.rawQuery("SELECT * FROM parents WHERE email = ?",new String[]{email});
You are checking whether the cursor object res is null. This will never happen; rawQuery() always returns a cursor object.
You have to check whether the cursor is empty, i.e., whether the cursor actually contains any rows. To do this, call a method like moveToFirst() and check if it succeeds.
Or even better, use a helper function that does handle the cursor for you:
public boolean checkParent(String email)
{
SQLiteDatabase db = this.getReadableDatabase();
long count = DatabaseUtils.queryNumEntries(db,
"parents", "email = ?", new String[]{ email });
return count > 0;
}

How to check data in SQLite if already exist update or else insert in android

I want to check the data in SQLite if already exist can update or else insert.I am checking code like this what i mentioned below.
Code:
public long addmenus(String navigationdrawer,String optionname)
{
SQLiteDatabase menus=this.getWritableDatabase();
try {
ContentValues values=new ContentValues();
values.put(HEADER_NAME,navigationdrawer);
values.put(CHILD_NAME,optionname);
// menus.insert(TABLE_NAME,null,values);
// String owner=optionname;
Cursor cursor = menus.rawQuery("select * from TABLE_NAME where CHILD_NAME ='"+ optionname +"'", null);
if(cursor.getCount()<1)
{
//execute insert query here
long rows = menus.insert(TABLE_NAME, null, values);
return rows;
// return rows inserted.
}
else
{
//Perform the update query
String strFilter = "CHILD_NAME" + optionname;
long updaterow=menus.update(TABLE_NAME,values,strFilter,null);
return updaterow;
// return rows updated.
}
// menus.close();
} catch (Exception e) {
return -1;
}
finally {
if (menus != null)
menus.close();
}
}
My activity:
I converted whole json data into string object then insert into SQLite.
String productpage=jsonObject.toString();
db.addmenus(productpage,"Navigationmenus");
But It doesn't work.It couldn't insert into sqlite.
Anyone solve this problem Glad to appreciate.
Thanks in advance
You can user insertWithOnConflict() like this
db.insertWithOnConflict(TABLE, null, yourContentValues, SQLiteDatabase.CONFLICT_REPLACE);
You can use refer this Link. That link explains how to find the email address available in a table or not, you can change the column name, table and pass the values according. In your scenario you want to check the whether the name exists already or not, so you must pass which name you want to find. If the name is there then this method will return true or false. You can validate whether you had to insert or update according the response.i.e., false means you had to insert, otherwise if it is true means then you had to update.
you should use replace into
REPLACE INTO table(...) VALUES(...);
Question is not much clear but, i think you want to check either data/record is inserted in SQLite or not. you will need to define some extra variable long rowInserted insert() method returns the row ID of the newly inserted row, or -1 when an error occurred.
menus.insert(TABLE_NAME, null, values);
long rowInserted = db.insert(AddNewPhysicalPerson, null, newValues);
if(rowInserted != -1)
Toast.makeText(myContext, "New row added :" + rowInserted, Toast.LENGTH_SHORT).show();
else
Toast.makeText(myContext, "Something wrong", Toast.LENGTH_SHORT).show();
Updated
check either data is in table or column? for this you use this code
public boolean Exists(String id){
Cursor res = getAllData();
int count=0;
while (res.moveToNext()){
String email =res.getString(3);
if(email.equals(id)){
count++;
}
}
if(count==0){
return false;
} else{
return true;
}
}
Second you asking about json first store all data in any List run time and get string from it then you are able to store in SQlite
try {
items = jsonObject.getJSONArray("myjsonattribute");
List<MyAnySetterGetter> mList = new ArrayList<MyAnySetterGetter>();
for (int i = 0; i < items.length(); i++) {
JSONObject c = items.getJSONObject(i);
String mfilename = c.getString("myjsonattribute2");
mList.add(mfilename);
}
} catch (JSONException e) {
//e.printStackTrace();
}
then use above list to insert data from list to SQLite
like
String str1 = mList.get(position).getMYITEM1();
String str2 = mList.get(position).getMYITEM2();
insert str1 and str2 in SQLite hope you will get idea.
you should
set key for the table, then
insert(if the key existed it will not insert anymore), then
update all row.

Categories

Resources