Search in sources :

Example 6 with DBHelper

use of dev.sagar.smsblocker.tech.service.helper.DBHelper in project SMSBlocker by sagarpawardev.

the class DBServiceSingleton method update.

/**
 * Provides Database Service for deleting
 * @param context Context
 * @param uri URI of Table
 * @param where Where Condition for update
 * @param selectionArgs Query Selection arguments
 * @param values Values to update
 * @return number of rows updated
 */
public int update(Context context, Uri uri, ContentValues values, String where, String[] selectionArgs) {
    String methodName = "update()";
    log.justEntered(methodName);
    log.info(methodName, "Updating SMS Database...");
    ContentResolver contentResolver = context.getContentResolver();
    int count = contentResolver.update(uri, values, where, selectionArgs);
    log.info(methodName, "SMS DB Updated with count: " + count);
    log.info(methodName, "Updating Conversation Database...");
    DBHelper dbHelper = new DBHelper(context);
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    if (values.containsKey(read)) {
        // Converting fields of different column names to Local Database column name
        String value = values.getAsBoolean(read) ? "1" : "0";
        values.remove(read);
        values.put(read_local, value);
        values.put(unreadCount_local, 0);
    }
    if (values.containsKey(date)) {
        // Converting fields of different column names to Local Database column name
        String value = values.getAsString(date);
        values.remove(date);
        values.put(date_local, value);
    }
    count = db.update(Converesation.TABLE_NAME, values, where, selectionArgs);
    log.info(methodName, "Conversation DB Updated count: " + count);
    db.close();
    dbHelper.close();
    log.returning(methodName);
    return count;
}
Also used : SQLiteDatabase(android.database.sqlite.SQLiteDatabase) DBHelper(dev.sagar.smsblocker.tech.service.helper.DBHelper) ContentResolver(android.content.ContentResolver)

Example 7 with DBHelper

use of dev.sagar.smsblocker.tech.service.helper.DBHelper in project SMSBlocker by sagarpawardev.

the class DBServiceSingleton method refreshConversations.

/**
 * Refreshes Conversation Shadow Database
 * @param context Context
 * @return Returns number of rows present in ShadowConversation
 */
