类android.content.AsyncQueryHandler源码实例Demo

下面列出了怎么用android.content.AsyncQueryHandler的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: citra_android   文件: AddDirectoryHelper.java
public void addDirectory(String dir, AddDirectoryListener addDirectoryListener)
{
  AsyncQueryHandler handler = new AsyncQueryHandler(mContext.getContentResolver())
  {
    @Override
    protected void onInsertComplete(int token, Object cookie, Uri uri)
    {
      addDirectoryListener.onDirectoryAdded();
    }
  };

  ContentValues file = new ContentValues();
  file.put(GameDatabase.KEY_FOLDER_PATH, dir);

  handler.startInsert(0,                // We don't need to identify this call to the handler
          null,                        // We don't need to pass additional data to the handler
          GameProvider.URI_FOLDER,    // Tell the GameProvider we are adding a folder
          file);
}
 
源代码2 项目: xmpp   文件: ChatActivity.java
/**
 * 初始化数据
 */
public void initialData() {

    new AsyncQueryHandler(getContentResolver()) {

        @Override
        protected void onQueryComplete(int token, Object cookie,
                                       Cursor cursor) {
            list = new ArrayList<>();
            while (cursor.moveToNext()) {
                String main = cursor.getString(cursor.getColumnIndex("main"));
                String user = cursor.getString(cursor.getColumnIndex("user"));
                String nickname = cursor.getString(cursor.getColumnIndex("nickname"));
                String icon = cursor.getString(cursor.getColumnIndex("icon"));
                int type = cursor.getInt(cursor.getColumnIndex("type"));
                String content = cursor.getString(cursor.getColumnIndex("content"));
                String sex = cursor.getString(cursor.getColumnIndex("sex"));
                String too = cursor.getString(cursor.getColumnIndex("too"));
                String times = cursor.getString(cursor.getColumnIndex("time"));
                long time = Long.parseLong(times);
                int viewType = cursor.getInt(cursor.getColumnIndex("viewtype"));
                XmppChat xm = new XmppChat(main, user, nickname, icon, type, content, sex, too, viewType, time);
                Log.i("chat》》》》》》》》》》》", too + "\n" + user.toLowerCase());
                list.add(xm);
            }
            adapter = new ChatAdapter();
            msgListView.setAdapter(adapter);
            msgListView.setSelection(adapter.getCount() - 1);
        }

    }.startQuery(0, null, XmppFriendMessageProvider.CONTENT_CHATS_URI, null,
            "main=?", new String[]{user.getUser() + xf.getUser().getUser()}, null);
}
 
源代码3 项目: catnut   文件: ComposeTweetActivity.java
private void injectLayout() {
	// for panel
	mSlidingPaneLayout = (SlidingPaneLayout) findViewById(R.id.sliding_pane_layout);
	mEmotions = (GridView) findViewById(R.id.emotions);
	mEmotions.setAdapter(new EmotionsAdapter(this));
	mEmotions.setOnItemClickListener(this);
	mSlidingPaneLayout.setPanelSlideListener(new SliderListener());
	mSlidingPaneLayout.openPane();
	mSlidingPaneLayout.getViewTreeObserver().addOnGlobalLayoutListener(new FirstLayoutListener());
	// for tweet
	mAvatar = (ImageView) findViewById(R.id.avatar);
	mScreenName = (TextView) findViewById(R.id.screen_name);
	mText = (EditText) findViewById(R.id.text);
	mLocationMarker = findViewById(R.id.location_marker);
	// set data to layout...
	new AsyncQueryHandler(getContentResolver()) {
		@Override
		protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
			if (cursor.moveToNext()) {
				Picasso.with(ComposeTweetActivity.this)
						.load(cursor.getString(cursor.getColumnIndex(User.avatar_large)))
						.placeholder(R.drawable.error)
						.error(R.drawable.error)
						.into(mAvatar);
				mScreenName.setText("@" + cursor.getString(cursor.getColumnIndex(User.screen_name)));
			}
			cursor.close();
		}
	}.startQuery(0, null,
			CatnutProvider.parse(User.MULTIPLE, mApp.getAccessToken().uid),
			new String[]{User.avatar_large, User.screen_name}, null, null, null);
	// other stuffs...
	mText.addTextChangedListener(this);
}
 
