Example usage for android.database Cursor getPosition

List of usage examples for android.database Cursor getPosition

Introduction

In this page you can find the example usage for android.database Cursor getPosition.

Prototype

int getPosition();

Source Link

Document

Returns the current position of the cursor in the row set.

Usage

From source file:org.linphone.ContactsManager.java

public Contact findContactWithAddress(ContentResolver contentResolver, LinphoneAddress address) {
    String sipUri = address.asStringUriOnly();
    if (sipUri.startsWith("sip:"))
        sipUri = sipUri.substring(4);/*from w  ww.ja  v  a  2s  .  c om*/

    LinphoneCore lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
    if (lc != null && lc.getFriendList() != null
            && LinphoneManager.getLcIfManagerNotDestroyedOrNull().getFriendList().length > 0) {
        for (LinphoneFriend friend : LinphoneManager.getLcIfManagerNotDestroyedOrNull().getFriendList()) {
            if (friend.getAddress().equals(address)) {
                return getContact(friend.getRefKey(), contentResolver);
            }
        }
    }

    //Find Sip address
    Contact contact;
    String[] projection = new String[] { ContactsContract.Data.CONTACT_ID, ContactsContract.Data.DISPLAY_NAME };
    String selection = new StringBuilder().append(ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS)
            .append(" = ?").toString();

    Cursor cur = contentResolver.query(ContactsContract.Data.CONTENT_URI, projection, selection,
            new String[] { sipUri }, null);
    if (cur != null) {
        if (cur.moveToFirst()) {
            contact = Compatibility.getContact(contentResolver, cur, cur.getPosition());
            cur.close();

            if (contact != null) {
                return contact;
            }
        }
        cur.close();
    }

    //Find number
    Uri lookupUri = Uri.withAppendedPath(android.provider.ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
            Uri.encode(address.getUserName()));
    projection = new String[] { ContactsContract.PhoneLookup._ID, ContactsContract.PhoneLookup.NUMBER,
            ContactsContract.PhoneLookup.DISPLAY_NAME };
    Cursor c = contentResolver.query(lookupUri, projection, null, null, null);
    contact = checkPhoneQueryResult(contentResolver, c, ContactsContract.PhoneLookup.NUMBER,
            ContactsContract.PhoneLookup._ID, address.getUserName());

    if (contact != null) {
        return contact;
    }

    return null;
}

