一般加载数据库数据都是开启线程调用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 不过感觉没有方法一方便好用。