public void getContactNameAsyncAndPost(@NonNull final Record record, final TextView textView) {

        String cachedContactName = mMemoryCacheHelper.getMemoryCacheForContactsName(record.getNumber());

        if (cachedContactName != null) {
            textView.setText(cachedContactName);
            record.setName(cachedContactName);

        } else {

            AsyncQueryHandler asyncQueryHandler = new AsyncQueryHandler(mContentResolver) {
                @Override
                protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
                    try {
                        if (cursor != null && cursor.moveToFirst()) {
                            mCursorLogger.log(cursor);
                            int contactNameRow = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
                            String contactName = cursor.getString(contactNameRow);

                            if (contactName != null && contactName.length() > 0) {
                                record.setName(contactName);
                                textView.setText(contactName);
                                record.setName(contactName);
                            }
                        }
                    } catch (Exception e) {
                        Log.d(TAG, "Error: --> ", e);
                    } finally {
                        if (cursor != null) {
                            cursor.close();
                        }
                    }
                }
            };

            Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
                    Uri.encode(record.getNumber()));
            String[] projection = {ContactsContract.PhoneLookup.DISPLAY_NAME};

            asyncQueryHandler.startQuery(0, null, contactUri, projection, null, null, null);
        }
    }
 
/**
     * create and insert db record using a real contact information.
     *
     * @param contactID - the target contact id. If id = -1 then get a random one
     */
    public void createDemoRecord(long contactID) {

        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        // TODO: 17.05.2017 @contact_ID
        String[] projection =
                {
                        ContactsContract.PhoneLookup.CONTACT_ID,
//                        ContactsContract.CommonDataKinds.Phone._ID, //the same as phonelookup_ID
                        ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                        ContactsContract.CommonDataKinds.Phone.NUMBER
                };

        String selection = contactID != 0 ? ContactsContract.PhoneLookup.CONTACT_ID + " = ?" : null;
        String[] selectionArguments = contactID != 0
                ? new String[]{String.valueOf(contactID)} : null;

        String orderBy = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";

        AsyncQueryHandler asyncQueryHandler = new AsyncQueryHandler(mContext.getContentResolver()) {
            @Override
            protected void onQueryComplete(int token, Object cookie, Cursor cursor) {

                if (cursor.getCount() == 0) {
//                    createDummyRecord(mContext);
                    return;
                }

                mCursorLogger.log(cursor);

                if (cursor.getCount() == 1) {
                    cursor.moveToFirst();
                } else {
                    int random = generateNumber(cursor.getCount() - 1, 0);
                    cursor.moveToPosition(random);
                }

                Contact contact = new MicroOrm().fromCursor(cursor, Contact.class);

//                long contact_id = cursor.getLong(cursor.getColumnIndex(ContactsContract.PhoneLookup.CONTACT_ID));
//                String contact_number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                ContentValues values = new ContentValues();
//                values.put(RecordDbContract.RecordItem.COLUMN_ID, String.valueOf(generateNumber(10000, 5000)));
                values.put(RecordDbContract.RecordItem.COLUMN_PATH, mConstant.DEMO_PATH);
                values.put(RecordDbContract.RecordItem.COLUMN_DATE, generateDate());
                values.put(RecordDbContract.RecordItem.COLUMN_NUMBER, contact.getNumber());
                values.put(RecordDbContract.RecordItem.COLUMN_CONTACT_ID, contact.get_ID());
                values.put(RecordDbContract.RecordItem.COLUMN_SIZE, generateNumber(100, 1));
                values.put(RecordDbContract.RecordItem.COLUMN_DURATION, generateNumber(100, 1));
                values.put(RecordDbContract.RecordItem.COLUMN_IS_INCOMING, generateBoolean());
                values.put(RecordDbContract.RecordItem.COLUMN_IS_LOVE, generateBoolean());
                values.put(RecordDbContract.RecordItem.COLUMN_IS_LOCKED, generateBoolean());
                values.put(RecordDbContract.RecordItem.COLUMN_IS_TO_DELETE, generateBoolean());

                mRecordsQueryHandler.startInsert(RecordsQueryHandler.INSERT_DEMO, null, RecordDbContract.CONTENT_URL, values);
            }
        };

        // retrieve all contacts
        asyncQueryHandler.startQuery(0, null, uri, projection, selection, selectionArguments, orderBy);

    }
 