From source file:org.totschnig.myexpenses.provider.TransactionDatabase.java

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    try {/*from  w  w w .j  a  v  a 2s. c  o m*/
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ".");
        if (oldVersion < 17) {
            db.execSQL("drop table accounts");
            db.execSQL("CREATE TABLE accounts (_id integer primary key autoincrement, label text not null, "
                    + "opening_balance integer, description text, currency text not null);");
            //db.execSQL("ALTER TABLE expenses add column account_id integer");
        }

        if (oldVersion < 18) {
            db.execSQL(
                    "CREATE TABLE payee (_id integer primary key autoincrement, name text unique not null);");
            db.execSQL("ALTER TABLE expenses add column payee text");
        }

        if (oldVersion < 19) {
            db.execSQL("ALTER TABLE expenses add column transfer_peer text");
        }

        if (oldVersion < 20) {
            db.execSQL(
                    "CREATE TABLE transactions ( _id integer primary key autoincrement, comment text not null, "
                            + "date datetime not null, amount integer not null, cat_id integer, account_id integer, "
                            + "payee  text, transfer_peer integer default null);");
            db.execSQL("INSERT INTO transactions (comment,date,amount,cat_id,account_id,payee,transfer_peer)"
                    + " SELECT comment,date,CAST(ROUND(amount*100) AS INTEGER),cat_id,account_id,payee,transfer_peer FROM expenses");
            db.execSQL("DROP TABLE expenses");
            db.execSQL("ALTER TABLE accounts RENAME to accounts_old");
            db.execSQL("CREATE TABLE accounts (_id integer primary key autoincrement, label text not null, "
                    + "opening_balance integer, description text, currency text not null);");
            db.execSQL("INSERT INTO accounts (label,opening_balance,description,currency)"
                    + " SELECT label,CAST(ROUND(opening_balance*100) AS INTEGER),description,currency FROM accounts_old");
            db.execSQL("DROP TABLE accounts_old");
        }

        if (oldVersion < 21) {
            db.execSQL(
                    "CREATE TABLE paymentmethods (_id integer primary key autoincrement, label text not null, type integer default 0);");
            db.execSQL(
                    "CREATE TABLE accounttype_paymentmethod (type text, method_id integer, primary key (type,method_id));");
            ContentValues initialValues;
            long _id;
            for (PaymentMethod.PreDefined pm : PaymentMethod.PreDefined.values()) {
                initialValues = new ContentValues();
                initialValues.put("label", pm.name());
                initialValues.put("type", pm.paymentType);
                _id = db.insert("paymentmethods", null, initialValues);
                initialValues = new ContentValues();
                initialValues.put("method_id", _id);
                initialValues.put("type", "BANK");
                db.insert("accounttype_paymentmethod", null, initialValues);
            }
            db.execSQL("ALTER TABLE transactions add column payment_method_id integer");
            db.execSQL("ALTER TABLE accounts add column type text default 'CASH'");
        }

        if (oldVersion < 22) {
            db.execSQL("CREATE TABLE templates ( _id integer primary key autoincrement, comment text not null, "
                    + "amount integer not null, cat_id integer, account_id integer, payee text, transfer_peer integer default null, "
                    + "payment_method_id integer, title text not null);");
        }

        if (oldVersion < 23) {
            db.execSQL("ALTER TABLE templates RENAME to templates_old");
            db.execSQL("CREATE TABLE templates ( _id integer primary key autoincrement, comment text not null, "
                    + "amount integer not null, cat_id integer, account_id integer, payee text, transfer_peer integer default null, "
                    + "payment_method_id integer, title text not null, unique(account_id, title));");
            try {
                db.execSQL(
                        "INSERT INTO templates(comment,amount,cat_id,account_id,payee,transfer_peer,payment_method_id,title)"
                                + " SELECT comment,amount,cat_id,account_id,payee,transfer_peer,payment_method_id,title FROM templates_old");
            } catch (SQLiteConstraintException e) {
                Log.e(TAG, e.getLocalizedMessage());
                //theoretically we could have entered duplicate titles for one account
                //we silently give up in that case (since this concerns only a narrowly distributed alpha version)
            }
            db.execSQL("DROP TABLE templates_old");
        }

        if (oldVersion < 24) {
            db.execSQL("ALTER TABLE templates add column usages integer default 0");
        }

        if (oldVersion < 25) {
            //for transactions that were not transfers, transfer_peer was set to null in transactions, but to 0 in templates
            db.execSQL("update transactions set transfer_peer=0 WHERE transfer_peer is null;");
        }

        if (oldVersion < 26) {
            db.execSQL("alter table accounts add column color integer default -6697984");
        }

        if (oldVersion < 27) {
            db.execSQL("CREATE TABLE feature_used (feature text not null);");
        }

        if (oldVersion < 28) {
            db.execSQL("ALTER TABLE transactions RENAME to transactions_old");
            db.execSQL(
                    "CREATE TABLE transactions(_id integer primary key autoincrement, comment text, date datetime not null, amount integer not null, "
                            + "cat_id integer references categories(_id), account_id integer not null references accounts(_id),payee text, "
                            + "transfer_peer integer references transactions(_id), transfer_account integer references accounts(_id), "
                            + "method_id integer references paymentmethods(_id));");
            db.execSQL(
                    "INSERT INTO transactions (_id,comment,date,amount,cat_id,account_id,payee,transfer_peer,transfer_account,method_id) "
                            + "SELECT _id,comment,date,amount, "
                            + "CASE WHEN transfer_peer THEN null ELSE CASE WHEN cat_id THEN cat_id ELSE null END END, "
                            + "account_id,payee, "
                            + "CASE WHEN transfer_peer THEN transfer_peer ELSE null END, "
                            + "CASE WHEN transfer_peer THEN cat_id ELSE null END, "
                            + "CASE WHEN payment_method_id THEN payment_method_id ELSE null END "
                            + "FROM transactions_old");
            db.execSQL("ALTER TABLE accounts RENAME to accounts_old");
            db.execSQL(
                    "CREATE TABLE accounts (_id integer primary key autoincrement, label text not null, opening_balance integer, description text, "
                            + "currency text not null, type text not null check (type in ('CASH','BANK','CCARD','ASSET','LIABILITY')) default 'CASH', color integer default -3355444);");
            db.execSQL("INSERT INTO accounts (_id,label,opening_balance,description,currency,type,color) "
                    + "SELECT _id,label,opening_balance,description,currency,type,color FROM accounts_old");
            //previously templates where not deleted if referred to accounts were deleted
            db.execSQL(
                    "DELETE FROM templates where account_id not in (SELECT _id FROM accounts) or (cat_id != 0 and transfer_peer = 1 and cat_id not in (SELECT _id from accounts))");
            db.execSQL("ALTER TABLE templates RENAME to templates_old");
            db.execSQL(
                    "CREATE TABLE templates ( _id integer primary key autoincrement, comment text not null, amount integer not null, "
                            + "cat_id integer references categories(_id), account_id integer not null references accounts(_id),payee text, "
                            + "transfer_peer boolean default false, transfer_account integer references accounts(_id),method_id integer references paymentmethods(_id), "
                            + "title text not null, usages integer default 0, unique(account_id,title));");
            db.execSQL(
                    "INSERT INTO templates (_id,comment,amount,cat_id,account_id,payee,transfer_peer,transfer_account,method_id,title,usages) "
                            + "SELECT _id,comment,amount,"
                            + "CASE WHEN transfer_peer THEN null ELSE CASE WHEN cat_id THEN cat_id ELSE null END END, "
                            + "account_id,payee, " + "CASE WHEN transfer_peer THEN 1 ELSE 0 END, "
                            + "CASE WHEN transfer_peer THEN cat_id ELSE null END, "
                            + "CASE WHEN payment_method_id THEN payment_method_id ELSE null END, "
                            + "title,usages FROM templates_old");
            db.execSQL("ALTER TABLE categories RENAME to categories_old");
            db.execSQL(
                    "CREATE TABLE categories (_id integer primary key autoincrement, label text not null, parent_id integer references categories(_id), "
                            + "usages integer default 0, unique (label,parent_id));");
            db.execSQL("INSERT INTO categories (_id,label,parent_id,usages) "
                    + "SELECT _id,label,CASE WHEN parent_id THEN parent_id ELSE null END,usages FROM categories_old");
            db.execSQL("ALTER TABLE paymentmethods RENAME to paymentmethods_old");
            db.execSQL(
                    "CREATE TABLE paymentmethods (_id integer primary key autoincrement, label text not null, type integer check (type in (-1,0,1)) default 0);");
            db.execSQL(
                    "INSERT INTO paymentmethods (_id,label,type) SELECT _id,label,type FROM paymentmethods_old");
            db.execSQL("ALTER TABLE accounttype_paymentmethod RENAME to accounttype_paymentmethod_old");
            db.execSQL(
                    "CREATE TABLE accounttype_paymentmethod (type text not null check (type in ('CASH','BANK','CCARD','ASSET','LIABILITY')), method_id integer references paymentmethods (_id), primary key (type,method_id));");
            db.execSQL(
                    "INSERT INTO accounttype_paymentmethod (type,method_id) SELECT type,method_id FROM accounttype_paymentmethod_old");
            db.execSQL("DROP TABLE transactions_old");
            db.execSQL("DROP TABLE accounts_old");
            db.execSQL("DROP TABLE templates_old");
            db.execSQL("DROP TABLE categories_old");
            db.execSQL("DROP TABLE paymentmethods_old");
            db.execSQL("DROP TABLE accounttype_paymentmethod_old");
            //Changes to handle
            //1) Transfer account no longer stored as cat_id but in transfer_account (in transactions and templates)
            //2) parent_id for categories uses foreign key on itself, hence root categories have null instead of 0 as parent_id
            //3) catId etc now need to be null instead of 0
            //4) transactions payment_method_id renamed to method_id
        }

        if (oldVersion < 29) {
            db.execSQL("ALTER TABLE transactions add column status integer default 0");
        }

        if (oldVersion < 30) {
            db.execSQL("ALTER TABLE transactions add column parent_id integer references transactions (_id)");
            //      db.execSQL("CREATE VIEW committed AS SELECT * FROM transactions WHERE status != 2;");
            //      db.execSQL("CREATE VIEW uncommitted AS SELECT * FROM transactions WHERE status = 2;");
            ContentValues initialValues = new ContentValues();
            initialValues.put("_id", 0);
            initialValues.put("parent_id", 0);
            initialValues.put("label", "__SPLIT_TRANSACTION__");
            db.insert("categories", null, initialValues);
        }

        if (oldVersion < 31) {
            //in an alpha version distributed on Google Play, we had SPLIT_CATID as -1
            ContentValues initialValues = new ContentValues();
            initialValues.put("_id", 0);
            initialValues.put("parent_id", 0);
            db.update("categories", initialValues, "_id=-1", null);
        }

        if (oldVersion < 32) {
            db.execSQL("ALTER TABLE accounts add column grouping text not null check (grouping in "
                    + "('NONE','DAY','WEEK','MONTH','YEAR')) default 'NONE'");
        }

        if (oldVersion < 33) {
            db.execSQL("ALTER TABLE accounts add column usages integer default 0");
            db.execSQL(
                    "UPDATE accounts SET usages = (SELECT count(*) FROM transactions WHERE account_id = accounts._id AND parent_id IS null)");
        }

        if (oldVersion < 34) {
            //fix for https://github.com/mtotschnig/MyExpenses/issues/69
            db.execSQL(
                    "UPDATE transactions set date = (SELECT date from transactions parent WHERE parent._id = transactions.parent_id) WHERE parent_id IS NOT null");
        }

        if (oldVersion < 35) {
            db.execSQL(
                    "ALTER TABLE transactions add column cr_status text not null check (cr_status in ('UNRECONCILED','CLEARED','RECONCILED')) default 'UNRECONCILED'");
        }

        if (oldVersion < 36) {
            //move payee field in transactions from text to foreign key
            db.execSQL("ALTER TABLE transactions RENAME to transactions_old");
            db.execSQL("CREATE TABLE transactions (" + " _id integer primary key autoincrement,"
                    + " comment text, date datetime not null," + " amount integer not null,"
                    + " cat_id integer references categories(_id),"
                    + " account_id integer not null references accounts(_id),"
                    + " payee_id integer references payee(_id),"
                    + " transfer_peer integer references transactions(_id),"
                    + " transfer_account integer references accounts(_id),"
                    + " method_id integer references paymentmethods(_id),"
                    + " parent_id integer references transactions(_id)," + " status integer default 0,"
                    + " cr_status text not null check (cr_status in ('UNRECONCILED','CLEARED','RECONCILED')) default 'RECONCILED')");
            //insert all payees that are stored in transactions, but are not in payee
            db.execSQL(
                    "INSERT INTO payee (name) SELECT DISTINCT payee FROM transactions_old WHERE payee != '' AND NOT exists (SELECT 1 FROM payee WHERE name=transactions_old.payee)");
            db.execSQL("INSERT INTO transactions "
                    + "(_id,comment,date,amount,cat_id,account_id,payee_id,transfer_peer,transfer_account,method_id,parent_id,status,cr_status) "
                    + "SELECT " + "_id, " + "comment, " + "date, " + "amount, " + "cat_id, " + "account_id, "
                    + "(SELECT _id from payee WHERE name = payee), " + "transfer_peer, " + "transfer_account, "
                    + "method_id," + "parent_id," + "status," + "cr_status " + "FROM transactions_old");
            db.execSQL("DROP TABLE transactions_old");

            //move payee field in templates from text to foreign key
            db.execSQL("ALTER TABLE templates RENAME to templates_old");
            db.execSQL("CREATE TABLE templates (" + " _id integer primary key autoincrement," + " comment text,"
                    + " amount integer not null," + " cat_id integer references categories(_id),"
                    + " account_id integer not null references accounts(_id),"
                    + " payee_id integer references payee(_id)," + " transfer_peer boolean default false,"
                    + " transfer_account integer references accounts(_id),"
                    + " method_id integer references paymentmethods(_id)," + " title text not null,"
                    + " usages integer default 0," + " unique(account_id,title));");
            //insert all payees that are stored in templates, but are not in payee
            db.execSQL(
                    "INSERT INTO payee (name) SELECT DISTINCT payee FROM templates_old WHERE payee != '' AND NOT exists (SELECT 1 FROM payee WHERE name=templates_old.payee)");
            db.execSQL("INSERT INTO templates "
                    + "(_id,comment,amount,cat_id,account_id,payee_id,transfer_peer,transfer_account,method_id,title,usages) "
                    + "SELECT " + "_id, " + "comment, " + "amount, " + "cat_id, " + "account_id, "
                    + "(SELECT _id from payee WHERE name = payee), " + "transfer_peer, " + "transfer_account, "
                    + "method_id," + "title," + "usages " + "FROM templates_old");
            db.execSQL("DROP TABLE templates_old");

            db.execSQL("DROP VIEW IF EXISTS committed");
            db.execSQL("DROP VIEW IF EXISTS uncommitted");
            //for the definition of the view, it is safe to rely on the constants,
            //since we will not alter the view, but drop it, and recreate it, if needed
            //      String viewTransactions = VIEW_DEFINITION(TABLE_TRANSACTIONS);
            //      db.execSQL("CREATE VIEW transactions_committed "  + viewTransactions + " WHERE " + KEY_STATUS + " != " + STATUS_UNCOMMITTED + ";");
            //      db.execSQL("CREATE VIEW transactions_uncommitted" + viewTransactions + " WHERE " + KEY_STATUS +  " = " + STATUS_UNCOMMITTED + ";");
            //      db.execSQL("CREATE VIEW transactions_all" + viewTransactions);
            //      db.execSQL("CREATE VIEW templates_all" +  VIEW_DEFINITION(TABLE_TEMPLATES));
        }

        if (oldVersion < 37) {
            db.execSQL("ALTER TABLE transactions add column number text");
            db.execSQL("ALTER TABLE paymentmethods add column is_numbered boolean default 0");
            ContentValues initialValues = new ContentValues();
            initialValues.put("is_numbered", true);
            db.update("paymentmethods", initialValues, "label = ?", new String[] { "CHEQUE" });
        }

        if (oldVersion < 38) {
            db.execSQL("ALTER TABLE templates add column plan_id integer");
            db.execSQL("ALTER TABLE templates add column plan_execution boolean default 0");
        }

        if (oldVersion < 39) {
            //      db.execSQL("CREATE VIEW transactions_extended" + VIEW_DEFINITION_EXTENDED(TABLE_TRANSACTIONS) + " WHERE " + KEY_STATUS + " != " + STATUS_UNCOMMITTED + ";");
            //      db.execSQL("CREATE VIEW templates_extended" +  VIEW_DEFINITION_EXTENDED(TABLE_TEMPLATES));
            db.execSQL(
                    "CREATE TABLE currency (_id integer primary key autoincrement, code text unique not null);");
            insertCurrencies(db);
        }

        if (oldVersion < 40) {
            //added currency to extended view
            db.execSQL("DROP VIEW IF EXISTS transactions_extended");
            db.execSQL("DROP VIEW IF EXISTS templates_extended");
            //      db.execSQL("CREATE VIEW transactions_extended" + VIEW_DEFINITION_EXTENDED(TABLE_TRANSACTIONS) + " WHERE " + KEY_STATUS + " != " + STATUS_UNCOMMITTED + ";");
            //      db.execSQL("CREATE VIEW templates_extended" +  VIEW_DEFINITION_EXTENDED(TABLE_TEMPLATES));
        }

        if (oldVersion < 41) {
            db.execSQL("CREATE TABLE planinstance_transaction "
                    + "(template_id integer references templates(_id), " + "instance_id integer, "
                    + "transaction_id integer references transactions(_id), "
                    + "primary key (instance_id,transaction_id));");
        }

        if (oldVersion < 42) {
            //migrate date field to unix time stamp (UTC)
            db.execSQL("ALTER TABLE transactions RENAME to transactions_old");
            db.execSQL("CREATE TABLE transactions (" + " _id integer primary key autoincrement,"
                    + " comment text, date datetime not null," + " amount integer not null,"
                    + " cat_id integer references categories(_id),"
                    + " account_id integer not null references accounts(_id),"
                    + " payee_id integer references payee(_id),"
                    + " transfer_peer integer references transactions(_id),"
                    + " transfer_account integer references accounts(_id),"
                    + " method_id integer references paymentmethods(_id),"
                    + " parent_id integer references transactions(_id)," + " status integer default 0,"
                    + " cr_status text not null check (cr_status in ('UNRECONCILED','CLEARED','RECONCILED')) default 'RECONCILED',"
                    + " number text)");
            db.execSQL("INSERT INTO transactions "
                    + "(_id,comment,date,amount,cat_id,account_id,payee_id,transfer_peer,transfer_account,method_id,parent_id,status,cr_status,number) "
                    + "SELECT " + "_id, " + "comment, " + "strftime('%s',date,'utc'), " + "amount, "
                    + "cat_id, " + "account_id, " + "payee_id, " + "transfer_peer, " + "transfer_account, "
                    + "method_id," + "parent_id," + "status," + "cr_status, " + "number "
                    + "FROM transactions_old");
            db.execSQL("DROP TABLE transactions_old");
        }

        if (oldVersion < 43) {
            db.execSQL("UPDATE accounts set currency = 'ZMW' WHERE currency = 'ZMK'");
            db.execSQL("UPDATE currency set code = 'ZMW' WHERE code = 'ZMK'");
        }

        if (oldVersion < 44) {
            //add ON DELETE CASCADE
            //accounts table sort_key column
            db.execSQL("ALTER TABLE planinstance_transaction RENAME to planinstance_transaction_old");
            db.execSQL("CREATE TABLE planinstance_transaction "
                    + "(template_id integer references templates(_id) ON DELETE CASCADE, "
                    + "instance_id integer, "
                    + "transaction_id integer references transactions(_id) ON DELETE CASCADE, "
                    + "primary key (instance_id,transaction_id));");
            db.execSQL("INSERT INTO planinstance_transaction " + "(template_id,instance_id,transaction_id)"
                    + "SELECT " + "template_id,instance_id,transaction_id FROM planinstance_transaction_old");
            db.execSQL("DROP TABLE planinstance_transaction_old");
            db.execSQL("ALTER TABLE transactions RENAME to transactions_old");
            db.execSQL("CREATE TABLE transactions (" + " _id integer primary key autoincrement,"
                    + " comment text, date datetime not null," + " amount integer not null,"
                    + " cat_id integer references categories(_id),"
                    + " account_id integer not null references accounts(_id) ON DELETE CASCADE,"
                    + " payee_id integer references payee(_id),"
                    + " transfer_peer integer references transactions(_id),"
                    + " transfer_account integer references accounts(_id),"
                    + " method_id integer references paymentmethods(_id),"
                    + " parent_id integer references transactions(_id) ON DELETE CASCADE,"
                    + " status integer default 0,"
                    + " cr_status text not null check (cr_status in ('UNRECONCILED','CLEARED','RECONCILED')) default 'RECONCILED',"
                    + " number text)");
            db.execSQL("INSERT INTO transactions "
                    + "(_id,comment,date,amount,cat_id,account_id,payee_id,transfer_peer,transfer_account,method_id,parent_id,status,cr_status,number) "
                    + "SELECT " + "_id, " + "comment, " + "date, " + "amount, " + "cat_id, " + "account_id, "
                    + "payee_id, " + "transfer_peer, " + "transfer_account, " + "method_id," + "parent_id,"
                    + "status," + "cr_status, " + "number " + "FROM transactions_old");
            db.execSQL("DROP TABLE transactions_old");
            db.execSQL("ALTER TABLE templates RENAME to templates_old");
            db.execSQL("CREATE TABLE templates (" + " _id integer primary key autoincrement," + " comment text,"
                    + " amount integer not null," + " cat_id integer references categories(_id),"
                    + " account_id integer not null references accounts(_id) ON DELETE CASCADE,"
                    + " payee_id integer references payee(_id)," + " transfer_peer boolean default 0,"
                    + " transfer_account integer references accounts(_id) ON DELETE CASCADE,"
                    + " method_id integer references paymentmethods(_id)," + " title text not null,"
                    + " usages integer default 0," + " plan_id integer, "
                    + " plan_execution boolean default 0, " + " unique(account_id,title));");
            db.execSQL("INSERT INTO templates "
                    + "(_id,comment,amount,cat_id,account_id,payee_id,transfer_peer,transfer_account,method_id,title,usages,plan_id,plan_execution) "
                    + "SELECT " + "_id, " + "comment, " + "amount, " + "cat_id, " + "account_id, "
                    + "payee_id, " + "transfer_peer, " + "transfer_account, " + "method_id," + "title,"
                    + "usages, " + "plan_id, " + "plan_execution " + "FROM templates_old");
            db.execSQL("ALTER TABLE accounts add column sort_key integer");
        }

        if (oldVersion < 45) {
            db.execSQL("ALTER TABLE accounts add column exclude_from_totals boolean default 0");
            //added  to extended view
            db.execSQL("DROP VIEW IF EXISTS transactions_extended");
            db.execSQL("DROP VIEW IF EXISTS templates_extended");
            //      db.execSQL("CREATE VIEW transactions_extended" + VIEW_DEFINITION_EXTENDED(TABLE_TRANSACTIONS) + " WHERE " + KEY_STATUS + " != " + STATUS_UNCOMMITTED + ";");
            //      db.execSQL("CREATE VIEW templates_extended" +  VIEW_DEFINITION_EXTENDED(TABLE_TEMPLATES));
        }

        if (oldVersion < 46) {
            db.execSQL("ALTER TABLE payee add column name_normalized text");
            Cursor c = db.query("payee", new String[] { "_id", "name" }, null, null, null, null, null);
            if (c != null) {
                if (c.moveToFirst()) {
                    ContentValues v = new ContentValues();
                    while (c.getPosition() < c.getCount()) {
                        v.put("name_normalized", Utils.normalize(c.getString(1)));
                        db.update("payee", v, "_id = " + c.getLong(0), null);
                        c.moveToNext();
                    }
                }
                c.close();
            }
        }

        if (oldVersion < 47) {
            db.execSQL("ALTER TABLE templates add column uuid text");
            db.execSQL(EVENT_CACHE_CREATE);
        }

        if (oldVersion < 48) {
            //added method_label to extended view
            //do not comment out, since it is needed by the uuid update
            refreshViews(db);
            //need to inline to protect against later renames

            if (oldVersion < 47) {
                String[] projection = new String[] { "templates._id", "amount", "comment", "cat_id",
                        "CASE WHEN " + "  " + "transfer_peer" + " " + " THEN " + "  (SELECT " + "label"
                                + " FROM " + "accounts" + " WHERE " + "_id" + " = " + "transfer_account" + ") "
                                + " ELSE " + " CASE WHEN " + " (SELECT " + "parent_id" + " FROM " + "categories"
                                + " WHERE " + "_id" + " = " + "cat_id" + ") " + " THEN " + " (SELECT " + "label"
                                + " FROM " + "categories" + " WHERE " + "_id" + " = " + " (SELECT "
                                + "parent_id" + " FROM " + "categories" + " WHERE " + "_id" + " = " + "cat_id"
                                + ")) " + "  || ' : ' || " + " (SELECT " + "label" + " FROM " + "categories"
                                + " WHERE " + "_id" + " = " + "cat_id" + ") " + " ELSE" + " (SELECT " + "label"
                                + " FROM " + "categories" + " WHERE " + "_id" + " = " + "cat_id" + ") "
                                + " END " + " END AS  " + "label",
                        "name", "transfer_peer", "transfer_account", "account_id", "method_id",
                        "paymentmethods.label AS method_label", "title", "plan_id", "plan_execution", "uuid",
                        "currency" };
                SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
                qb.setTables("templates LEFT JOIN payee ON payee_id = payee._id"
                        + " LEFT JOIN accounts ON account_id = accounts._id"
                        + " LEFT JOIN paymentmethods ON method_id = paymentmethods._id");
                Cursor c = qb.query(db, projection, null, null, null, null, null);
                if (c != null) {
                    if (c.moveToFirst()) {
                        ContentValues templateValues = new ContentValues(), eventValues = new ContentValues();
                        String planCalendarId = MyApplication.getInstance().checkPlanner();
                        while (c.getPosition() < c.getCount()) {
                            Template t = new Template(c);
                            templateValues.put(DatabaseConstants.KEY_UUID, t.getUuid());
                            long templateId = c.getLong(c.getColumnIndex("_id"));
                            long planId = c.getLong(c.getColumnIndex("plan_id"));
                            eventValues.put(Events.DESCRIPTION, t.compileDescription(mCtx));
                            db.update("templates", templateValues, "_id = " + templateId, null);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                                try {
                                    mCtx.getContentResolver().update(Events.CONTENT_URI, eventValues,
                                            Events._ID + "= ? AND " + Events.CALENDAR_ID + " = ?",
                                            new String[] { String.valueOf(planId), planCalendarId });
                                } catch (Exception e) {
                                    //fails with IllegalArgumentException on 2.x devices,
                                    //since the same uri works for inserting and querying
                                    //but also on HUAWEI Y530-U00 with 4.3
                                    //probably SecurityException could arise here
                                }
                            }
                            c.moveToNext();
                        }
                    }
                    c.close();
                }
            }
        }

        if (oldVersion < 49) {
            //forgotten to drop in previous upgrade
            db.execSQL("DROP TABLE IF EXISTS templates_old");
        }

        if (oldVersion < 50) {
            db.execSQL("ALTER TABLE transactions add column picture_id text");
            db.execSQL("DROP TABLE IF EXISTS feature_used");
        }

        if (oldVersion < 51) {
            File pictureDir = Utils.getPictureDir(false);
            //fallback if not mounted
            if (pictureDir == null) {
                pictureDir = new File(
                        Environment.getExternalStorageDirectory().getPath() + "/Android/data/"
                                + MyApplication.getInstance().getPackageName() + "/files",
                        Environment.DIRECTORY_PICTURES);
            }
            if (!pictureDir.exists()) {
                AcraHelper.report(new Exception("Unable to calculate pictureDir during upgrade"));
            }
            //if pictureDir does not exist, we use its URI nonetheless, in order to have the data around
            //for potential trouble handling
            String prefix = Uri.fromFile(pictureDir).toString() + "/";
            String postfix = ".jpg";
            //if picture_id concat expression will also be null
            db.execSQL("UPDATE transactions set picture_id = '" + prefix + "'||picture_id||'" + postfix + "'");

            db.execSQL("CREATE TABLE stale_uris ( picture_id text);");
            db.execSQL(
                    "CREATE TRIGGER cache_stale_uri BEFORE DELETE ON transactions WHEN old.picture_id NOT NULL "
                            + " BEGIN INSERT INTO stale_uris VALUES (old.picture_id); END");
        }

        if (oldVersion < 52) {
            db.execSQL("CREATE INDEX transactions_cat_id_index on transactions(cat_id)");
            db.execSQL("CREATE INDEX templates_cat_id_index on templates(cat_id)");
        }

        if (oldVersion < 53) {
            //add VOID status
            db.execSQL("ALTER TABLE transactions RENAME to transactions_old");
            db.execSQL("CREATE TABLE " + "transactions" + "( " + "_id" + " integer primary key autoincrement, "
                    + "comment" + " text, " + "date" + " datetime not null, " + "amount" + " integer not null, "
                    + "cat_id" + " integer references " + "categories" + "(" + "_id" + "), " + "account_id"
                    + " integer not null references " + "accounts" + "(" + "_id" + ") ON DELETE CASCADE,"
                    + "payee_id" + " integer references " + "payee" + "(" + "_id" + "), " + "transfer_peer"
                    + " integer references " + "transactions" + "(" + "_id" + "), " + "transfer_account"
                    + " integer references " + "accounts" + "(" + "_id" + ")," + "method_id"
                    + " integer references " + "paymentmethods" + "(" + "_id" + ")," + "parent_id"
                    + " integer references " + "transactions" + "(" + "_id" + ") ON DELETE CASCADE, " + "status"
                    + " integer default 0, " + "cr_status" + " text not null check (" + "cr_status"
                    + " in ('UNRECONCILED','CLEARED','RECONCILED','VOID')) default 'RECONCILED', " + "number"
                    + " text, " + "picture_id" + " text);");
            db.execSQL("INSERT INTO transactions "
                    + "(_id,comment,date,amount,cat_id,account_id,payee_id,transfer_peer,transfer_account,method_id,parent_id,status,cr_status,number,picture_id) "
                    + "SELECT " + "_id, " + "comment, " + "date, " + "amount, " + "cat_id, " + "account_id, "
                    + "payee_id, " + "transfer_peer, " + "transfer_account, " + "method_id," + "parent_id,"
                    + "status," + "cr_status, " + "number, " + "picture_id " + "FROM transactions_old");
            db.execSQL("DROP TABLE transactions_old");
            db.execSQL(
                    "CREATE TRIGGER cache_stale_uri BEFORE DELETE ON transactions WHEN old.picture_id NOT NULL "
                            + " BEGIN INSERT INTO stale_uris VALUES (old.picture_id); END");
            db.execSQL("CREATE INDEX transactions_cat_id_index on transactions(cat_id)");
        }

        if (oldVersion < 54) {
            db.execSQL("DROP TRIGGER cache_stale_uri");
            db.execSQL("CREATE TRIGGER cache_stale_uri " + "AFTER DELETE ON " + "transactions" + " "
                    + "WHEN old." + "picture_id" + " NOT NULL " + "AND NOT EXISTS " + "(SELECT 1 FROM "
                    + "transactions" + " " + "WHERE " + "picture_id" + " = old." + "picture_id" + ") "
                    + "BEGIN INSERT INTO " + "stale_uris" + " VALUES (old." + "picture_id" + "); END");
            //all Accounts with old default color are updated to the new one
            db.execSQL(String.format(Locale.US, "UPDATE accounts set color = %d WHERE color = %d", 0xff009688,
                    0xff99CC00));
        }

        if (oldVersion < 55) {
            db.execSQL("ALTER TABLE categories add column label_normalized text");
            Cursor c = db.query("categories", new String[] { "_id", "label" }, null, null, null, null, null);
            if (c != null) {
                if (c.moveToFirst()) {
                    ContentValues v = new ContentValues();
                    while (c.getPosition() < c.getCount()) {
                        v.put("label_normalized", Utils.normalize(c.getString(1)));
                        db.update("categories", v, "_id = " + c.getLong(0), null);
                        c.moveToNext();
                    }
                }
                c.close();
            }
        }

        if (oldVersion < 56) {
            db.execSQL("ALTER TABLE templates add column last_used datetime");
            db.execSQL("ALTER TABLE categories add column last_used datetime");
            db.execSQL("ALTER TABLE accounts add column last_used datetime");
            db.execSQL("CREATE TRIGGER sort_key_default AFTER INSERT ON accounts "
                    + "BEGIN UPDATE accounts SET sort_key = (SELECT coalesce(max(sort_key),0) FROM accounts) + 1 "
                    + "WHERE _id = NEW._id; END");
            //The sort key could be set by user in previous versions, now it is handled internally
            Cursor c = db.query("accounts", new String[] { "_id", "sort_key" }, null, null, null, null,
                    "sort_key ASC");
            boolean hasAccountSortKeySet = false;
            if (c != null) {
                if (c.moveToFirst()) {
                    ContentValues v = new ContentValues();
                    while (c.getPosition() < c.getCount()) {
                        v.put("sort_key", c.getPosition() + 1);
                        db.update("accounts", v, "_id = ?", new String[] { c.getString(0) });
                        if (c.getInt(1) != 0)
                            hasAccountSortKeySet = true;
                        c.moveToNext();
                    }
                }
                c.close();
            }
            String legacy = PrefKey.SORT_ORDER_LEGACY.getString("USAGES");
            PrefKey.SORT_ORDER_TEMPLATES.putString(legacy);
            PrefKey.SORT_ORDER_CATEGORIES.putString(legacy);
            PrefKey.SORT_ORDER_ACCOUNTS.putString(hasAccountSortKeySet ? "CUSTOM" : legacy);
            PrefKey.SORT_ORDER_LEGACY.remove();
        }
    } catch (SQLException e) {
        throw Utils.hasApiLevel(Build.VERSION_CODES.JELLY_BEAN)
                ? new SQLiteUpgradeFailedException("Database upgrade failed", e)
                : e;
    }

    if (oldVersion < 57) {
        //fix custom app uris
        if (ContextCompat.checkSelfPermission(mCtx,
                Manifest.permission.WRITE_CALENDAR) == PackageManager.PERMISSION_GRANTED) {
            Cursor c = db.query("templates", new String[] { "_id", "plan_id" }, "plan_id IS NOT null", null,
                    null, null, null);
            if (c != null) {
                if (c.moveToFirst()) {
                    while (!c.isAfterLast()) {
                        Plan.updateCustomAppUri(c.getLong(1), Template.buildCustomAppUri(c.getLong(0)));
                        c.moveToNext();
                    }
                }
                c.close();
            }
        }

        //Drop unique constraint on templates

        db.execSQL("ALTER TABLE templates RENAME to templates_old");
        db.execSQL("CREATE TABLE templates (" + " _id integer primary key autoincrement," + " comment text,"
                + " amount integer not null," + " cat_id integer references categories(_id),"
                + " account_id integer not null references accounts(_id) ON DELETE CASCADE,"
                + " payee_id integer references payee(_id)," + " transfer_peer boolean default 0,"
                + " transfer_account integer references accounts(_id) ON DELETE CASCADE,"
                + " method_id integer references paymentmethods(_id)," + " title text not null,"
                + " usages integer default 0," + " plan_id integer, " + " plan_execution boolean default 0, "
                + " uuid text, " + " last_used datetime);");
        db.execSQL("INSERT INTO templates "
                + "(_id,comment,amount,cat_id,account_id,payee_id,transfer_peer,transfer_account,method_id,title,usages,plan_id,plan_execution,uuid,last_used) "
                + "SELECT " + "_id, " + "comment, " + "amount, " + "cat_id, " + "account_id, " + "payee_id, "
                + "transfer_peer, " + "transfer_account, " + "method_id," + "title," + "usages, " + "plan_id, "
                + "plan_execution, uuid, last_used " + "FROM templates_old");
        db.execSQL("DROP TABLE templates_old");
        //Recreate changed views
        refreshViews(db);
    }

    if (oldVersion < 58) {
        //cache fraction digits
        Cursor c = db.rawQuery("SELECT distinct currency from accounts", null);
        if (c != null) {
            if (c.moveToFirst()) {
                while (!c.isAfterLast()) {
                    Money.ensureFractionDigitsAreCached(Utils.getSaveInstance(c.getString(0)));
                    c.moveToNext();
                }
            }
            c.close();
        }
    }
}

