如何使用Anko检查记录是否存在?

时间:2017-12-18 11:07:09

标签: android sqlite anko

我正在学习使用anko从sqlite获取数据。我可以成功打印数据(如果记录存在)但我的应用程序总是在数据不存在时崩溃。

错误说:

  

parseSingle只接受带有单个条目的游标

我确切地知道错误的含义,我只是不知道如何解决它。

这是查询的代码:

+function($) {
'use strict';

var modals = $('.modal.multi-step');

modals.each(function(idx, modal) {
    var $modal = $(modal);
    var $bodies = $modal.find('div.modal-body');
    var total_num_steps = $bodies.length;
    var $progress = $modal.find('.m-progress');
    var $progress_bar = $modal.find('.m-progress-bar');
    var $progress_stats = $modal.find('.m-progress-stats');
    var $progress_current = $modal.find('.m-progress-current');
    var $progress_total = $modal.find('.m-progress-total');
    var $progress_complete  = $modal.find('.m-progress-complete');
    var reset_on_close = $modal.attr('reset-on-close') === 'true';

    function reset() {
        $modal.find('.step').hide();
        $modal.find('[data-step]').hide();
    }

    function completeSteps() {
        $progress_stats.hide();
        $progress_complete.show();
        $modal.find('.progress-text').animate({
            top: '-2em'
        });
        $modal.find('.complete-indicator').animate({
            top: '-2em'
        });
        $progress_bar.addClass('completed');
    }

    function getPercentComplete(current_step, total_steps) {
        return Math.min(current_step / total_steps * 100, 100) + '%';
    }

    function updateProgress(current, total) {
        $progress_bar.animate({
            width: getPercentComplete(current, total)
        });
        if (current - 1 >= total_num_steps) {
            completeSteps();
        } else {
            $progress_current.text(current);
        }

        $progress.find('[data-progress]').each(function() {
            var dp = $(this);
            if (dp.data().progress <= current - 1) {
                dp.addClass('completed');
            } else {
                dp.removeClass('completed');
            }
        });
    }

    function goToStep(step) {
        reset();
        var to_show = $modal.find('.step-' + step);
        if (to_show.length === 0) {
            // at the last step, nothing else to show
            return;
        }
        to_show.show();
        var current = parseInt(step, 10);
        updateProgress(current, total_num_steps);
        findFirstFocusableInput(to_show).focus();
    }

    function findFirstFocusableInput(parent) {
        var candidates = [parent.find('input'), parent.find('select'),
                          parent.find('textarea'),parent.find('button')],
            winner = parent;
        $.each(candidates, function() {
            if (this.length > 0) {
                winner = this[0];
                return false;
            }
        });
        return $(winner);
    }

    function bindEventsToModal($modal) {
        var data_steps = [];
        $('[data-step]').each(function() {
            var step = $(this).data().step;
            if (step && $.inArray(step, data_steps) === -1) {
                data_steps.push(step);
            }
        });

        $.each(data_steps, function(i, v) {
            $modal.on('next.m.' + v, {step: v}, function(e) {
                goToStep(e.data.step);
            });
        });
    }

    function initialize() {
        reset();
        updateProgress(1, total_num_steps);
        $modal.find('.step-1').show();
        $progress_complete.hide();
        $progress_total.text(total_num_steps);
        bindEventsToModal($modal, total_num_steps);
        $modal.data({
            total_num_steps: $bodies.length,
        });
        if (reset_on_close){
            //Bootstrap 2.3.2
            $modal.on('hidden', function () {
                reset();
                $modal.find('.step-1').show();
            })
            //Bootstrap 3
            $modal.on('hidden.bs.modal', function () {
                reset();
                $modal.find('.step-1').show();
            })
        }
    }

    initialize();
})
}(jQuery);

我尝试在ServerRoot "/etc/httpd" Listen 80 Include conf.modules.d/*.conf User apache Group apache ServerAdmin root@localhost ServerName locahost:80 <Directory /> AllowOverride none Require all denied </Directory> DocumentRoot "/var/www/html/site1" <Directory "/var/www"> AllowOverride None # Allow open access: Require all granted </Directory> <Directory "/var/www/html/site1"> Options FollowSymLinks AllowOverride all Order allow,deny Allow from all </Directory> <IfModule dir_module> DirectoryIndex index.html </IfModule> <Files ".ht*"> Require all denied </Files> ErrorLog "logs/error_log" LogLevel warn <IfModule log_config_module> LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %b" common <IfModule logio_module> LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio </IfModule> CustomLog "logs/access_log" combined </IfModule> <IfModule alias_module> ScriptAlias /cgi-bin/ "/var/www/cgi-bin/" </IfModule> <Directory "/var/www/cgi-bin"> AllowOverride None Options None Require all granted </Directory> <IfModule mime_module> TypesConfig /etc/mime.types AddType application/x-compress .Z AddType application/x-gzip .gz .tgz AddType text/html .shtml AddOutputFilter INCLUDES .shtml </IfModule> AddDefaultCharset UTF-8 <IfModule mime_magic_module> MIMEMagicFile conf/magic </IfModule> EnableSendfile on IncludeOptional conf.d/*.conf fun getUserByUid(uid: Int): UserModel { val data = context.database.use { val db = context.database.readableDatabase val columns = UserModel.COLUMN_ID + "," + UserModel.COLUMN_NAME + "," + UserModel.COLUMN_API_KEY val query = db.select(UserModel.TABLE_NAME, columns) .whereArgs("(uid = {userId})", "userId" to uid) query.exec { val rowParser = classParser<UserModel>() parseSingle(rowParser) // this line that trigger error exception } } return data } 变量中找到count函数,以检查记录是否存在但无法找到。

1 个答案:

答案 0 :(得分:2)

来自维基页面。 https://github.com/Kotlin/anko/wiki/Anko-SQLite#parsing-query-results

解析查询结果

所以我们有一些Cursor,我们如何将它解析为常规类? Anko提供了函数parseSingle,parseOpt和parseList来更轻松地完成它。

方法说明 parseSingle(rowParser):T正好解析一行 parseOpt(rowParser):T?解零或一行 parseList(rowParser):列表解析零行或多行 请注意,如果收到的Cursor包含多行,parseSingle()和parseOpt()将抛出异常。