下面列出了怎么用android.widget.SimpleCursorAdapter的API类实例代码及写法,或者点击链接到github查看源代码。
void refreshView() {
TaskLocalUtils tLocalUtils = new TaskLocalUtils(GlobalContext.getInstance());
cr = tLocalUtils.getAllCursorInMainList();
mTitles = getAllTitlesOfCurosr(cr);
mIds = getAllIdFromCursor(cr);
// final TaskListCursorAdapter mAdapter = new TaskListCursorAdapter(getActivity(), R.layout.my_task_list,
// cr,
// new String[] { TaskRecorder.KEY_TITLE },
// new int[] { R.id.tvLarger }, 2, getFragmentManager(), this);
final SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(getActivity(),
R.layout.my_task_list, cr, new String[] { TaskRecorder.KEY_TITLE },
new int[] { R.id.tvLarger });
listView.setAdapter(mAdapter);
}
private void setActAdapter(IDictionary dict) {
Object adapter = dict.getAutoCompleteAdapter(PopupActivity.this,
android.R.layout.simple_spinner_dropdown_item);
if(adapter != null){
if(adapter instanceof SimpleCursorAdapter){
act.setAdapter((SimpleCursorAdapter) adapter);
}
else if(adapter instanceof UrbanAutoCompleteAdapter){
act.setAdapter((UrbanAutoCompleteAdapter) adapter);
}
}
act.setOnFocusChangeListener(
new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
if(act.getText().toString().trim().isEmpty()){
return;
}
act.showDropDown();
}
}
}
);
}
private SimpleCursorAdapter getSmsListAdapter() {
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,
DbHelper.getDbHelper(this).getCursor(),
new String[] { DbHelper.COLUMN_MESSAGE, DbHelper.COLUMN_RECIPIENT_NAME },
new int[] { android.R.id.text1, android.R.id.text2 }
);
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
TextView textView = (TextView) view;
if (textView.getId() == android.R.id.text2) {
textView.setText(getFormattedSmsInfo(cursor));
return true;
}
return false;
}
});
return adapter;
}
/**
* 关注1
* 模糊查询数据 & 显示到ListView列表上
*/
private void queryData(String tempName) {
// 1. 模糊搜索
Cursor cursor = helper.getReadableDatabase().rawQuery(
"select id as _id,name from records where name like '%" + tempName + "%' order by id desc ", null);
// 2. 创建adapter适配器对象 & 装入模糊搜索的结果
adapter = new SimpleCursorAdapter(context, android.R.layout.simple_list_item_1, cursor, new String[] { "name" },
new int[] { android.R.id.text1 }, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
// 3. 设置适配器
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
System.out.println(cursor.getCount());
// 当输入框为空 & 数据库中有搜索记录时,显示 "删除搜索记录"按钮
if (tempName.equals("") && cursor.getCount() != 0){
tv_clear.setVisibility(VISIBLE);
}
else {
tv_clear.setVisibility(INVISIBLE);
};
}
public void accessNotes(View view) {
EditText pinTxt = (EditText) findViewById(R.id.aci3notesPinText);
Button abutton = (Button) findViewById(R.id.aci3naccessbutton);
SharedPreferences spref = PreferenceManager.getDefaultSharedPreferences(this);
String pin = spref.getString(getString(R.string.pkey), "");
String userpin = pinTxt.getText().toString();
// XXX Easter Egg?
if (userpin.equals(pin)) {
// Display the private notes
ListView lview = (ListView) findViewById(R.id.aci3nlistView);
Cursor cr = getContentResolver().query(NotesProvider.CONTENT_URI, new String[] {"_id", "title", "note"}, null, null, null);
String[] columns = {NotesProvider.C_TITLE, NotesProvider.C_NOTE};
int [] fields = {R.id.title_entry, R.id.note_entry};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.notes_entry ,cr, columns, fields, 0);
lview.setAdapter(adapter);
pinTxt.setVisibility(View.INVISIBLE);
abutton.setVisibility(View.INVISIBLE);
//cr.close();
}
else {
Toast.makeText(this, "Please Enter a valid pin!", Toast.LENGTH_SHORT).show();
}
}
/**
* Hook method dispatched by the GenericActivity framework to
* initialize the ContactsOpsImpl object after it's been created.
*
* @param view The currently active ContactsOps.View.
* @param firstTimeIn Set to "true" if this is the first time the
* Ops class is initialized, else set to
* "false" if called after a runtime
* configuration change.
*/
public void onConfiguration(ContactsOps.View view,
boolean firstTimeIn) {
// Create a WeakReference to the ContactsOps.View.
mContactsView =
new WeakReference<>(view);
if (firstTimeIn) {
// Initialize the Google account information.
initializeAccount();
// Initialize the SimpleCursorAdapter.
mCursorAdapter =
new SimpleCursorAdapter(view.getApplicationContext(),
R.layout.list_layout,
null,
sColumnsToDisplay,
sColumnResIds,
1);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_example);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//deleteDatabase(new MyCPOrmConfiguration().getDatabaseName());
adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
null,
new String[]{"user_name"},
new int[]{android.R.id.text1},
0);
listview = (ListView) findViewById(R.id.listView);
listview.setAdapter(adapter);
getLoaderManager().initLoader(1, Bundle.EMPTY, this);
new PopulateDataTask(this).execute();
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
setRetainInstance(true); // save fragment across config changes
setHasOptionsMenu(true); // this fragment has menu items to display
// set text to display when there are no contacts
setEmptyText(getResources().getString(R.string.no_contacts));
// get ListView reference and configure ListView
contactListView = getListView();
contactListView.setOnItemClickListener(viewContactListener);
contactListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
// map each contact's name to a TextView in the ListView layout
String[] from = new String[] { "name" };
int[] to = new int[] { android.R.id.text1 };
contactAdapter = new SimpleCursorAdapter(getActivity(),
android.R.layout.simple_list_item_1, null, from, to, 0);
setListAdapter(contactAdapter); // set adapter that supplies data
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
setRetainInstance(true); // save fragment across config changes
setHasOptionsMenu(true); // this fragment has menu items to display
// set text to display when there are no contacts
setEmptyText(getResources().getString(R.string.no_contacts));
// get ListView reference and configure ListView
contactListView = getListView();
contactListView.setOnItemClickListener(viewContactListener);
contactListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
// map each contact's name to a TextView in the ListView layout
String[] from = new String[] { "name" };
int[] to = new int[] { android.R.id.text1 };
contactAdapter = new SimpleCursorAdapter(getActivity(),
android.R.layout.simple_list_item_1, null, from, to, 0);
setListAdapter(contactAdapter); // set adapter that supplies data
}
/**
* Set {@link SimpleCursorAdapter} for {@link Spinner}.
*/
private void setAdapter() {
final Cursor c = getContentResolver().query(DataProvider.Plans.CONTENT_URI,
PROJ_ADAPTER, DataProvider.Plans.WHERE_PLANS, null, DataProvider.Plans.NAME);
String[] fieldName;
if (cbShowShortname.isChecked()) {
fieldName = new String[]{DataProvider.Plans.SHORTNAME};
} else {
fieldName = new String[]{DataProvider.Plans.NAME};
}
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item, c, fieldName,
new int[]{android.R.id.text1});
final int pos = spinner.getSelectedItemPosition();
spinner.setAdapter(adapter);
if (pos >= 0 && pos < spinner.getCount()) {
spinner.setSelection(pos);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get Account information
// Must have a Google account set up on your device
mAccountList = AccountManager.get(this).getAccountsByType("com.google");
mType = mAccountList[0].type;
mName = mAccountList[0].name;
// Insert new contacts
insertAllNewContacts();
// Create and set empty list adapter
mAdapter = new SimpleCursorAdapter(this, R.layout.list_layout, null,
columnsToDisplay, resourceIds, 0);
setListAdapter(mAdapter);
// Initialize a CursorLoader
getLoaderManager().initLoader(0, null, this);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get Account information
Account[] mAccountList = AccountManager.get(this).getAccountsByType("com.google");
// Must have a Google account set up on your device
if (mAccountList.length == 0) finish();
mType = mAccountList[0].type;
mName = mAccountList[0].name;
// Insert new contacts
insertAllNewContacts();
// Create and set empty list adapter
mAdapter = new SimpleCursorAdapter(this, R.layout.list_layout, null,
columnsToDisplay, resourceIds, 0);
setListAdapter(mAdapter);
// Initialize a CursorLoader
getLoaderManager().initLoader(0, null, this);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create a new DatabaseHelper
mDbHelper = new DatabaseOpenHelper(this);
// start with an empty database
clearAll();
// Insert records
insertArtists();
// Create a cursor
mCursor = readArtists();
mAdapter = new SimpleCursorAdapter(this, R.layout.list_layout, mCursor,
DatabaseOpenHelper.columns, new int[] { R.id._id, R.id.name },
0);
setListAdapter(mAdapter);
}
@Override public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Give some text to display if there is no data. In a real
// application this would come from a resource.
setEmptyText("No phone numbers");
// We have a menu item to show in action bar.
setHasOptionsMenu(true);
// Create an empty adapter we will use to display the loaded data.
mAdapter = new SimpleCursorAdapter(getActivity(),
android.R.layout.simple_list_item_2, null,
new String[] { Contacts.DISPLAY_NAME, Contacts.CONTACT_STATUS },
new int[] { android.R.id.text1, android.R.id.text2 }, 0);
setListAdapter(mAdapter);
// Start out with a progress indicator.
setListShown(false);
// Prepare the loader. Either re-connect with an existing one,
// or start a new one.
getLoaderManager().initLoader(0, null, this);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] columns = { android.provider.MediaStore.Audio.Albums._ID,
android.provider.MediaStore.Audio.Albums.ALBUM };
cursor = managedQuery(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
columns, null, null, null);
String[] displayFields = new String[] { MediaStore.Audio.Albums.ALBUM };
int[] displayViews = new int[] { android.R.id.text1 };
setListAdapter(new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, cursor, displayFields,
displayViews));
}
/**
* {@inheritDoc}
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Uri uri = getIntent().getData();
if (uri == null) {
uri = Procedures.CONTENT_URI;
}
sync(this, uri);
Cursor cursor = managedQuery(uri, PROJECTION2, null, null,
Procedures.DEFAULT_SORT_ORDER);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.procedure_list_row, cursor,
new String[]{
Procedures.Contract.TITLE,
Procedures.Contract.VERSION
//Procedures.Contract.AUTHOR
},
new int[]{
R.id.toptext, R.id.bottomtext
});
Locales.updateLocale(this, getString(R.string.force_locale));
setListAdapter(adapter);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.students_list, container, false);
db = new Database(getActivity());
// Obtiene el cursor con el listado de alumnos de la Base de Datos
Cursor cursor = db.getStudents();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(getActivity(), R.layout.student_row, cursor, FROM_SHOW, TO,
SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
ListView lvStudentsList = (ListView) view.findViewById(R.id.lvStudentsList);
lvStudentsList.setAdapter(adapter);
return view;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "notes-db", null);
db = helper.getWritableDatabase();
daoMaster = new DaoMaster(db);
daoSession = daoMaster.newSession();
userInfoDao = daoSession.getNoteDao();
String textColumn = UserInfoDao.Properties.Text.columnName;
String orderBy = textColumn + " COLLATE LOCALIZED ASC";
cursor = db.query(userInfoDao.getTablename(), userInfoDao.getAllColumns(), null, null, null, null, orderBy);
String[] from = { textColumn, UserInfoDao.Properties.Comment.columnName };
int[] to = { android.R.id.text1, android.R.id.text2 };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, from,
to);
setListAdapter(adapter);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextAge = (EditText) findViewById(R.id.editTextAge);
addUiListeners();
}
@SuppressWarnings("deprecation")
private void showAndFillListView()
{
makeSureSqlDatabaseIsOpen();
String[] from = { NotesTable.CLOUMN_CONTENT, NotesTable.COLUMN_STATUS };
int[] to = {R.id.textview_note_row_content, R.id.textview_note_row_marked };
simpleCursorAdapter = new SimpleCursorAdapter(this, R.layout.note_listview_row, null, from, to);
if(loaderManager.getLoader(1) != null)
{
loaderManager.destroyLoader(1);
}
loaderManager.initLoader(1, null, this);
setListAdapter(simpleCursorAdapter);
}
private void setLoader(final String filterClusterId, final String filterHostId) {
hostsAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_activated_1, null,
new String[]{OVirtContract.Host.NAME}, new int[]{android.R.id.text1}, 0);
cursorAdapterLoader = new CursorAdapterLoader(hostsAdapter) {
@Override
public synchronized Loader<Cursor> onCreateLoader(int id, Bundle args) {
return provider.query(Host.class)
.where(Host.STATUS, HostStatus.UP.toString())
.where(Host.CLUSTER_ID, filterClusterId)
.where(Host.ID, filterHostId, Relation.NOT_EQUAL).asLoader();
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
hostsAdapter.swapCursor(data);
if (data != null && data.getCount() > 0) {
enableViews();
}
}
};
getSupportLoaderManager().initLoader(HOSTS_LOADER, null, cursorAdapterLoader);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery_2);
// Get a cursor with all people
Cursor c = getContentResolver().query(Contacts.CONTENT_URI,
CONTACT_PROJECTION, null, null, null);
startManagingCursor(c);
SpinnerAdapter adapter = new SimpleCursorAdapter(this,
// Use a template that displays a text view
android.R.layout.simple_gallery_item,
// Give the cursor to the list adatper
c,
// Map the NAME column in the people database to...
new String[] {Contacts.DISPLAY_NAME},
// The "text1" view defined in the XML template
new int[] { android.R.id.text1 });
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(adapter);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get a cursor with all people
Cursor c = getContentResolver().query(Contacts.CONTENT_URI,
CONTACT_PROJECTION, null, null, null);
startManagingCursor(c);
ListAdapter adapter = new SimpleCursorAdapter(this,
// Use a template that displays a text view
android.R.layout.simple_list_item_1,
// Give the cursor to the list adatper
c,
// Map the NAME column in the people database to...
new String[] {Contacts.DISPLAY_NAME},
// The "text1" view defined in the XML template
new int[] {android.R.id.text1});
setListAdapter(adapter);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_7);
mPhone = (TextView) findViewById(R.id.phone);
getListView().setOnItemSelectedListener(this);
// Get a cursor with all numbers.
// This query will only return contacts with phone numbers
Cursor c = getContentResolver().query(Phone.CONTENT_URI,
PHONE_PROJECTION, Phone.NUMBER + " NOT NULL", null, null);
startManagingCursor(c);
ListAdapter adapter = new SimpleCursorAdapter(this,
// Use a template that displays a text view
android.R.layout.simple_list_item_1,
// Give the cursor to the list adapter
c,
// Map the DISPLAY_NAME column to...
new String[] {Phone.DISPLAY_NAME},
// The "text1" view defined in the XML template
new int[] {android.R.id.text1});
setListAdapter(adapter);
}
@Override public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Give some text to display if there is no data. In a real
// application this would come from a resource.
setEmptyText("No phone numbers");
// We have a menu item to show in action bar.
setHasOptionsMenu(true);
// Create an empty adapter we will use to display the loaded data.
mAdapter = new SimpleCursorAdapter(getActivity(),
android.R.layout.simple_list_item_2, null,
new String[] { Contacts.DISPLAY_NAME, Contacts.CONTACT_STATUS },
new int[] { android.R.id.text1, android.R.id.text2 }, 0);
setListAdapter(mAdapter);
// Start out with a progress indicator.
setListShown(false);
// Prepare the loader. Either re-connect with an existing one,
// or start a new one.
getLoaderManager().initLoader(0, null, this);
}
@Override public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setEmptyText("No data. Select 'Populate' to fill with data from Z to A at a rate of 4 per second.");
setHasOptionsMenu(true);
// Create an empty adapter we will use to display the loaded data.
mAdapter = new SimpleCursorAdapter(getActivity(),
android.R.layout.simple_list_item_1, null,
new String[] { MainTable.COLUMN_NAME_DATA },
new int[] { android.R.id.text1 }, 0);
setListAdapter(mAdapter);
// Start out with a progress indicator.
setListShown(false);
// Prepare the loader. Either re-connect with an existing one,
// or start a new one.
getLoaderManager().initLoader(0, null, this);
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Cursor mCursor = getContacts();
startManagingCursor(mCursor);
// Now create a new list adapter bound to the cursor.
// SimpleListAdapter is designed for binding to a Cursor.
ListAdapter adapter = new SimpleCursorAdapter(this, // Context.
android.R.layout.simple_list_item_2, // Specify the row template
// to use (here, two
// columns bound to the
// two retrieved cursor
// rows).
mCursor, // Pass in the cursor to bind to.
// Array of cursor columns to bind to.
new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME },
// Array of layout variables to bind to
new int[] { android.R.id.text1, android.R.id.text2 });
// Bind to our new adapter.
setListAdapter(adapter);
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// We select the id, the URL and the title from the database
// the ID is handy for the reaction on the selection
String[] selection = { Browser.BookmarkColumns._ID,
Browser.BookmarkColumns.URL, Browser.BookmarkColumns.TITLE };
String[] displayFields = { Browser.BookmarkColumns.URL,
Browser.BookmarkColumns.TITLE };
int[] viewFields = { android.R.id.text1, android.R.id.text2 };
Cursor cursor = managedQuery(Browser.BOOKMARKS_URI, selection, null,
null, null);
startManagingCursor(cursor);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_2, cursor, displayFields,
viewFields);
setListAdapter(adapter);
}
/**
* 初始化ListView中的数据
*/
@SuppressWarnings("deprecation")
private void initDataFavorites() {
//获取书签管理
this.favAndHisManager = new FavAndHisManager(this);
this.favAndHisCursor = this.favAndHisManager.getAllFavorites();
this.favAndHisAdapter = new SimpleCursorAdapter(getApplicationContext(),
R.layout.list_item_, this.favAndHisCursor,
new String[]{"_id", "name", "url"},
new int[]{R.id.item_id, R.id.item_name, R.id.item_url});
this.favoritesContent.setAdapter(this.favAndHisAdapter);
}
/**
* 初始化ListView中History的数据
*/
@SuppressWarnings("deprecation")
private void initDataHistory() {
//获取书签管理
this.favAndHisManager = new FavAndHisManager(this);
this.favAndHisCursor = this.favAndHisManager.getAllHistories();
this.favAndHisAdapter = new SimpleCursorAdapter(getApplicationContext(),
R.layout.list_item_, this.favAndHisCursor,
new String[]{"_id", "name", "url", "date"},
new int[]{R.id.item_id, R.id.item_name, R.id.item_url, R.id.item_date});
this.historyContent.setAdapter(this.favAndHisAdapter);
}
private void populateListViewFromDB() {
Cursor cursor = myDb.getAllRows();
// Allow activity to manage lifetime of the cursor.
// DEPRECATED! Runs on the UI thread, OK for small/short queries.
startManagingCursor(cursor);
// Setup mapping from cursor to view fields:
String[] fromFieldNames = new String[]
{DBAdapter.KEY_NAME, DBAdapter.KEY_STUDENTNUM, DBAdapter.KEY_FAVCOLOUR, DBAdapter.KEY_STUDENTNUM};
int[] toViewIDs = new int[]
{R.id.item_name, R.id.item_icon, R.id.item_favcolour, R.id.item_studentnum};
// Create adapter to may columns of the DB onto elemesnt in the UI.
SimpleCursorAdapter myCursorAdapter =
new SimpleCursorAdapter(
this, // Context
R.layout.item_layout, // Row layout template
cursor, // cursor (set of DB records to map)
fromFieldNames, // DB Column names
toViewIDs // View IDs to put information in
);
// Set the adapter for the list view
ListView myList = (ListView) findViewById(R.id.listViewFromDB);
myList.setAdapter(myCursorAdapter);
}