From source file:org.servalproject.maps.bridge.tasks.BatchUploadTask.java

private void uploadJson() {

    // update the display
    updateUi = true;//from  w w  w. ja  va 2  s.  c o  m
    publishProgress(0);

    // get the upload URL
    SharedPreferences mPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    String uploadUrl = mPreferences.getString("preferences_upload_url", null);
    mPreferences = null;

    boolean mUploadStatus = false;

    // get the list of stuff to upload
    String[] mProjection = new String[2];
    mProjection[0] = LogContract.Table._ID;
    mProjection[1] = LogContract.Table.JSON_CONTENT;

    String mSelection = LogContract.Table.UPLOAD_STATUS + " = ?";
    String mSelectionArgs[] = new String[1];
    mSelectionArgs[0] = Integer.toString(LogContract.UPLOAD_PENDING_FLAG);

    ContentValues mUpdateValues;

    Cursor mCursor = contentResolver.query(LogContract.CONTENT_URI, mProjection, mSelection, mSelectionArgs,
            null);

    // loop through the cursor
    while (mCursor.moveToNext()) {

        if (V_LOG) {
            Log.v(sTag, "attempting upload of record: "
                    + mCursor.getString(mCursor.getColumnIndex(LogContract.Table._ID)));
        }

        mUploadStatus = BasicHttpUploader.doBasicPost(uploadUrl,
                mCursor.getString(mCursor.getColumnIndex(mProjection[1])));

        // update the selection criteria for the update
        mSelection = LogContract.Table._ID + " = ?";
        mSelectionArgs = new String[1];
        mSelectionArgs[0] = mCursor.getString(mCursor.getColumnIndex(LogContract.Table._ID));

        if (mUploadStatus) {
            // the upload was a success
            mUpdateValues = new ContentValues();
            mUpdateValues.put(LogContract.Table.UPLOAD_STATUS, LogContract.UPLOAD_SUCCESS_FLAG);
            mUpdateValues.put(LogContract.Table.TIMESTAMP, System.currentTimeMillis());
        } else {
            // the upload was a failure
            mUpdateValues = new ContentValues();
            mUpdateValues.put(LogContract.Table.UPLOAD_STATUS, LogContract.UPLOAD_FAILED_FLAG);
            mUpdateValues.put(LogContract.Table.TIMESTAMP, System.currentTimeMillis());
        }

        // update the log entry
        contentResolver.update(LogContract.CONTENT_URI, mUpdateValues, mSelection, mSelectionArgs);

        publishProgress(mCursor.getPosition());
    }

    mCursor.close();

}

