Friday, December 9, 2011

Open webpage using Android app and mark URL as Bookmark

Few of fellow developer friends drop me a query about an app which open a browser with predefined URL & mark that URL as bookmark. The solution is as follows:-
To open a browser with in a app, you have to create a browser Intent.

        private void browseURL(String url) {
            Intent browseIntent = new Intent(Intent.ACTION_VIEW);

Now before saving this URL as a bookmark, you need to check whether it's already exist or not. So to read bookmarks we need to access Android's Browser content provider using ContentResolver object. You can then use the ContentResolver's methods to interact with whatever content providers you're interested in.

private boolean isBookmarked() {
            boolean isBookemarked = false;                
            String[] projection = new String[] {
         Cursor mCur = managedQuery(Browser.BOOKMARKS_URI, projection,            Browser.BookmarkColumns.URL + " like '" +   m_url + "' AND " + Browser.BookmarkColumns.BOOKMARK + " = 1", null, null);
int titleIdx = mCur.getColumnIndex(Browser.BookmarkColumns.TITLE);
int urlIdx = mCur.getColumnIndex(Browser.BookmarkColumns.URL);
            String bTitle = "";
            String bUrl = "";
            while (mCur.isAfterLast() == false) {
                bTitle = mCur.getString(titleIdx);
                bUrl = mCur.getString(urlIdx);
if(bTitle.equalsIgnoreCase(m_title) && bUrl.equalsIgnoreCase(m_url)) {
                isBookemarked = true;
            return isBookemarked;                

The above method will query the Browser.BookmarkColumns table which containing both bookmarks and history items. To read this table requires the READ_HISTORY_BOOKMARKS permission and writing to it requires the WRITE_HISTORY_BOOKMARKS permission. Now if url is not marked in bookmarks then you need to save the url in bookmark.

private void saveBookmark(String title, String url) {
            final ContentValues bookmarkValues = new ContentValues();
            bookmarkValues.put(Browser.BookmarkColumns.TITLE, title);
            bookmarkValues.put(Browser.BookmarkColumns.URL, url);
            bookmarkValues.put(Browser.BookmarkColumns.BOOKMARK, 1);
            final Uri newBookmark = getContentResolver().insert(Browser.BOOKMARKS_URI, bookmarkValues);                

ContentValues class is used to store a set of values that the ContentResolver can process. To verify you can check the browser bookmarks for new entry.