public int refreshConversations(Context context) {
    String methodName = "refreshConversation()";
    log.justEntered(methodName);
    int result = 0;
    DBHelper mDBHelper = new DBHelper(context);
    // Content MAP
    ContentResolver contentResolver = context.getContentResolver();
    Uri mUriSMS = Telephony.Sms.CONTENT_URI;
    // Read Old Conversation DB Rows Starts
    log.info(methodName, "Reading old Address and Date rows");
    String[] mOldProjection = { "*" };
    SQLiteDatabase readDB = mDBHelper.getReadableDatabase();
    Cursor mOldCursor = readDB.query(Converesation.TABLE_NAME, mOldProjection, null, null, null, null, null);
    HashMap<String, SMS> oldMap = new HashMap<>();
    if (mOldCursor != null) {
        log.info(methodName, "Reading Address and Date Count:" + mOldCursor.getCount());
        while (mOldCursor.moveToNext()) {
            String address = mOldCursor.getString(mOldCursor.getColumnIndexOrThrow(this.address_local));
            /*String normalizeAddress = PhoneNumberUtils.normalizeNumber(originalAddress);
                String address = normalizeAddress;
                if(address.length() < 9){ //If Number is like VK-Voda its normalized code is 3856778
                    address = originalAddress;
                }*/
            log.info(methodName, "Reading contact details: " + address);
            long date = mOldCursor.getLong(mOldCursor.getColumnIndexOrThrow(this.date_local));
            String id = mOldCursor.getString(mOldCursor.getColumnIndexOrThrow(this._id_local));
            String body = mOldCursor.getString(mOldCursor.getColumnIndexOrThrow(this.body_local));
            int subscriptionId = mOldCursor.getInt(mOldCursor.getColumnIndexOrThrow(this.subscriptionId_local));
            String read = mOldCursor.getString(mOldCursor.getColumnIndex(this.read_local));
            boolean bRead = (read.equals("0") || read.equalsIgnoreCase("false"));
            long type = mOldCursor.getLong(mOldCursor.getColumnIndexOrThrow(this.type_local));
            SMS sms = new SMS();
            sms.setId(id);
            sms.setAddress(address);
            sms.setDateTime(date);
            sms.setId(id);
            sms.setBody(body);
            sms.setSubscription(subscriptionId);
            sms.setRead(bRead);
            sms.setType(type);
            oldMap.put(address, sms);
        }
        mOldCursor.close();
    } else {
        log.error(methodName, "OLD Conversation Query returned null cursor");
    }
    // -- Read Old Conversation DB Rows Ends
    // Reading Latest SMS DB Rows from ContentProvider Starts
    log.info(methodName, "Reading Latest SMS from Contact");
    String[] mProjection = new String[] { "*" };
    String mSelection = "";
    String[] mSelectionArgs = {};
    String mSortOrder = this.date + " DESC";
    HashSet<String> doneSet = new HashSet<>();
    HashMap<String, Integer> unreadCountMap = new HashMap<>();
    SQLiteDatabase writableDB = mDBHelper.getWritableDatabase();
    Cursor mLatestSmsCursor = contentResolver.query(mUriSMS, mProjection, mSelection, mSelectionArgs, mSortOrder);
    int tempCount = 0;
    if (mLatestSmsCursor != null) {
        log.info(methodName, "Reading latest sms from contact count:" + mLatestSmsCursor.getCount());
        while (mLatestSmsCursor.moveToNext()) {
            String id = mLatestSmsCursor.getString(mLatestSmsCursor.getColumnIndexOrThrow(this._id));
            String address = mLatestSmsCursor.getString(mLatestSmsCursor.getColumnIndexOrThrow(this.address));
            String body = mLatestSmsCursor.getString(mLatestSmsCursor.getColumnIndexOrThrow(this.body));
            String subscriptionId = mLatestSmsCursor.getString(mLatestSmsCursor.getColumnIndexOrThrow(this.subscriptionId));
            String read = mLatestSmsCursor.getString(mLatestSmsCursor.getColumnIndex(this.read));
            long date = mLatestSmsCursor.getLong(mLatestSmsCursor.getColumnIndexOrThrow(this.date));
            long type = mLatestSmsCursor.getLong(mLatestSmsCursor.getColumnIndexOrThrow(this.type));
            String threadId = mLatestSmsCursor.getString(mLatestSmsCursor.getColumnIndex(this.threadId));
            String person = mLatestSmsCursor.getString(mLatestSmsCursor.getColumnIndex(this.person));
            String protocol = mLatestSmsCursor.getString(mLatestSmsCursor.getColumnIndex(this.protocol));
            String status = mLatestSmsCursor.getString(mLatestSmsCursor.getColumnIndex(this.status));
            String reply_path_present = mLatestSmsCursor.getString(mLatestSmsCursor.getColumnIndex(this.reply_path_present));
            String subject = mLatestSmsCursor.getString(mLatestSmsCursor.getColumnIndex(this.subject));
            String locked = mLatestSmsCursor.getString(mLatestSmsCursor.getColumnIndex(this.locked));
            String errorCode = mLatestSmsCursor.getString(mLatestSmsCursor.getColumnIndex(this.errorCode));
            /*String normalizedAddress = PhoneNumberUtils.normalizeNumber(address);
                String address = normalizedAddress;
                if(address.length() < 8){ //If Number is like VK-Voda its normalized code is 3856778
                    address = originalAddress;
                }*/
            log.info(methodName, "Reading SMS from contactNumber: " + address + " ");
            ContentValues values = new ContentValues();
            values.put(this._id_local, id);
            values.put(this.address_local, address);
            values.put(this.body_local, body);
            values.put(this.subscriptionId_local, subscriptionId);
            values.put(this.read_local, read);
            values.put(this.date_local, date);
            values.put(this.type_local, type);
            values.put(this.threadId_local, threadId);
            values.put(this.person_local, person);
            values.put(this.protocol_local, protocol);
            values.put(this.status_local, status);
            values.put(this.reply_path_present_local, reply_path_present);
            values.put(this.subject_local, subject);
            values.put(this.locked_local, locked);
            values.put(this.errorCode_local, errorCode);
            // If unread increment count
            log.info(methodName, "Raw Unread value: " + read + " for address: " + address);
            // If object is saved as integer or boolean
            boolean bUnread = (read.equals("0") || read.equalsIgnoreCase("false"));
            if (bUnread) {
                Integer unreadCount = unreadCountMap.get(address);
                int count = unreadCount == null ? 0 : unreadCount;
                count++;
                // Increment count here
                unreadCountMap.put(address, count);
                values.put(this.unreadCount_local, count);
                log.info(methodName, "Adding unread count: " + count + " for address: " + address);
            }
            // If value is already in Map then go to next value
            if (doneSet.contains(address))
                continue;
            SMS oldSMS = oldMap.get(address);
            // if(oldSMS == null) continue; //Just in case if nothing found
            long oldDate = oldMap.get(address) == null ? 0 : oldMap.get(address).getDateTime();
            // if(oldDate >= date) continue; //If oldDate is greater than or equals current date ignore message
            log.error(methodName, "Olddate: " + oldDate + " newdate:" + date + " address:" + address + " type:" + type);
            if (oldSMS != null && id.equals(oldSMS.getId()) && address.equals(oldSMS.getAddress())) {
                doneSet.add(address);
                // If SMS is same as older ones
                continue;
            }
            if (oldMap.containsKey(address)) {
                String whereClause = this.address_local + " = ?";
                String[] whereArgs = { address };
                writableDB.update(Converesation.TABLE_NAME, values, whereClause, whereArgs);
            } else {
                writableDB.insert(Converesation.TABLE_NAME, null, values);
            }
            doneSet.add(address);
            result++;
        }
        mLatestSmsCursor.close();
    } else {
        log.error(methodName, "SMS Query returned null cursor");
    }
    // -- Reading Latest SMS DB Rows from ContentProvider Ends
    // Create a map of all contacts Starts
    Uri mContactUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
    String[] mContactProjection = { this.photoUri, this.photoUriThumbnail, ContactsContract.CommonDataKinds.Phone.NUMBER, this.contactName };
    Map<String, ContactDetails> mContactMap = new HashMap<>();
    if (permUtil.hasPermission(context, Permission.READ_CONTACTS)) {
        Cursor mContactCursor = contentResolver.query(mContactUri, mContactProjection, null, null, null);
        if (mContactCursor != null) {
            while (mContactCursor.moveToNext()) {
                String contactName = mContactCursor.getString(mContactCursor.getColumnIndex(this.contactName));
                String photoThumb = mContactCursor.getString(mContactCursor.getColumnIndex(this.photoUriThumbnail));
                String photoUri = mContactCursor.getString(mContactCursor.getColumnIndex(this.photoUri));
                String address = mContactCursor.getString(mContactCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                /*String normalizedAddress = PhoneNumberUtils.normalizeNumber(address);*/
                ContactDetails contact = new ContactDetails();
                contact.name = contactName;
                contact.photoThumbUri = photoThumb;
                contact.photoUri = photoUri;
                contact.address = address;
                String formattedAddress = phoneUtils.formatNumber(context, contact.address);
                mContactMap.put(formattedAddress, contact);
                // TODO Default country to format number
                log.info(methodName, "Found contactName: " + contactName + " for address: " + address + " In new map: " + doneSet.contains(address));
            }
            mContactCursor.close();
        } else {
            log.error(methodName, "Nothing in Contacts Cursor for " + address);
        }
    } else {
        log.error(methodName, "No contact read permissions");
    }
    // Update Photo in Database Starts
    for (String key : doneSet) {
        String formattedKey = phoneUtils.formatNumber(context, key);
        ContactDetails contact = mContactMap.get(formattedKey);
        if (contact == null) {
            // In case address does not exists in Contacts
            continue;
        }
        ContentValues values = new ContentValues();
        values.put(this.contactName_local, contact.name);
        values.put(this.photoUri_local, contact.photoUri);
        values.put(this.photoUriThumbnail_local, contact.photoThumbUri);
        String whereClause = this.address_local + " LIKE ?";
        String encodedAddress = phoneUtils.encode(contact.address);
        String[] whereArgs = { encodedAddress };
        writableDB.update(Converesation.TABLE_NAME, values, whereClause, whereArgs);
    }
    // -- Update Photo in Database Ends
    // Update unread_count in Conversation Starts
    StringBuilder sbRawQuery = new StringBuilder();
    sbRawQuery.append(" UPDATE ");
    sbRawQuery.append(Converesation.TABLE_NAME);
    sbRawQuery.append(" SET " + Converesation.COLUMN_NAME_UNREAD_COUNT + "= CASE " + Converesation.COLUMN_NAME_ADDRESS);
    ArrayList<Integer> alValues = new ArrayList<>();
    Set<String> addresses = unreadCountMap.keySet();
    for (String mAddress : addresses) {
        Integer iUnreadCount = unreadCountMap.get(mAddress);
        int unreadCount = iUnreadCount == null ? 0 : iUnreadCount;
        sbRawQuery.append(" WHEN '" + mAddress + "' THEN " + unreadCount);
        alValues.add(unreadCount);
    }
    sbRawQuery.append(" END WHERE ");
    sbRawQuery.append(Converesation.COLUMN_NAME_ADDRESS);
    sbRawQuery.append(" IN (");
    for (String mAddress : addresses) {
        sbRawQuery.append("'" + mAddress + "',");
    }
    // Deleting , at end
    sbRawQuery.deleteCharAt(sbRawQuery.length() - 1);
    sbRawQuery.append(")");
    if (addresses.size() > 0) {
        // Updating empty database does not make sense and App crashes as well
        String[] strArgs = null;
        String rawQuery = sbRawQuery.toString();
        log.debug(methodName, "Formed Query: " + rawQuery);
        Cursor c = writableDB.rawQuery(rawQuery, strArgs);
        log.info(methodName, "Updated rows: " + c.getCount());
        // Query won't update unless moveToFirst() or close() is called
        c.close();
    }
    // -- Update unread_count in Conversation Starts
    // TODO: Delete Condition when conversation is removed from main database but exists in Local Database
    writableDB.close();
    mDBHelper.close();
    log.returning(methodName);
    return result;
}
Also used : ContentValues(android.content.ContentValues) HashMap(java.util.HashMap) DBHelper(dev.sagar.smsblocker.tech.service.helper.DBHelper) ArrayList(java.util.ArrayList) Cursor(android.database.Cursor) Uri(android.net.Uri) ContentResolver(android.content.ContentResolver) SQLiteDatabase(android.database.sqlite.SQLiteDatabase) SMS(dev.sagar.smsblocker.tech.beans.SMS) HashSet(java.util.HashSet)

Aggregations

SQLiteDatabase (android.database.sqlite.SQLiteDatabase)7 DBHelper (dev.sagar.smsblocker.tech.service.helper.DBHelper)7 ContentResolver (android.content.ContentResolver)4 Cursor (android.database.Cursor)4 SQLiteOpenHelper (android.database.sqlite.SQLiteOpenHelper)3 Uri (android.net.Uri)3 SMS (dev.sagar.smsblocker.tech.beans.SMS)3 ArrayList (java.util.ArrayList)3 HashSet (java.util.HashSet)2 ContentValues (android.content.ContentValues)1 Context (android.content.Context)1 Conversation (dev.sagar.smsblocker.tech.beans.Conversation)1 IndexedHashMap (dev.sagar.smsblocker.tech.datastructures.IndexedHashMap)1 DBServiceSingleton (dev.sagar.smsblocker.tech.service.DBServiceSingleton)1 HashMap (java.util.HashMap)1