使用CursorLoader加载联系人信息

来源:互联网 发布:java 神经网络框架bp 编辑:程序博客网 时间:2024/04/30 20:17
public class ContactsActivity extends AppCompatActivity implements SearchView.OnCloseListener,        SearchView.OnQueryTextListener, LoaderManager.LoaderCallbacks<Cursor>, AdapterView.OnItemClickListener {    // These are the Contacts rows that we will retrieve.    static final String[] CONTACTS_SUMMARY_PROJECTION = new String[]{            ContactsContract.Contacts._ID,            ContactsContract.Contacts.DISPLAY_NAME,            ContactsContract.Contacts.CONTACT_STATUS,            ContactsContract.Contacts.CONTACT_PRESENCE,            ContactsContract.Contacts.PHOTO_ID,            ContactsContract.Contacts.LOOKUP_KEY,    };    private ListView mListView;    private SearchView mSearchView;    private SimpleCursorAdapter mAdapter;    private String mCurFilter;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_contacts);        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);        toolbar.setLogo(R.mipmap.ic_launcher);        toolbar.setTitle("Contacts");        setSupportActionBar(toolbar);        mListView = (ListView) findViewById(R.id.lv);        TextView emptyView = (TextView) findViewById(R.id.empty_view);        mListView.setEmptyView(emptyView);        setAdapter();        getSupportLoaderManager().initLoader(0, null, this);    }    private void setAdapter() {        mAdapter = new SimpleCursorAdapter(this,                android.R.layout.simple_list_item_2, null,                new String[]{ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.PHOTO_ID},                new int[]{android.R.id.text1, android.R.id.text2}, 0);        mListView.setAdapter(mAdapter);        mListView.setOnItemClickListener(this);    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        getMenuInflater().inflate(R.menu.menu_main, menu);        MenuItem item = menu.findItem(R.id.search_view);        mSearchView = (SearchView) MenuItemCompat.getActionView(item);        // The normal SearchView doesn't clear its search text when        // collapsed, so we will do this for it.        mSearchView.setQuery("", false);        mSearchView.setIconifiedByDefault(true);        mSearchView.setOnCloseListener(this);        mSearchView.setOnQueryTextListener(this);        return true;    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {        return super.onOptionsItemSelected(item);    }    @Override    public boolean onClose() {        if (!TextUtils.isEmpty(mSearchView.getQuery())) {            mSearchView.setQuery(null, true);        }        return true;    }    @Override    public boolean onQueryTextSubmit(String query) {        //do nothing        return true;    }    @Override    public boolean onQueryTextChange(String newText) {        // Called when the action bar search text has changed.  Update        // the search filter, and restart the loader to do a new query        // with this filter.        String newFilter = !TextUtils.isEmpty(newText) ? newText : null;        // Don't do anything if the filter hasn't actually changed.        // Prevents restarting the loader when restoring state.        if (mCurFilter == null && newFilter == null) {            return true;        }        if (mCurFilter != null && mCurFilter.equals(newFilter)) {            return true;        }        mCurFilter = newFilter;        getSupportLoaderManager().restartLoader(0, null, this);        return true;    }    @Override    public Loader<Cursor> onCreateLoader(int id, Bundle args) {        // This is called when a new Loader needs to be created.  This        // sample only has one Loader, so we don't care about the ID.        // First, pick the base URI to use depending on whether we are        // currently filtering.        Uri baseUri;        if (mCurFilter != null) {            baseUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_FILTER_URI,                    Uri.encode(mCurFilter));        } else {            baseUri = ContactsContract.Contacts.CONTENT_URI;        }        // Now create and return a CursorLoader that will take care of        // creating a Cursor for the data being displayed.        String selection = "((" + ContactsContract.Contacts.DISPLAY_NAME + " NOTNULL) AND ("                + ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1) AND ("                + ContactsContract.Contacts.DISPLAY_NAME + " != '' ))";        return new CursorLoader(ContactsActivity.this,                baseUri,                CONTACTS_SUMMARY_PROJECTION,                selection,                null,                ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC"        );    }    @Override    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {        if (loader.getId() == 0) {            mAdapter.swapCursor(data);        }    }    @Override    public void onLoaderReset(Loader<Cursor> loader) {        mAdapter.swapCursor(null);    }    //有问题--->根据id查询电话号码    @Override    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {        Cursor cursor = (Cursor) parent.getItemAtPosition(position);        if (cursor == null) {            return;        }        int contactsId = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID));        String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));        // query the corresponding phone number via contact_id, noting the relation between the        // table {@link ContactsContract.Contacts} and the table {@link ContactsContract.CommonDataKind}        Cursor c = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,                new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " LIKE ?",                new String[]{String.valueOf(contactsId)},                null        );        String phoneNumber = "";        try {            if (c.moveToFirst()) {                int numberColumn = c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);                // a contact may have may phone number, so we need to fetch all. otherwise, you                 // can use{@link ContactsContract.CommonDataKinds.phone.TYPE.*} to limit the query                 //condition.                do {                    phoneNumber += c.getString(numberColumn) + ",";                } while (c.moveToNext());                Toast.makeText(ContactsActivity.this, name + "phone: " + phoneNumber, Toast.LENGTH_SHORT).show();            }        } finally {            if (c != null) {                c.close();            }        }    }}
0 0