异步加载数据库数据

一般加载数据库数据都是开启线程调用sqlite

这里有更加简便的方法,但是需要在android3.0才支持

方法一:

CursorLoader

MainActivity.java

package com.waitingfy.android;
 
import android.app.ListActivity;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
 
public class MainActivity extends ListActivity implements LoaderCallbacks<Cursor> {//1.首先要实现这接口
 
    private TextView mNoticeMessage;
    private SimpleCursorAdapter  mAdapter;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mNoticeMessage = (TextView)findViewById(R.id.notice_message);
        getLoaderManager().initLoader(1, null, this);//2.要初始化Loader
    }
 
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        return new MyCursorLoader(getApplicationContext());//3.去数据库读取数据等要消耗大量时间的操作放在
                                                           //自定义 CursorLoader 的 onLoadInBackground
    }
    /**
     * 4.自定义 CursorLoader 的 onLoadInBackground
     *  会返回一个Cursor,这里给SimpleCursorAdapter用
     *  来填充数据。
     */
    public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
        mAdapter = new SimpleCursorAdapter(MainActivity.this,R.layout.contacts_list_item, 
                cursor, new String[]{ContactsContract.Contacts.DISPLAY_NAME},new int[]{ android.R.id.text1});
        setListAdapter(mAdapter);
        mNoticeMessage.setText(getResources().getString(R.string.count_string,mAdapter.getCount()));
 
    }
 
    public void onLoaderReset(Loader<Cursor> arg0) {
        // TODO Auto-generated method stub
 
    }
}

MyCursorLoader.java

package com.waitingfy.android;
 
import android.content.Context;
import android.content.CursorLoader;
import android.database.Cursor;
import android.provider.ContactsContract;
 
public class MyCursorLoader extends CursorLoader{
 
    String[] mContactProjection={
            ContactsContract.Contacts._ID, //0
            ContactsContract.Contacts.DISPLAY_NAME//1
    };
 
    private Context mContext;
    public MyCursorLoader(Context context) {
        super(context);
        mContext = context;
    }
    /**
     * 查询数据等操作放在这里执行 
     */
    @Override
    protected Cursor onLoadInBackground() {
        Cursor cursor = mContext.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, 
                mContactProjection, null,null, null);
        return cursor;
    }
}

方法二:

AsyncQueryHandler 不过感觉没有方法一方便好用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值