每次切换片段时,Custom CursorAdapter都会从db加载数据

时间:2015-07-16 11:16:31

标签: android android-fragments lifecycle android-cursoradapter

我有一个Activity ViewPager和三个Fragments with-in。一个Fragment包含ListView,其中包含从数据库加载数据的自定义CursorAdapter

我注意到每次在Fragments中切换ViewPager时,我的光标适配器都会加载数据。我认为这是正常的,这是因为每个Fragment都有自己的生命周期。

对于我来说,如果stackoverflow的用户完全解释他们的经验或最佳实践,我将非常高兴。

谢谢!

1 个答案:

答案 0 :(得分:1)

ViewPagers仅保留一定数量的片段的状态,当前所选片段的两侧默认为1。例如,如果您有3个片段,则在选择第一个片段时,只会实例化前两个片段并加载listview数据。或者,如果选择了第二个片段,则将实例化第一个和第三个片段。如果切换到第三个片段,第二个片段将被保留,但第一个片段将丢失。但是,您可以使用viewPager上的viewPager方法设置要保留的片段数,并保留您需要的任意数量的片段。虽然您应该记住,将数字设置得太高可能会导致您的应用消耗太多内存。

例如,如果您希望片段在切换片段时不从db重新加载listview内容,并且ViewPager mViewPager; mViewPager.setOffscreenPageLimit(2); 中有3个片段,则可以编写以下代码:

def prepare_invoice(self, cr, uid, order, lines, context=None):
    """Prepare the dict of values to create the new invoice for a
       sales order. This method may be overridden to implement custom
       invoice generation (making sure to call super() to establish
       a clean extension chain).

       :param browse_record order: sale.order record to invoice
       :param list(int) line: list of invoice line IDs that must be
                              attached to the invoice
       :return: dict of value to create() the invoice
    """
    order=self.browse(cr,uid,lines,context=context)
    if context is None:
        context = {}
    journal_ids = self.pool.get('account.journal').search(cr, uid,
        [('type', '=', 'sale'), ('company_id', '=', order.company_id.id)],
        limit=1)
    # if not journal_ids:
    #     raise osv.except_osv(_('Error!'),
    #         _('Please define sales journal for this company: "%s" (id:%d).') % (order.company_id.name, order.company_id.id))
    invoice_vals = {
        'name': order.client_order_ref or '',
        'origin': order.name,
        'type': 'out_invoice',
        'reference': order.client_order_ref or order.name,
        'account_id': order.partner_invoice_id.property_account_receivable.id,
        'partner_id': order.partner_invoice_id.id,
        'journal_id': journal_ids[0],
        'invoice_line': [(6, 0, lines)],
        'currency_id': order.pricelist_id.currency_id.id,
        'comment': order.note,
        'payment_term': order.payment_term and order.payment_term.id or False,
        'fiscal_position': order.fiscal_position.id or order.partner_invoice_id.property_account_position.id,
        'date_invoice': context.get('date_invoice', False),
        'company_id': order.company_id.id,
        'user_id': order.user_id and order.user_id.id or False,
        'section_id' : order.section_id.id,
        'Order' : order.Order
    }

    # Care for deprecated _inv_get() hook - FIXME: to be removed after 6.1
    invoice_vals.update(self._inv_get(cr, uid, order, context=context))
    return invoice_vals