Check if two items are equal - android

I'm creating a forum application and I currently if I delete a thread I'm deleting all threads.
Is there a good method or query to check if the UserId == ThreadId?
My current code:
public void deleteThread() {
SQLiteDatabase db = this.getWritableDatabase();
// Delete All Rows
db.delete(TABLE_THREAD, null, null);
db.close();
Log.d(TAG, "Deleted all Thread info from sqlite");
}

You need to pass correct value to the well-documented delete method to narrow down the scope of deletion to a subset of all entries in the DB table.
public void deleteThreadById(String threadId) {
SQLiteDatabase db = this.getWritableDatabase();
String whereClause = "threadId = " + threadId;
db.delete(TABLE_THREAD, whereClause, null);
db.close();
}
Deleting all threads of a given user via their userId would be similar but probably doesn't make sense in a forum software.
This is how SQL works in general and it's a bit scary you started development without familiarising yourself with the very basics.

Something like this;
public void deleteThread(String threadName) {
SQLiteDatabase db = this.getWritableDatabase();
try {
db.delete(MYDATABASE_TABLE, "name = ?", new String[]{threadName});
} catch (Exception e) {
e.printStackTrace();
} finally {
db.close();
}
}
Something long these lines, querying database to find the specific row that has column which matches the parameter.
For example to delete a row which the name column is "Hello World";
deleteThread("Hello World");

Related

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.

Android - SQLite db keeps showing rows that should have been deleted

I'm currently creating an app that downloads lists from a server and places those lists into an SQLite database. In the Mainactivity it calls the lists from the db and places them into a custom adapter, everything works fine and such.
After this I go through several screens to proces the listdata and in the final activity it uses a query to delete the row it's been working on from the db. I use logcat to print the db after this and it shows that the row has been deleted.
Next it takes me back to the Mainactivity and in its onResume I once again load the lists from the db only to find that the row that should have been deleted is still in it. The listview is being updated correctly, it's really an issue of retrieving data from the database that should have been deleted.
So, anybody has an idea why I get rows that have been deleted in another activity?
Mainactivity:
private List<String> list = new ArrayList<>();
public void onResume() {
super.onResume();
context = getApplicationContext();
ConsLoadListDataSource cllDataSource = new ConsLoadListDataSource(context);
cllDataSource.open();
list = cllDataSource.sqliteToListIds();
cllDataSource.close();
logcat("Jadajada: " + list.toString());
}
SQLiteHelper:
public List<String> sqliteToListIds() {
List<String> conList= new ArrayList<>();
if (!db.isOpen()) {
open();
}
Cursor cursor = db.query(ConsLoadListSQLHelper.TABLE_CONS_HEADER,
allConsListColumns, null, null, "loadlist" , null, "loadlist");
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
conList.add(cursor.getString(1));
cursor.moveToNext();
}
db.close();
return conList;
}
The deleting method works, but since it's being asked for:
public void deleteList(int id) {
if (!db.isOpen()) {
open();
}
db.delete(ConsLoadListSQLHelper.TABLE_CONS_HEADER,
ConsLoadListSQLHelper.CONS_HEADER_ID + " = " + id, null);
db.close();
}
edit
I've found a workaround solution by deleting the row on my server and once again retrieving all data from the server before I go back to my MainActivity, but I still don't know how to solve the original problem and this makes my app more dependent on an internet connection, so it's not perfect, but will have to do for now.
For deleting single item you have to use
public void deleteRule(String value) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(Table_Name, Key_value + " = ?",
new String[] { value });
db.close();
}
Hope it helps.

Should I check if the SQLite is open before each transaction?

In my database there are many methods, each one is created to retrieve a specific row by passing the ID as a parameter. And, In my App, I need to call these methods to perform certain action on the retrieved data. example of that is, the code posted below. Do I need to check the SqliteDB.isOpen before I call these methods.
Java_Code:
if (! sqliteDB.isOpen()) {
Log.d(TAG, "#fetchItemRelativeToFullList(): Sqlite DataBase Was Closed, and it Will Be Opened");
sqliteDB = mplOpenHelperDB.getWritableDatabase();
}
Log.d(TAG, "#fetchItemRelativeToFullList(): Sqlite DataBase Is Opened");
String name = mplOpenHelperDB.getLocationName(itemClickedPos+1);
Toast.makeText(getApplicationContext(), "name of location"+name, Toast.LENGTH_SHORT).show();
DataBaseRow dataBaseRow = new DataBaseRow();
if (dataBaseRow != null) {
Log.d(TAG, "#fetchItemRelativeToFullList(): Object of DataBaseRow Class Is Created, Not NULL");
if ( (mplOpenHelperDB.getLocationName(itemClickedPos+1)).equals("") ) {
Log.i(TAG, "#fetchItemRelativeToFullList: getLocationName Is Empty");
dataBaseRow.setLocName("NULL");
}
else {
String targetName = mplOpenHelperDB.getLocationName(itemClickedPos+1);
dataBaseRow.setLocName(targetName);
}
Sample Of DataBase Methods:
public String getLocationName(long id) {
SQLiteDatabase db = this.getReadableDatabase();
SQLiteCursor c = (SQLiteCursor) db.rawQuery("SELECT locationName FROM MPLData WHERE "+
BaseColumns._ID+" = "+
Long.toString(id) +" AND locationName IS NOT NULL ", null);
String r;
c.moveToFirst();
if (c.getCount() == 0) {
return "";
} else {
r = c.getString(0);
}
c.close();
db.close();
return r;
}
The answer to your immediate question is "No". When you getReadableDatabase(), the db is open. You are good.
FWIW, I'd guess that you have experience doing db work in some other context (Ruby, PHP, etc). As David points out you are doing way more work than you need to do. Have a look at Loaders, ContentProviders and ContentResolvers, FTW.
No, getReadableDatabase() and getWritableDatabase() Create and/or open a database that will be used for reading and writing. The first time this is called, the database will be opened and onCreate(SQLiteDatabase), onUpgrade(SQLiteDatabase, int, int) and/or onOpen(SQLiteDatabase) will be called.

Delete Record from Database row wise in Android

I'm trying to build my first Android application, but I'm experiencing a problem: I write following code for insert record in database, but I don't know how to delete a row, so can anybody help me???
Code for insert record:
public void btnAddEmp_Click(View view)
{
boolean ok=true;
try
{
Spannable spn=txtAge.getText();
String name=txtName.getText().toString();
int age=Integer.valueOf(spn.toString());
int deptID=Integer.valueOf((int)spinDept.getSelectedItemId());
Student emp=new Student(name,age,deptID);
dbHelper.AddEmployee(emp);
}
catch(Exception ex)
{
ok=false;
CatchError(ex.toString());
}
finally
{
if(ok)
{
//NotifyEmpAdded();
Alerts.ShowEmpAddedAlert(this);
txtEmps.setText("Number of students "+String.valueOf(dbHelper.getEmployeeCount()));
}
}
}
DELETE FROM tableName WHERE fieldName = value
This is delete query. Execute it with execSql
Edit: use execSql instead of rawQuery
You can simply do this using SQLiteDatabase.execSQL() and don't try rawQuery It's meant for querying.
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM tableName where fieldName=Value");
db.close();
Check out the detailed answer here

Categories

Resources