From source file:edu.stanford.mobisocial.dungbeetle.model.DbObject.java

/**
 * @param v the view to bind//from  www  .  ja  va2  s .  c o  m
 * @param context standard activity context
 * @param c the cursor source for the object in the db object table.
 * Must include _id in the projection.
 * 
 * @param allowInteractions controls whether the bound view is
 * allowed to intercept touch events and do its own processing.
 */
public static void bindView(View v, final Context context, Cursor cursor, boolean allowInteractions) {
    TextView nameText = (TextView) v.findViewById(R.id.name_text);
    ViewGroup frame = (ViewGroup) v.findViewById(R.id.object_content);
    frame.removeAllViews();

    // make sure we have all the columns we need
    Long objId = cursor.getLong(cursor.getColumnIndexOrThrow(DbObj.COL_ID));
    String[] projection = null;
    String selection = DbObj.COL_ID + " = ?";
    String[] selectionArgs = new String[] { Long.toString(objId) };
    String sortOrder = null;
    Cursor c = context.getContentResolver().query(DbObj.OBJ_URI, projection, selection, selectionArgs,
            sortOrder);
    if (!c.moveToFirst()) {
        Log.w(TAG, "could not find obj " + objId);
        c.close();
        return;
    }
    DbObj obj = App.instance().getMusubi().objForCursor(c);
    if (obj == null) {
        nameText.setText("Failed to access database.");
        Log.e("DbObject", "cursor was null for bindView of DbObject");
        return;
    }
    DbUser sender = obj.getSender();
    Long timestamp = c.getLong(c.getColumnIndexOrThrow(DbObj.COL_TIMESTAMP));
    Long hash = obj.getHash();
    short deleted = c.getShort(c.getColumnIndexOrThrow(DELETED));
    String feedName = obj.getFeedName();
    String type = obj.getType();
    Date date = new Date(timestamp);
    c.close();
    c = null;

    if (sender == null) {
        nameText.setText("Message from unknown contact.");
        return;
    }
    nameText.setText(sender.getName());

    final ImageView icon = (ImageView) v.findViewById(R.id.icon);
    if (sViewProfileAction == null) {
        sViewProfileAction = new OnClickViewProfile((Activity) context);
    }
    icon.setTag(sender.getLocalId());
    if (allowInteractions) {
        icon.setOnClickListener(sViewProfileAction);
        v.setTag(objId);
    }
    icon.setImageBitmap(sender.getPicture());

    if (deleted == 1) {
        v.setBackgroundColor(sDeletedColor);
    } else {
        v.setBackgroundColor(Color.TRANSPARENT);
    }

    TextView timeText = (TextView) v.findViewById(R.id.time_text);
    timeText.setText(RelativeDate.getRelativeDate(date));

    frame.setTag(objId); // TODO: error prone! This is database id
    frame.setTag(R.id.object_entry, cursor.getPosition()); // this is cursor id
    FeedRenderer renderer = DbObjects.getFeedRenderer(type);
    if (renderer != null) {
        renderer.render(context, frame, obj, allowInteractions);
    }

    if (!allowInteractions) {
        v.findViewById(R.id.obj_attachments_icon).setVisibility(View.GONE);
        v.findViewById(R.id.obj_attachments).setVisibility(View.GONE);
    } else {
        if (!MusubiBaseActivity.isDeveloperModeEnabled(context)) {
            v.findViewById(R.id.obj_attachments_icon).setVisibility(View.GONE);
            v.findViewById(R.id.obj_attachments).setVisibility(View.GONE);
        } else {
            ImageView attachmentCountButton = (ImageView) v.findViewById(R.id.obj_attachments_icon);
            TextView attachmentCountText = (TextView) v.findViewById(R.id.obj_attachments);
            attachmentCountButton.setVisibility(View.VISIBLE);

            if (hash == 0) {
                attachmentCountButton.setVisibility(View.GONE);
            } else {
                //int color = DbObject.colorFor(hash);
                boolean selfPost = false;
                DBHelper helper = new DBHelper(context);
                try {
                    Cursor attachments = obj.getSubfeed().query("type=?", new String[] { LikeObj.TYPE });
                    try {
                        attachmentCountText.setText("+" + attachments.getCount());

                        if (attachments.moveToFirst()) {
                            while (!attachments.isAfterLast()) {
                                if (attachments.getInt(attachments.getColumnIndex(CONTACT_ID)) == -666) {
                                    selfPost = true;
                                    break;
                                }
                                attachments.moveToNext();

                            }
                        }
                    } finally {
                        attachments.close();
                    }
                } finally {
                    helper.close();
                }
                if (selfPost) {
                    attachmentCountButton.setImageResource(R.drawable.ic_menu_love_red);
                } else {
                    attachmentCountButton.setImageResource(R.drawable.ic_menu_love);
                }
                attachmentCountText.setTag(R.id.object_entry, hash);
                attachmentCountText.setTag(R.id.feed_label, Feed.uriForName(feedName));
                attachmentCountText.setOnClickListener(LikeListener.getInstance(context));
            }
        }
    }
}