源代码6 项目: AndroidDemo   文件: CallLogActivity.java
@Override
protected void init() {
    listView = (ListView) findViewById(R.id.listView);
    adapter = new CommonAdapter<String>(this, data, android.R.layout.simple_list_item_1) {
        @Override
        protected void fillData(ViewHolder holder, int position) {
            ((TextView) holder.getView(android.R.id.text1)).setText(data.get(position));
        }
    };
    listView.setAdapter(adapter);

    asyncHandler = new AsyncQueryHandler(getContentResolver()) {
        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    String number = cursor.getString(1);
                    if (TextUtils.isEmpty(number))
                        continue;
                    String name = cursor.getString(0);
                    long date = cursor.getLong(2);
                    int duration = cursor.getInt(3);
                    duration = duration < 0 ? 0 : duration;
                    int type = cursor.getInt(4);
                    String v;
                    if (name == null || name.trim().length() == 0 || name.equalsIgnoreCase("null"))
                        v = String.format(Locale.getDefault(), "%s\n%s   %d%s   %s",
                                number, format.format(new Date(date)),
                                duration < 60 ? duration : duration / 60,
                                duration < 60 ? "分钟" : "小时",
                                type == CallLog.Calls.INCOMING_TYPE ? "打入" : "拨出");
                    else
                        v = String.format(Locale.getDefault(), "%s   %s\n%s   %d%s   %s",
                                name, format.format(new Date(date)), number,
                                duration < 60 ? duration : duration / 60,
                                duration < 60 ? "分钟" : "小时",
                                type == CallLog.Calls.INCOMING_TYPE ? "打入" : "拨出");
                    data.add(v);
                }
                cursor.close();
                adapter.notifyDataSetChanged();
            }
        }
    };
    if (Build.VERSION_CODES.JELLY_BEAN <= Build.VERSION.SDK_INT)
        checkPermission();
    else
        asyncLoadData();
}
 
源代码7 项目: catnut   文件: MainActivity.java
private void prepareDrawer() {
	// for drawer
	mActionBar.setDisplayHomeAsUpEnabled(true);
	mActionBar.setHomeButtonEnabled(true);
	// for user' s profile
	new AsyncQueryHandler(getContentResolver()) {
		@Override
		protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
			if (cursor.moveToNext()) {
				mNick = cursor.getString(cursor.getColumnIndex(User.screen_name));
				mTextNick.setText(mNick);
				Picasso.with(MainActivity.this)
						.load(cursor.getString(cursor.getColumnIndex(User.avatar_large)))
						.placeholder(R.drawable.error)
						.error(R.drawable.error)
						.into(mProfileCover);
				TextView location = (TextView) findViewById(R.id.location);
				location.setText(cursor.getString(cursor.getColumnIndex(User.location)));

				String description = cursor.getString(cursor.getColumnIndex(User.description));
				mDescription.setText(TextUtils.isEmpty(description) ? getString(R.string.no_description) : description);

				View flowingCount = findViewById(R.id.following_count);
				CatnutUtils.setText(flowingCount, android.R.id.text1, cursor.getString(cursor.getColumnIndex(User.friends_count)));
				CatnutUtils.setText(flowingCount, android.R.id.text2, getString(R.string.followings));
				View flowerCount = findViewById(R.id.followers_count);
				CatnutUtils.setText(flowerCount, android.R.id.text1, cursor.getString(cursor.getColumnIndex(User.followers_count)));
				CatnutUtils.setText(flowerCount, android.R.id.text2, getString(R.string.followers));
				View tweetsCount = findViewById(R.id.tweets_count);

				tweetsCount.setOnClickListener(MainActivity.this);
				flowingCount.setOnClickListener(MainActivity.this);
				flowerCount.setOnClickListener(MainActivity.this);
				CatnutUtils.setText(tweetsCount, android.R.id.text1, cursor.getString(cursor.getColumnIndex(User.statuses_count)));
				CatnutUtils.setText(tweetsCount, android.R.id.text2, getString(R.string.tweets));
			}
			cursor.close();
		}
	}.startQuery(
			0, null,
			CatnutProvider.parse(User.MULTIPLE, mApp.getAccessToken().uid),
			new String[]{
					User.screen_name,
					User.avatar_large,
					User.description,
					User.statuses_count,
					User.followers_count,
					User.friends_count,
					User.verified,
					User.location
			},
			null, null, null
	);
}
 
 类所在包
 同包方法