Example usage for android.database Cursor getBlob

List of usage examples for android.database Cursor getBlob

Introduction

In this page you can find the example usage for android.database Cursor getBlob.

Prototype

byte[] getBlob(int columnIndex);

Source Link

Document

Returns the value of the requested column as a byte array.

Usage

From source file:org.tvbrowser.tvbrowser.TvBrowser.java

private void showChannelSelectionInternal(final String selection, final String title, final String help,
        final boolean delete) {
    String[] projection = {//w w w.  j  av  a  2 s .  c o  m
            TvBrowserContentProvider.CHANNEL_TABLE + "." + TvBrowserContentProvider.KEY_ID + " AS "
                    + TvBrowserContentProvider.KEY_ID,
            TvBrowserContentProvider.GROUP_KEY_DATA_SERVICE_ID, TvBrowserContentProvider.CHANNEL_KEY_NAME,
            TvBrowserContentProvider.CHANNEL_KEY_SELECTION, TvBrowserContentProvider.CHANNEL_KEY_CATEGORY,
            TvBrowserContentProvider.CHANNEL_KEY_LOGO, TvBrowserContentProvider.CHANNEL_KEY_ALL_COUNTRIES };

    ContentResolver cr = getContentResolver();
    Cursor channels = cr.query(TvBrowserContentProvider.CONTENT_URI_CHANNELS_WITH_GROUP, projection, selection,
            null, TvBrowserContentProvider.CHANNEL_KEY_NAME);
    channels.moveToPosition(-1);

    // populate array list with all available channels
    final ArrayListWrapper channelSelectionList = new ArrayListWrapper();
    ArrayList<Country> countryList = new ArrayList<Country>();

    int channelIdColumn = channels.getColumnIndex(TvBrowserContentProvider.KEY_ID);
    int categoryColumn = channels.getColumnIndex(TvBrowserContentProvider.CHANNEL_KEY_CATEGORY);
    int logoColumn = channels.getColumnIndex(TvBrowserContentProvider.CHANNEL_KEY_LOGO);
    int dataServiceColumn = channels.getColumnIndex(TvBrowserContentProvider.GROUP_KEY_DATA_SERVICE_ID);
    int nameColumn = channels.getColumnIndex(TvBrowserContentProvider.CHANNEL_KEY_NAME);
    int countyColumn = channels.getColumnIndex(TvBrowserContentProvider.CHANNEL_KEY_ALL_COUNTRIES);
    int selectionColumn = channels.getColumnIndex(TvBrowserContentProvider.CHANNEL_KEY_SELECTION);
    ;
    while (channels.moveToNext()) {
        int channelID = channels.getInt(channelIdColumn);
        int category = channels.getInt(categoryColumn);
        byte[] logo = channels.getBlob(logoColumn);
        String dataService = channels.getString(dataServiceColumn);
        String name = channels.getString(nameColumn);
        String countries = channels.getString(countyColumn);
        boolean isSelected = channels.getInt(selectionColumn) == 1 && !delete;

        if (countries.contains("$")) {
            String[] values = countries.split("\\$");

            for (String country : values) {
                Country test = new Country(new Locale(country, country));

                if (!countryList.contains(test) && test.mLocale.getDisplayCountry().trim().length() > 0) {
                    countryList.add(test);
                }
            }
        } else {
            Country test = new Country(new Locale(countries, countries));

            if (!countryList.contains(test) && test.mLocale.getDisplayCountry().trim().length() > 0) {
                countryList.add(test);
            }
        }

        Bitmap channelLogo = UiUtils.createBitmapFromByteArray(logo);

        if (channelLogo != null) {
            BitmapDrawable l = new BitmapDrawable(getResources(), channelLogo);

            ColorDrawable background = new ColorDrawable(SettingConstants.LOGO_BACKGROUND_COLOR);
            background.setBounds(0, 0, channelLogo.getWidth() + 2, channelLogo.getHeight() + 2);

            LayerDrawable logoDrawable = new LayerDrawable(new Drawable[] { background, l });
            logoDrawable.setBounds(background.getBounds());

            l.setBounds(2, 2, channelLogo.getWidth(), channelLogo.getHeight());

            channelLogo = UiUtils.drawableToBitmap(logoDrawable);
        }

        channelSelectionList.add(new ChannelSelection(channelID, name, category, countries, channelLogo,
                isSelected, SettingConstants.EPG_DONATE_KEY.equals(dataService)));
    }

    // sort countries for filtering
    Collections.sort(countryList, new Comparator<Country>() {
        @Override
        public int compare(Country lhs, Country rhs) {
            return lhs.toString().compareToIgnoreCase(rhs.toString());
        }
    });

    countryList.add(0, new Country(null));

    channels.close();

    // create filter for filtering of category and country
    final ChannelFilter filter = new ChannelFilter(SettingConstants.TV_CATEGORY, null);

    // create default logo for channels without logo
    final Bitmap defaultLogo = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);

    final Set<String> firstDeletedChannels = PrefUtils.getStringSetValue(R.string.PREF_FIRST_DELETED_CHANNELS,
            new HashSet<String>());
    final Set<String> keptDeletedChannels = PrefUtils.getStringSetValue(R.string.PREF_KEPT_DELETED_CHANNELS,
            new HashSet<String>());

    final int firstDeletedColor = getResources().getColor(R.color.pref_first_deleted_channels);
    final int keptDeletedColor = getResources().getColor(R.color.pref_kept_deleted_channels);

    // Custom array adapter for channel selection
    final ArrayAdapter<ChannelSelection> channelSelectionAdapter = new ArrayAdapter<ChannelSelection>(
            TvBrowser.this, R.layout.channel_row, channelSelectionList) {
        public View getView(int position, View convertView, ViewGroup parent) {
            ChannelSelection value = getItem(position);
            ViewHolder holder = null;

            if (convertView == null) {
                LayoutInflater mInflater = (LayoutInflater) getContext()
                        .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

                holder = new ViewHolder();

                convertView = mInflater.inflate(R.layout.channel_row, getParentViewGroup(), false);

                holder.mTextView = (TextView) convertView.findViewById(R.id.row_of_channel_text);
                holder.mCheckBox = (CheckBox) convertView.findViewById(R.id.row_of_channel_selection);
                holder.mLogo = (ImageView) convertView.findViewById(R.id.row_of_channel_icon);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            SpannableStringBuilder nameBuilder = new SpannableStringBuilder(value.toString());

            String channelID = String.valueOf(value.getChannelID());

            if (keptDeletedChannels.contains(channelID)) {
                nameBuilder.setSpan(new ForegroundColorSpan(keptDeletedColor), 0, value.toString().length(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else if (firstDeletedChannels.contains(channelID)) {
                nameBuilder.setSpan(new ForegroundColorSpan(firstDeletedColor), 0, value.toString().length(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }

            if (value.isEpgDonateChannel()) {
                nameBuilder.append("\n(EPGdonate)");
                nameBuilder.setSpan(new RelativeSizeSpan(0.65f), value.toString().length(),
                        nameBuilder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }

            holder.mTextView.setText(nameBuilder);
            holder.mCheckBox.setChecked(value.isSelected());

            Bitmap logo = value.getLogo();

            if (logo != null) {
                holder.mLogo.setImageBitmap(logo);
            } else {
                holder.mLogo.setImageBitmap(defaultLogo);
            }

            return convertView;
        }
    };

    // inflate channel selection view
    View channelSelectionView = getLayoutInflater().inflate(R.layout.dialog_channel_selection_list,
            getParentViewGroup(), false);
    channelSelectionView.findViewById(R.id.channel_selection_selection_buttons).setVisibility(View.GONE);
    channelSelectionView.findViewById(R.id.channel_selection_input_id_name).setVisibility(View.GONE);

    TextView infoView = (TextView) channelSelectionView.findViewById(R.id.channel_selection_label_id_name);

    if (help != null) {
        infoView.setText(help);
        infoView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
                getResources().getDimension(R.dimen.epg_donate_info_font_size));
    } else {
        infoView.setVisibility(View.GONE);
    }

    // get spinner for country filtering and create array adapter with all available countries
    Spinner country = (Spinner) channelSelectionView.findViewById(R.id.channel_country_value);

    final ArrayAdapter<Country> countryListAdapter = new ArrayAdapter<Country>(this,
            android.R.layout.simple_spinner_item, countryList);
    countryListAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    country.setAdapter(countryListAdapter);

    // add item selection listener to react of user setting filter for country
    country.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            Country country = countryListAdapter.getItem(position);

            filter.mCountry = country.getCountry();
            channelSelectionList.setFilter(filter);
            channelSelectionAdapter.notifyDataSetChanged();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

    // get spinner for category selection and add listener to react to user category selection
    Spinner category = (Spinner) channelSelectionView.findViewById(R.id.channel_category_value);
    category.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            switch (position) {
            case 1:
                filter.mCategory = SettingConstants.TV_CATEGORY;
                break;
            case 2:
                filter.mCategory = SettingConstants.RADIO_CATEGORY;
                break;
            case 3:
                filter.mCategory = SettingConstants.CINEMA_CATEGORY;
                break;

            default:
                filter.mCategory = SettingConstants.NO_CATEGORY;
                break;
            }

            channelSelectionList.setFilter(filter);
            channelSelectionAdapter.notifyDataSetChanged();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

    if (delete) {
        channelSelectionView.findViewById(R.id.channel_country_label).setVisibility(View.GONE);
        channelSelectionView.findViewById(R.id.channel_category_label).setVisibility(View.GONE);

        country.setVisibility(View.GONE);
        category.setVisibility(View.GONE);
    }

    // get the list view of the layout and add adapter with available channels
    ListView list = (ListView) channelSelectionView.findViewById(R.id.channel_selection_list);
    list.setAdapter(channelSelectionAdapter);

    // add listener to react to user selection of channels
    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            CheckBox check = (CheckBox) view.findViewById(R.id.row_of_channel_selection);

            if (check != null) {
                check.setChecked(!check.isChecked());
                channelSelectionAdapter.getItem(position).setSelected(check.isChecked());
            }
        }
    });

    // show dialog only if channels are available
    if (!channelSelectionList.isEmpty()) {
        AlertDialog.Builder builder = new AlertDialog.Builder(TvBrowser.this);

        if (title == null) {
            builder.setTitle(R.string.select_channels);
        } else {
            builder.setTitle(title);
        }

        builder.setView(channelSelectionView);

        builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                boolean somethingSelected = false;
                boolean somethingChanged = false;

                Iterator<ChannelSelection> it = channelSelectionList.superIterator();

                StringBuilder deleteWhere = new StringBuilder();
                HashSet<String> keep = new HashSet<String>();

                while (it.hasNext()) {
                    ChannelSelection sel = it.next();

                    if (sel.isSelected() && !sel.wasSelected()) {
                        somethingChanged = somethingSelected = true;

                        if (delete) {
                            if (deleteWhere.length() > 0) {
                                deleteWhere.append(", ");
                            }

                            deleteWhere.append(sel.getChannelID());
                        } else {
                            ContentValues values = new ContentValues();

                            values.put(TvBrowserContentProvider.CHANNEL_KEY_SELECTION, 1);

                            getContentResolver().update(
                                    ContentUris.withAppendedId(TvBrowserContentProvider.CONTENT_URI_CHANNELS,
                                            sel.getChannelID()),
                                    values, null, null);
                        }
                    } else if (!sel.isSelected() && sel.wasSelected()) {
                        somethingChanged = true;

                        ContentValues values = new ContentValues();

                        values.put(TvBrowserContentProvider.CHANNEL_KEY_SELECTION, 0);

                        getContentResolver().update(
                                ContentUris.withAppendedId(TvBrowserContentProvider.CONTENT_URI_CHANNELS,
                                        sel.getChannelID()),
                                values, null, null);

                        getContentResolver().delete(TvBrowserContentProvider.CONTENT_URI_DATA_VERSION,
                                TvBrowserContentProvider.CHANNEL_KEY_CHANNEL_ID + "=" + sel.getChannelID(),
                                null);
                        getContentResolver().delete(TvBrowserContentProvider.CONTENT_URI_DATA,
                                TvBrowserContentProvider.CHANNEL_KEY_CHANNEL_ID + "=" + sel.getChannelID(),
                                null);
                    } else if (delete && !sel.isSelected()) {
                        keep.add(String.valueOf(sel.getChannelID()));
                    }
                }

                if (delete) {
                    if (deleteWhere.length() > 0) {
                        deleteWhere.insert(0, TvBrowserContentProvider.KEY_ID + " IN ( ");
                        deleteWhere.append(" ) ");

                        Log.d("info2", "DELETE WHERE FOR REMOVED CHANNELS " + deleteWhere.toString());

                        int count = getContentResolver().delete(TvBrowserContentProvider.CONTENT_URI_CHANNELS,
                                deleteWhere.toString(), null);

                        Log.d("info2", "REMOVED CHANNELS COUNT " + count);
                    }

                    Editor edit = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this).edit();
                    edit.putStringSet(getString(R.string.PREF_KEPT_DELETED_CHANNELS), keep);
                    edit.commit();
                }

                // if something was changed we need to update channel list bar in program list and the complete program table
                if (somethingChanged) {
                    SettingConstants.initializeLogoMap(TvBrowser.this, true);
                    updateProgramListChannelBar();
                }

                // if something was selected we need to download new data
                if (somethingSelected && !delete) {
                    checkTermsAccepted();
                }
            }
        });

        builder.setNegativeButton(android.R.string.cancel, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (delete) {
                    HashSet<String> keep = new HashSet<String>();
                    Iterator<ChannelSelection> it = channelSelectionList.superIterator();

                    while (it.hasNext()) {
                        ChannelSelection sel = it.next();

                        keep.add(String.valueOf(sel.getChannelID()));
                    }

                    Editor edit = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this).edit();
                    edit.putStringSet(getString(R.string.PREF_KEPT_DELETED_CHANNELS), keep);
                    edit.commit();
                }
            }
        });

        builder.show();
    }

    selectingChannels = false;
}