From source file:net.openwatch.acluaz.adapter.IncidentAdapter.java

@Override
public void bindView(View view, Context context, Cursor cursor) {
    super.bindView(view, context, cursor);

    ViewCache view_cache = (ViewCache) view.getTag(R.id.list_item_cache);
    if (view_cache == null) {
        view_cache = new ViewCache();
        view_cache.date = (TextView) view.findViewById(R.id.date);
        view_cache.location = (TextView) view.findViewById(R.id.location);
        view_cache.submitted = (TextView) view.findViewById(R.id.submitted);
        view_cache.container = (ViewGroup) view.findViewById(R.id.container);

        view_cache.date_col = cursor.getColumnIndexOrThrow(DBConstants.DATE);
        view_cache.location_col = cursor.getColumnIndexOrThrow(DBConstants.LOCATION);
        view_cache.submitted_col = cursor.getColumnIndexOrThrow(DBConstants.SUBMITTED);
        view_cache._id_col = cursor.getColumnIndexOrThrow(DBConstants.ID);
        view.setTag(R.id.list_item_cache, view_cache);
    }//from   ww w  .ja  v a2  s  .c om

    view_cache.date.setText(cursor.getString(view_cache.date_col));
    if (cursor.getString(view_cache.location_col).compareTo("") != 0) {
        view_cache.location.setText(cursor.getString(view_cache.location_col));
        view_cache.location.setVisibility(View.VISIBLE);
    } else {
        view_cache.location.setVisibility(View.GONE);
    }
    if (cursor.getInt(view_cache.submitted_col) == 1) {
        view_cache.submitted.setTextColor(c.getResources().getColor(R.color.submitted));
        view_cache.submitted.setText(R.string.incident_submitted);
    } else {
        view_cache.submitted.setTextColor(c.getResources().getColor(R.color.not_submitted));
        view_cache.submitted.setText(R.string.incident_not_submitted);
    }
    //Log.i("OWLocalRecordingAdapter", "got id: " + String.valueOf(cursor.getInt(view_cache._id_col)));
    view.setTag(R.id.list_item_model, cursor.getInt(view_cache._id_col));

    if (cursor.getPosition() % 2 == 0) {
        view_cache.container.setBackgroundResource(R.drawable.list_bg_1);
    } else {
        view_cache.container.setBackgroundResource(R.drawable.list_bg_2);
    }
}

