如何数据库适配器传递到另一个活动? [英] How to pass database adapter to another activity?

查看:255
本文介绍了如何数据库适配器传递到另一个活动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些无法理解的搜索对话框在Android SDK中。

I'm having some trouble understanding the search dialog in the Android SDK.

我的应用程序的主要活动提供了一个按钮。如果用户点击这个按钮搜索对话框被调用。搜索本身然后在一个异步任务做了,因为它可能需要一些时间。到目前为止好。

The "main activity" of my application provides a button. If the user clicks this button the search dialog is called. The search itself is then done in an async task as it might need some time. So far so good.

主要活动还创建用来初始化数据库,执行查询等,但我怎么能在搜索活动用这个适配器对象数据库适配器对象?

The main activity also creates a database adapter object which is used to initialize the database, perform queries, etc. But how can I use this adapter object in the searchable activity?

主要活动结果
//初始化数据库结果
DatabaseAdapter DBA =新DatabaseAdapter();结果
dba.init();结果
//打开搜索对话框结果
如果(buttonClick)onSearchRequest();

检索活动


  1. 获取意图,并从搜索对话框收到查询 - >确定

  2. 我怎样才能再次使用数据库适配器执行查询?

  1. Get intent and receive query from search dialog -> OK
  2. How can I use the database adapter again to perform a query?

我一定要创建一个新的对象?我能以某种方式将它传递从分活动到搜索活动,[...]

Do I have to create a new object? Can I pass it somehow from the min activity to the searchable activity, [...]?

谢谢,结果
罗伯特

Thanks,
Robert

推荐答案

一种选择是使用独立的,并通过一个静态方法提供访问DatabaseAdapter。例如:

An option would be to use a singleton and provide access to the DatabaseAdapter via a static method. Ex:

private static DatabaseAdapter sWritableAdapter = null;
private static DatabaseAdapter sReadableAdapter = null;

public static DatabaseAdapter openForReading(Context ctx) {
    if(sReadableAdapter == null)
    sReadableAdapter = new DatabaseAdapter(new DatabaseHelper(ctx).getReadableDatabase());

    return sReadableAdapter;

}

或写访问:

public static DatabaseAdapter openForWriting(Context ctx) {
if(sWritableAdapter == null)
        sWritableAdapter = new DatabaseAdapter(new DatabaseHelper(ctx).getWritableDatabase());

    return sWritableAdapter;

}

因此​​,在你的搜索活动,你会写,例如:

So in your searchable activity you would write for instance:

DatabaseAdapter adapter = DatabaseAdapter.openForReading(ctx);
adapter.searchSomething();

马可波罗

这篇关于如何数据库适配器传递到另一个活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