From source file:org.m2x.rssreader.service.FetcherService.java

private int refreshFeed(String feedId) {
    RssAtomParser handler = null;//w  w  w  . j a v a  2 s  .c o m

    ContentResolver cr = getContentResolver();
    Cursor cursor = cr.query(FeedColumns.CONTENT_URI(feedId), null, null, null, null);

    if (!cursor.moveToFirst()) {
        cursor.close();
        return 0;
    }

    int urlPosition = cursor.getColumnIndex(FeedColumns.URL);
    int titlePosition = cursor.getColumnIndex(FeedColumns.NAME);
    int fetchmodePosition = cursor.getColumnIndex(FeedColumns.FETCH_MODE);
    int realLastUpdatePosition = cursor.getColumnIndex(FeedColumns.REAL_LAST_UPDATE);
    int iconPosition = cursor.getColumnIndex(FeedColumns.ICON);
    int retrieveFullTextPosition = cursor.getColumnIndex(FeedColumns.RETRIEVE_FULLTEXT);

    HttpURLConnection connection = null;
    try {
        String feedUrl = cursor.getString(urlPosition);
        connection = NetworkUtils.setupConnection(feedUrl);
        String contentType = connection.getContentType();
        int fetchMode = cursor.getInt(fetchmodePosition);

        handler = new RssAtomParser(new Date(cursor.getLong(realLastUpdatePosition)), feedId,
                cursor.getString(titlePosition), feedUrl, cursor.getInt(retrieveFullTextPosition) == 1);
        handler.setFetchImages(PrefUtils.getBoolean(PrefUtils.FETCH_PICTURES, true));

        if (fetchMode == 0) {
            if (contentType != null && contentType.startsWith(CONTENT_TYPE_TEXT_HTML)) {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(NetworkUtils.getConnectionInputStream(connection)));

                String line;
                int posStart = -1;

                while ((line = reader.readLine()) != null) {
                    if (line.contains(HTML_BODY)) {
                        break;
                    } else {
                        Matcher matcher = FEED_LINK_PATTERN.matcher(line);

                        if (matcher.find()) { // not "while" as only one link is needed
                            line = matcher.group();
                            posStart = line.indexOf(HREF);

                            if (posStart > -1) {
                                String url = line.substring(posStart + 6, line.indexOf('"', posStart + 10))
                                        .replace("&amp", "&");

                                ContentValues values = new ContentValues();

                                if (url.startsWith("/")) {
                                    int index = feedUrl.indexOf('/', 8);

                                    if (index > -1) {
                                        url = feedUrl.substring(0, index) + url;
                                    } else {
                                        url = feedUrl + url;
                                    }
                                } else if (!url.startsWith(Constants.HTTP_SCHEME)
                                        && !url.startsWith(Constants.HTTPS_SCHEME)) {
                                    url = feedUrl + '/' + url;
                                }
                                values.put(FeedColumns.URL, url);
                                cr.update(FeedColumns.CONTENT_URI(feedId), values, null, null);
                                connection.disconnect();
                                connection = NetworkUtils.setupConnection(url);
                                contentType = connection.getContentType();
                                break;
                            }
                        }
                    }
                }
                // this indicates a badly configured feed
                if (posStart == -1) {
                    connection.disconnect();
                    connection = NetworkUtils.setupConnection(feedUrl);
                    contentType = connection.getContentType();
                }
            }

            if (contentType != null) {
                int index = contentType.indexOf(CHARSET);

                if (index > -1) {
                    int index2 = contentType.indexOf(';', index);

                    try {
                        Xml.findEncodingByName(index2 > -1 ? contentType.substring(index + 8, index2)
                                : contentType.substring(index + 8));
                        fetchMode = FETCHMODE_DIRECT;
                    } catch (UnsupportedEncodingException usee) {
                        fetchMode = FETCHMODE_REENCODE;
                    }
                } else {
                    fetchMode = FETCHMODE_REENCODE;
                }

            } else {
                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(NetworkUtils.getConnectionInputStream(connection)));

                char[] chars = new char[20];

                int length = bufferedReader.read(chars);

                String xmlDescription = new String(chars, 0, length);

                connection.disconnect();
                connection = NetworkUtils.setupConnection(connection.getURL());

                int start = xmlDescription != null ? xmlDescription.indexOf(ENCODING) : -1;

                if (start > -1) {
                    try {
                        Xml.findEncodingByName(
                                xmlDescription.substring(start + 10, xmlDescription.indexOf('"', start + 11)));
                        fetchMode = FETCHMODE_DIRECT;
                    } catch (UnsupportedEncodingException usee) {
                        fetchMode = FETCHMODE_REENCODE;
                    }
                } else {
                    // absolutely no encoding information found
                    fetchMode = FETCHMODE_DIRECT;
                }
            }

            ContentValues values = new ContentValues();
            values.put(FeedColumns.FETCH_MODE, fetchMode);
            cr.update(FeedColumns.CONTENT_URI(feedId), values, null, null);
        }

        switch (fetchMode) {
        default:
        case FETCHMODE_DIRECT: {
            if (contentType != null) {
                int index = contentType.indexOf(CHARSET);

                int index2 = contentType.indexOf(';', index);

                InputStream inputStream = NetworkUtils.getConnectionInputStream(connection);
                Xml.parse(inputStream,
                        Xml.findEncodingByName(index2 > -1 ? contentType.substring(index + 8, index2)
                                : contentType.substring(index + 8)),
                        handler);
            } else {
                InputStreamReader reader = new InputStreamReader(
                        NetworkUtils.getConnectionInputStream(connection));
                Xml.parse(reader, handler);
            }
            break;
        }
        case FETCHMODE_REENCODE: {
            ByteArrayOutputStream ouputStream = new ByteArrayOutputStream();
            InputStream inputStream = NetworkUtils.getConnectionInputStream(connection);

            byte[] byteBuffer = new byte[4096];

            int n;
            while ((n = inputStream.read(byteBuffer)) > 0) {
                ouputStream.write(byteBuffer, 0, n);
            }

            String xmlText = ouputStream.toString();

            int start = xmlText != null ? xmlText.indexOf(ENCODING) : -1;

            if (start > -1) {
                Xml.parse(new StringReader(new String(ouputStream.toByteArray(),
                        xmlText.substring(start + 10, xmlText.indexOf('"', start + 11)))), handler);
            } else {
                // use content type
                if (contentType != null) {
                    int index = contentType.indexOf(CHARSET);

                    if (index > -1) {
                        int index2 = contentType.indexOf(';', index);

                        try {
                            StringReader reader = new StringReader(new String(ouputStream.toByteArray(),
                                    index2 > -1 ? contentType.substring(index + 8, index2)
                                            : contentType.substring(index + 8)));
                            Xml.parse(reader, handler);
                        } catch (Exception ignored) {
                        }
                    } else {
                        StringReader reader = new StringReader(new String(ouputStream.toByteArray()));
                        Xml.parse(reader, handler);
                    }
                }
            }
            break;
        }
        }

        connection.disconnect();
    } catch (FileNotFoundException e) {
        if (handler == null || (handler != null && !handler.isDone() && !handler.isCancelled())) {
            ContentValues values = new ContentValues();

            // resets the fetchmode to determine it again later
            values.put(FeedColumns.FETCH_MODE, 0);

            values.put(FeedColumns.ERROR, getString(R.string.error_feed_error));
            cr.update(FeedColumns.CONTENT_URI(feedId), values, null, null);
        }
    } catch (Throwable e) {
        if (handler == null || (handler != null && !handler.isDone() && !handler.isCancelled())) {
            ContentValues values = new ContentValues();

            // resets the fetchmode to determine it again later
            values.put(FeedColumns.FETCH_MODE, 0);

            values.put(FeedColumns.ERROR,
                    e.getMessage() != null ? e.getMessage() : getString(R.string.error_feed_process));
            cr.update(FeedColumns.CONTENT_URI(feedId), values, null, null);
        }
    } finally {

        /* check and optionally find favicon */
        try {
            if (handler != null && cursor.getBlob(iconPosition) == null) {
                String feedLink = handler.getFeedLink();
                if (feedLink != null) {
                    NetworkUtils.retrieveFavicon(this, new URL(feedLink), feedId);
                } else {
                    NetworkUtils.retrieveFavicon(this, connection.getURL(), feedId);
                }
            }
        } catch (Throwable ignored) {
        }

        if (connection != null) {
            connection.disconnect();
        }
    }

    cursor.close();

    return handler != null ? handler.getNewCount() : 0;
}