From source file:com.android.messaging.datamodel.MessageNotificationState.java

/**
 * Check for failed messages and post notifications as needed.
 * TODO: Rewrite this as a NotificationState.
 */// w  w w  .  jav  a2s.  c o m
public static void checkFailedMessages() {
    final DatabaseWrapper db = DataModel.get().getDatabase();

    final Cursor messageDataCursor = db.query(DatabaseHelper.MESSAGES_TABLE, MessageData.getProjection(),
            FailedMessageQuery.FAILED_MESSAGES_WHERE_CLAUSE, null /*selectionArgs*/, null /*groupBy*/,
            null /*having*/, FailedMessageQuery.FAILED_ORDER_BY);

    try {
        final Context context = Factory.get().getApplicationContext();
        final Resources resources = context.getResources();
        final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
        if (messageDataCursor != null) {
            final MessageData messageData = new MessageData();

            final HashSet<String> conversationsWithFailedMessages = new HashSet<String>();

            // track row ids in case we want to display something that requires this
            // information
            final ArrayList<Integer> failedMessages = new ArrayList<Integer>();

            int cursorPosition = -1;
            final long when = 0;

            messageDataCursor.moveToPosition(-1);
            while (messageDataCursor.moveToNext()) {
                messageData.bind(messageDataCursor);

                final String conversationId = messageData.getConversationId();
                if (DataModel.get().isNewMessageObservable(conversationId)) {
                    // Don't post a system notification for an observable conversation
                    // because we already show an angry red annotation in the conversation
                    // itself or in the conversation preview snippet.
                    continue;
                }

                cursorPosition = messageDataCursor.getPosition();
                failedMessages.add(cursorPosition);
                conversationsWithFailedMessages.add(conversationId);
            }

            if (LogUtil.isLoggable(TAG, LogUtil.DEBUG)) {
                LogUtil.d(TAG, "Found " + failedMessages.size() + " failed messages");
            }
            if (failedMessages.size() > 0) {
                final NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

                CharSequence line1;
                CharSequence line2;
                final boolean isRichContent = false;
                ConversationIdSet conversationIds = null;
                PendingIntent destinationIntent;
                if (failedMessages.size() == 1) {
                    messageDataCursor.moveToPosition(cursorPosition);
                    messageData.bind(messageDataCursor);
                    final String conversationId = messageData.getConversationId();

                    // We have a single conversation, go directly to that conversation.
                    destinationIntent = UIIntents.get().getPendingIntentForConversationActivity(context,
                            conversationId, null /*draft*/);

                    conversationIds = ConversationIdSet.createSet(conversationId);

                    final String failedMessgeSnippet = messageData.getMessageText();
                    int failureStringId;
                    if (messageData.getStatus() == MessageData.BUGLE_STATUS_INCOMING_DOWNLOAD_FAILED) {
                        failureStringId = R.string.notification_download_failures_line1_singular;
                    } else {
                        failureStringId = R.string.notification_send_failures_line1_singular;
                    }
                    line1 = resources.getString(failureStringId);
                    line2 = failedMessgeSnippet;
                    // Set rich text for non-SMS messages or MMS push notification messages
                    // which we generate locally with rich text
                    // TODO- fix this
                    //                        if (messageData.isMmsInd()) {
                    //                            isRichContent = true;
                    //                        }
                } else {
                    // We have notifications for multiple conversation, go to the conversation
                    // list.
                    destinationIntent = UIIntents.get().getPendingIntentForConversationListActivity(context);

                    int line1StringId;
                    int line2PluralsId;
                    if (messageData.getStatus() == MessageData.BUGLE_STATUS_INCOMING_DOWNLOAD_FAILED) {
                        line1StringId = R.string.notification_download_failures_line1_plural;
                        line2PluralsId = R.plurals.notification_download_failures;
                    } else {
                        line1StringId = R.string.notification_send_failures_line1_plural;
                        line2PluralsId = R.plurals.notification_send_failures;
                    }
                    line1 = resources.getString(line1StringId);
                    line2 = resources.getQuantityString(line2PluralsId, conversationsWithFailedMessages.size(),
                            failedMessages.size(), conversationsWithFailedMessages.size());
                }
                line1 = applyWarningTextColor(context, line1);
                line2 = applyWarningTextColor(context, line2);

                final PendingIntent pendingIntentForDelete = UIIntents.get()
                        .getPendingIntentForClearingNotifications(context, BugleNotifications.UPDATE_ERRORS,
                                conversationIds, 0);

                builder.setContentTitle(line1).setTicker(line1)
                        .setWhen(when > 0 ? when : System.currentTimeMillis())
                        .setSmallIcon(R.drawable.ic_failed_light).setDeleteIntent(pendingIntentForDelete)
                        .setContentIntent(destinationIntent)
                        .setSound(UriUtil.getUriForResourceId(context, R.raw.message_failure));
                if (isRichContent && !TextUtils.isEmpty(line2)) {
                    final NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(builder);
                    if (line2 != null) {
                        inboxStyle.addLine(Html.fromHtml(line2.toString()));
                    }
                    builder.setStyle(inboxStyle);
                } else {
                    builder.setContentText(line2);
                }

                if (builder != null) {
                    notificationManager.notify(BugleNotifications
                            .buildNotificationTag(PendingIntentConstants.MSG_SEND_ERROR, null),
                            PendingIntentConstants.MSG_SEND_ERROR, builder.build());
                }
            } else {
                notificationManager.cancel(
                        BugleNotifications.buildNotificationTag(PendingIntentConstants.MSG_SEND_ERROR, null),
                        PendingIntentConstants.MSG_SEND_ERROR);
            }
        }
    } finally {
        if (messageDataCursor != null) {
            messageDataCursor.close();
        }
    }
}

