CursorLoader用法

CursorLoader繼承與AsycTaskLoader,內部自帶ContentObserver。咱們能夠用它來讀取數據庫,並自動檢測數據源的更新。java

下面是讀取短信的例子數據庫

public class LoadersActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {

    private ListView mListView;

    private MyAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loaders);
        mListView = (ListView) findViewById(R.id.lv);
        LoaderManager loaderManager = getSupportLoaderManager();
        loaderManager.initLoader(0, null, this);
    }

    @Override
    public Loader onCreateLoader(int id, Bundle args) {
        Uri CONTACT_URI = Uri.parse("content://sms/");
        CursorLoader cursorLoader = new CursorLoader(this, CONTACT_URI, null,
                null, null, null);
        return cursorLoader;
    }

    @Override
    public void onLoadFinished(Loader loader, Cursor data) {
        data.moveToFirst();
        mAdapter = new MyAdapter(this, data);
        mListView.setAdapter(mAdapter);
    }

    @Override
    public void onLoaderReset(Loader loader) {

    }

}

class MyAdapter extends BaseAdapter {

    private List<String> mDataList;

    private Context context;

    private Cursor cursor;

    private class ViewHolder {
        TextView textView;
    }

    public MyAdapter(Context context, Cursor cursor) {
        this.context = context;
        this.cursor = cursor;
    }

    public void setDataList(List<String> dataList) {
        this.mDataList = dataList;
    }

    @Override
    public int getCount() {
        return cursor.getCount();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        View view = convertView;
        if (view == null) {
            view = LayoutInflater.from(context).inflate(R.layout.item_cursor_loader, null);
            viewHolder = new ViewHolder();
            viewHolder.textView = (TextView) view.findViewById(R.id.textview);
            view.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) view.getTag();
        }
        cursor.moveToPosition(position);
        viewHolder.textView.setText(cursor.getString(2));
        return view;
    }
}
相關文章
相關標籤/搜索