From source file:org.sufficientlysecure.keychain.ui.widget.SelectKeyCursorAdapter.java

@Override
public void bindView(View view, Context context, Cursor cursor) {
    boolean valid = cursor.getInt(cursor.getColumnIndex(PROJECTION_ROW_VALID)) > 0;

    TextView mainUserId = (TextView) view.findViewById(R.id.mainUserId);
    mainUserId.setText(R.string.unknownUserId);
    TextView mainUserIdRest = (TextView) view.findViewById(R.id.mainUserIdRest);
    mainUserIdRest.setText("");
    TextView keyId = (TextView) view.findViewById(R.id.keyId);
    keyId.setText(R.string.noKey);/*from   w ww .  j  a  v  a2s  . c  om*/
    TextView status = (TextView) view.findViewById(R.id.status);
    status.setText(R.string.unknownStatus);

    String userId = cursor.getString(cursor.getColumnIndex(UserIds.USER_ID));
    if (userId != null) {
        String[] userIdSplit = OtherHelper.splitUserId(userId);

        if (userIdSplit[1] != null) {
            mainUserIdRest.setText(userIdSplit[1]);
        }
        mainUserId.setText(userIdSplit[0]);
    }

    long masterKeyId = cursor.getLong(cursor.getColumnIndex(KeyRings.MASTER_KEY_ID));
    keyId.setText(PgpHelper.getSmallFingerPrint(masterKeyId));

    if (mainUserIdRest.getText().length() == 0) {
        mainUserIdRest.setVisibility(View.GONE);
    }

    if (valid) {
        if (mKeyType == Id.type.public_key) {
            status.setText(R.string.canEncrypt);
        } else {
            status.setText(R.string.canSign);
        }
    } else {
        if (cursor.getInt(cursor.getColumnIndex(PROJECTION_ROW_AVAILABLE)) > 0) {
            // has some CAN_ENCRYPT keys, but col(ROW_VALID) = 0, so must be revoked or
            // expired
            status.setText(R.string.expired);
        } else {
            status.setText(R.string.noKey);
        }
    }

    CheckBox selected = (CheckBox) view.findViewById(R.id.selected);
    if (mKeyType == Id.type.public_key) {
        selected.setVisibility(View.VISIBLE);

        if (!valid) {
            mListView.setItemChecked(cursor.getPosition(), false);
        }

        selected.setChecked(mListView.isItemChecked(cursor.getPosition()));
        selected.setEnabled(valid);
    } else {
        selected.setVisibility(View.GONE);
    }

    status.setText(status.getText() + " ");

    view.setEnabled(valid);
    mainUserId.setEnabled(valid);
    mainUserIdRest.setEnabled(valid);
    keyId.setEnabled(valid);
    status.setEnabled(valid);
}

From source file:id.nci.stm_9.SelectKeyCursorAdapter.java

@Override
public void bindView(View view, Context context, Cursor cursor) {
    boolean valid = cursor.getInt(cursor.getColumnIndex(PROJECTION_ROW_VALID)) > 0;

    TextView mainUserId = (TextView) view.findViewById(R.id.mainUserId);
    mainUserId.setText(R.string.unknown_user_id);
    TextView mainUserIdRest = (TextView) view.findViewById(R.id.mainUserIdRest);
    mainUserIdRest.setText("");
    TextView keyId = (TextView) view.findViewById(R.id.keyId);
    keyId.setText(R.string.no_key);/*from  ww  w  .j a  va  2 s. co  m*/
    TextView status = (TextView) view.findViewById(R.id.status);
    status.setText(R.string.unknown_status);

    String userId = cursor.getString(cursor.getColumnIndex(UserIds.USER_ID));
    if (userId != null) {
        String[] userIdSplit = OtherHelper.splitUserId(userId);

        if (userIdSplit[1] != null) {
            mainUserIdRest.setText(userIdSplit[1]);
        }
        mainUserId.setText(userIdSplit[0]);
    }

    long masterKeyId = cursor.getLong(cursor.getColumnIndex(KeyRings.MASTER_KEY_ID));
    keyId.setText(PgpKeyHelper.convertKeyIdToHex(masterKeyId));

    if (mainUserIdRest.getText().length() == 0) {
        mainUserIdRest.setVisibility(View.GONE);
    }

    if (valid) {
        //            if (mKeyType == Id.type.public_key) {
        if (mKeyType == 0x21070001) {
            status.setText(R.string.can_encrypt);
        } else {
            status.setText(R.string.can_sign);
        }
    } else {
        if (cursor.getInt(cursor.getColumnIndex(PROJECTION_ROW_AVAILABLE)) > 0) {
            // has some CAN_ENCRYPT keys, but col(ROW_VALID) = 0, so must be revoked or
            // expired
            status.setText(R.string.expired);
        } else {
            status.setText(R.string.no_key);
        }
    }

    CheckBox selected = (CheckBox) view.findViewById(R.id.selected);
    //        if (mKeyType == Id.type.public_key) {
    if (mKeyType == 0x21070001) {
        selected.setVisibility(View.VISIBLE);

        if (!valid) {
            mListView.setItemChecked(cursor.getPosition(), false);
        }

        selected.setChecked(mListView.isItemChecked(cursor.getPosition()));
        selected.setEnabled(valid);
    } else {
        selected.setVisibility(View.GONE);
    }

    status.setText(status.getText() + " ");

    view.setEnabled(valid);
    mainUserId.setEnabled(valid);
    mainUserIdRest.setEnabled(valid);
    keyId.setEnabled(valid);
    status.setEnabled(valid);
}

From source file:group.pals.android.lib.ui.filechooser.BaseFileAdapter.java

@Override
public void bindView(View view, Context context, Cursor cursor) {
    Bag bag = (Bag) view.getTag();//from  www . j av  a2s.co  m

    if (bag == null) {
        bag = new Bag();
        bag.mImageIcon = (ImageView) view.findViewById(R.id.afc_imageview_icon);
        bag.mImageLockedSymbol = (ImageView) view.findViewById(R.id.afc_imageview_locked_symbol);
        bag.mTxtFileName = (TextView) view.findViewById(R.id.afc_textview_filename);
        bag.mTxtFileInfo = (TextView) view.findViewById(R.id.afc_textview_file_info);
        bag.mCheckboxSelection = (CheckBox) view.findViewById(R.id.afc_checkbox_selection);

        view.setTag(bag);
    }

    final int id = cursor.getInt(cursor.getColumnIndex(BaseFile._ID));
    final Uri uri = BaseFileProviderUtils.getUri(cursor);

    final BagInfo bagInfo;
    if (mSelectedChildrenMap.get(id) == null) {
        bagInfo = new BagInfo();
        bagInfo.mUri = uri;
        mSelectedChildrenMap.put(id, bagInfo);
    } else
        bagInfo = mSelectedChildrenMap.get(id);

    /*
     * Update views.
     */

    /*
     * Use single line for grid view, multiline for list view
     */
    bag.mTxtFileName.setSingleLine(view.getParent() instanceof GridView);

    /*
     * File icon.
     */
    bag.mImageLockedSymbol.setVisibility(
            cursor.getInt(cursor.getColumnIndex(BaseFile.COLUMN_CAN_READ)) > 0 ? View.GONE : View.VISIBLE);
    bag.mImageIcon.setImageResource(cursor.getInt(cursor.getColumnIndex(BaseFile.COLUMN_ICON_ID)));
    bag.mImageIcon.setOnTouchListener(mImageIconOnTouchListener);
    bag.mImageIcon.setOnClickListener(
            BaseFileProviderUtils.isDirectory(cursor) ? newImageIconOnClickListener(cursor.getPosition())
                    : null);

    /*
     * Filename.
     */
    bag.mTxtFileName.setText(BaseFileProviderUtils.getFileName(cursor));
    Ui.strikeOutText(bag.mTxtFileName, bagInfo.mMarkedAsDeleted);

    /*
     * File info.
     */
    String time = DateUtils.formatDate(context,
            cursor.getLong(cursor.getColumnIndex(BaseFile.COLUMN_MODIFICATION_TIME)), mFileTimeDisplay);
    if (BaseFileProviderUtils.isFile(cursor))
        bag.mTxtFileInfo.setText(String.format("%s, %s",
                Converter.sizeToStr(cursor.getLong(cursor.getColumnIndex(BaseFile.COLUMN_SIZE))), time));
    else
        bag.mTxtFileInfo.setText(time);

    /*
     * Check box.
     */
    if (mMultiSelection) {
        if (mFilterMode == BaseFile.FILTER_FILES_ONLY && BaseFileProviderUtils.isDirectory(cursor)) {
            bag.mCheckboxSelection.setVisibility(View.GONE);
        } else {
            bag.mCheckboxSelection.setVisibility(View.VISIBLE);

            bag.mCheckboxSelection.setOnCheckedChangeListener(null);
            bag.mCheckboxSelection.setChecked(bagInfo.mChecked);
            bag.mCheckboxSelection.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    bagInfo.mChecked = isChecked;
                }// onCheckedChanged()
            });

            bag.mCheckboxSelection.setOnLongClickListener(mCheckboxSelectionOnLongClickListener);
        }
    } else
        bag.mCheckboxSelection.setVisibility(View.GONE);
}

From source file:com.haibison.android.anhuu.BaseFileAdapter.java

@Override
public void bindView(View view, Context context, Cursor cursor) {
    Bag bag = (Bag) view.getTag();/* w  w w . j av a2 s .c om*/

    if (bag == null) {
        bag = new Bag();
        bag.mImageIcon = (ImageView) view.findViewById(R.id.anhuu_f5be488d_imageview_icon);
        bag.mImageLockedSymbol = (ImageView) view.findViewById(R.id.anhuu_f5be488d_imageview_locked_symbol);
        bag.mTxtFileName = (TextView) view.findViewById(R.id.anhuu_f5be488d_textview_filename);
        bag.mTxtFileInfo = (TextView) view.findViewById(R.id.anhuu_f5be488d_textview_file_info);
        bag.mCheckboxSelection = (CheckBox) view.findViewById(R.id.anhuu_f5be488d_checkbox_selection);

        view.setTag(bag);
    }

    final int id = cursor.getInt(cursor.getColumnIndex(BaseFile._ID));
    final Uri uri = BaseFileProviderUtils.getUri(cursor);

    final BagInfo bagInfo;
    if (mSelectedChildrenMap.get(id) == null) {
        bagInfo = new BagInfo();
        bagInfo.mUri = uri;
        mSelectedChildrenMap.put(id, bagInfo);
    } else
        bagInfo = mSelectedChildrenMap.get(id);

    /*
     * Update views.
     */

    /*
     * Use single line for grid view, multiline for list view
     */
    bag.mTxtFileName.setSingleLine(view.getParent() instanceof GridView);

    /*
     * File icon.
     */
    bag.mImageLockedSymbol.setVisibility(
            cursor.getInt(cursor.getColumnIndex(BaseFile.COLUMN_CAN_READ)) > 0 ? View.GONE : View.VISIBLE);
    bag.mImageIcon.setImageResource(cursor.getInt(cursor.getColumnIndex(BaseFile.COLUMN_ICON_ID)));
    bag.mImageIcon.setOnTouchListener(mImageIconOnTouchListener);
    bag.mImageIcon.setOnClickListener(
            BaseFileProviderUtils.isDirectory(cursor) ? newImageIconOnClickListener(cursor.getPosition())
                    : null);

    /*
     * Filename.
     */
    bag.mTxtFileName.setText(BaseFileProviderUtils.getFileName(cursor));
    UI.strikeOutText(bag.mTxtFileName, bagInfo.mMarkedAsDeleted);

    /*
     * File info.
     */
    String time = DateUtils.formatDate(context,
            cursor.getLong(cursor.getColumnIndex(BaseFile.COLUMN_MODIFICATION_TIME)));
    if (BaseFileProviderUtils.isFile(cursor))
        bag.mTxtFileInfo.setText(String.format("%s, %s",
                Converter.bytesToStr(cursor.getLong(cursor.getColumnIndex(BaseFile.COLUMN_SIZE))), time));
    else
        bag.mTxtFileInfo.setText(time);

    /*
     * Check box.
     */
    if (mMultiSelection) {
        if (mFilterMode == BaseFile.FILTER_FILES_ONLY && BaseFileProviderUtils.isDirectory(cursor)) {
            bag.mCheckboxSelection.setVisibility(View.GONE);
        } else {
            bag.mCheckboxSelection.setVisibility(View.VISIBLE);

            bag.mCheckboxSelection.setOnCheckedChangeListener(null);
            bag.mCheckboxSelection.setChecked(bagInfo.mChecked);
            bag.mCheckboxSelection.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    bagInfo.mChecked = isChecked;
                }// onCheckedChanged()
            });

            bag.mCheckboxSelection.setOnLongClickListener(mCheckboxSelectionOnLongClickListener);
        }
    } else
        bag.mCheckboxSelection.setVisibility(View.GONE);
}