Example usage for android.database Cursor getPosition

List of usage examples for android.database Cursor getPosition

Introduction

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

Prototype

int getPosition();

Source Link

Document

Returns the current position of the cursor in the row set.

Usage

From source file:com.remobile.contacts.ContactAccessorSdk5.java

/**
 * Creates an array of contacts from the cursor you pass in
 *
 * @param limit        max number of contacts for the array
 * @param populate     whether or not you should populate a certain value
 * @param c            the cursor//from  w  ww .  j a va  2s  . co m
 * @return             a JSONArray of contacts
 */
private JSONArray populateContactArray(int limit, HashMap<String, Boolean> populate, Cursor c) {

    String contactId = "";
    String rawId = "";
    String oldContactId = "";
    boolean newContact = true;
    String mimetype = "";

    JSONArray contacts = new JSONArray();
    JSONObject contact = new JSONObject();
    JSONArray organizations = new JSONArray();
    JSONArray addresses = new JSONArray();
    JSONArray phones = new JSONArray();
    JSONArray emails = new JSONArray();
    JSONArray ims = new JSONArray();
    JSONArray websites = new JSONArray();
    JSONArray photos = new JSONArray();

    // Column indices
    int colContactId = c.getColumnIndex(ContactsContract.Data.CONTACT_ID);
    int colRawContactId = c.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID);
    int colMimetype = c.getColumnIndex(ContactsContract.Data.MIMETYPE);
    int colDisplayName = c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME);
    int colNote = c.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE);
    int colNickname = c.getColumnIndex(ContactsContract.CommonDataKinds.Nickname.NAME);
    int colBirthday = c.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE);
    int colEventType = c.getColumnIndex(ContactsContract.CommonDataKinds.Event.TYPE);

    if (c.getCount() > 0) {
        while (c.moveToNext() && (contacts.length() <= (limit - 1))) {
            try {
                contactId = c.getString(colContactId);
                rawId = c.getString(colRawContactId);

                // If we are in the first row set the oldContactId
                if (c.getPosition() == 0) {
                    oldContactId = contactId;
                }

                // When the contact ID changes we need to push the Contact object
                // to the array of contacts and create new objects.
                if (!oldContactId.equals(contactId)) {
                    // Populate the Contact object with it's arrays
                    // and push the contact into the contacts array
                    contacts.put(populateContact(contact, organizations, addresses, phones, emails, ims,
                            websites, photos));

                    // Clean up the objects
                    contact = new JSONObject();
                    organizations = new JSONArray();
                    addresses = new JSONArray();
                    phones = new JSONArray();
                    emails = new JSONArray();
                    ims = new JSONArray();
                    websites = new JSONArray();
                    photos = new JSONArray();

                    // Set newContact to true as we are starting to populate a new contact
                    newContact = true;
                }

                // When we detect a new contact set the ID and display name.
                // These fields are available in every row in the result set returned.
                if (newContact) {
                    newContact = false;
                    contact.put("id", contactId);
                    contact.put("rawId", rawId);
                }

                // Grab the mimetype of the current row as it will be used in a lot of comparisons
                mimetype = c.getString(colMimetype);

                if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                        && isRequired("name", populate)) {
                    contact.put("displayName", c.getString(colDisplayName));
                }

                if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                        && isRequired("name", populate)) {
                    contact.put("name", nameQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                        && isRequired("phoneNumbers", populate)) {
                    phones.put(phoneQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                        && isRequired("emails", populate)) {
                    emails.put(emailQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
                        && isRequired("addresses", populate)) {
                    addresses.put(addressQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
                        && isRequired("organizations", populate)) {
                    organizations.put(organizationQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE)
                        && isRequired("ims", populate)) {
                    ims.put(imQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE)
                        && isRequired("note", populate)) {
                    contact.put("note", c.getString(colNote));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE)
                        && isRequired("nickname", populate)) {
                    contact.put("nickname", c.getString(colNickname));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE)
                        && isRequired("urls", populate)) {
                    websites.put(websiteQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE)) {
                    if (isRequired("birthday", populate)
                            && ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY == c.getInt(colEventType)) {
                        contact.put("birthday", c.getString(colBirthday));
                    }
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
                        && isRequired("photos", populate)) {
                    JSONObject photo = photoQuery(c, contactId);
                    if (photo != null) {
                        photos.put(photo);
                    }
                }
            } catch (JSONException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }

            // Set the old contact ID
            oldContactId = contactId;

        }

        // Push the last contact into the contacts array
        if (contacts.length() < limit) {
            contacts.put(
                    populateContact(contact, organizations, addresses, phones, emails, ims, websites, photos));
        }
    }
    c.close();
    return contacts;
}

From source file:com.enadein.carlogbook.adapter.LogAdapter.java

@Override
public void bindView(View view, Context context, Cursor cursor) {
    int type = cursor.getInt(cursor.getColumnIndex(ProviderDescriptor.LogView.Cols.TYPE_LOG));

    int idIdx = cursor.getColumnIndex(ProviderDescriptor.LogView.Cols._ID);
    int odometerIdx = cursor.getColumnIndex(ProviderDescriptor.LogView.Cols.ODOMETER);
    int priceIdx = cursor.getColumnIndex(ProviderDescriptor.LogView.Cols.PRICE);
    int dateIdx = cursor.getColumnIndex(ProviderDescriptor.LogView.Cols.DATE);

    double price = cursor.getDouble(priceIdx);
    String date = CommonUtils.formatDate(new Date(cursor.getLong(dateIdx)));

    int odometer = cursor.getInt(odometerIdx);
    int id = cursor.getInt(idIdx);

    if (type == ProviderDescriptor.Log.Type.FUEL) {
        LogFuelHolder logFuelHolder = (LogFuelHolder) view.getTag();
        int fuelValueIdx = cursor.getColumnIndex(ProviderDescriptor.LogView.Cols.FUEL_VOLUME);
        double fuelValue = cursor.getDouble(fuelValueIdx);

        double priceTotalDouble = fuelValue * price;

        int stationNameIdx = cursor.getColumnIndex(ProviderDescriptor.LogView.Cols.STATION_NAME);
        String stationName = cursor.getString(stationNameIdx);

        int fuelNameIdx = cursor.getColumnIndex(ProviderDescriptor.LogView.Cols.FUEL_NAME);
        String fuelName = cursor.getString(fuelNameIdx);

        logFuelHolder.odometerView.setText(String.valueOf(odometer));
        unitFacade.appendDistUnit(logFuelHolder.odometerView, false);
        logFuelHolder.dateView.setText(date);
        logFuelHolder.fuelValueView.setText(CommonUtils.formatFuel(fuelValue, unitFacade));
        unitFacade.appendFuelUnit(logFuelHolder.fuelValueView, false);
        logFuelHolder.priceTotal.setText(CommonUtils.formatPriceNew(priceTotalDouble, unitFacade));
        unitFacade.appendCurrency(logFuelHolder.priceTotal, false, false);
        logFuelHolder.fuelView.setText(fuelName + "(" + stationName + ")");
        logFuelHolder.imgType.setBackgroundResource(R.drawable.fuel);
        logFuelHolder.id = id;/*from   w  ww.ja  v  a  2  s. c  o  m*/
        rateLoader.calculateFuelRate(logFuelHolder.rateView, id);
    } else {
        int nameIdx = cursor.getColumnIndex(ProviderDescriptor.LogView.Cols.NAME);
        int typeIdx = cursor.getColumnIndex(ProviderDescriptor.LogView.Cols.TYPE_ID);

        String name = cursor.getString(nameIdx);
        int typeId = cursor.getInt(typeIdx);

        LogHolder logHolder = (LogHolder) view.getTag();
        logHolder.dateView.setText(date);
        logHolder.odometerView.setText(String.valueOf(odometer));
        unitFacade.appendDistUnit(logHolder.odometerView, false);
        logHolder.imgType.setBackgroundResource(DataInfo.images.get(typeId));
        logHolder.priceTotal.setText(CommonUtils.formatPriceNew(price, unitFacade));
        unitFacade.appendCurrency(logHolder.priceTotal, false, false);
        logHolder.nameView.setText(name);

        if (typeId == 0) {
            int fuelNameIdx = cursor.getColumnIndex(ProviderDescriptor.LogView.Cols.FUEL_NAME);
            String fuelName = cursor.getString(fuelNameIdx);
            logHolder.typeView.setText(fuelName);
        } else {
            logHolder.typeView.setText(types[typeId]);
            //                int fuelNameIdx = cursor.getColumnIndex(ProviderDescriptor.LogView.Cols.FUEL_NAME);
            //                String fuelName = cursor.getString(fuelNameIdx);
            //                logHolder.typeView.setText(fuelName);
        }

        if (name == null || name.trim().equals("")) {
            logHolder.nameView.setText(logHolder.typeView.getText());
        }

        logHolder.id = id;
    }

    int pos = cursor.getPosition();
    CommonUtils.runAnimation(mlastPos, pos, view, UnitFacade.animSize);
    mlastPos = pos;
}

From source file:group.pals.android.lib.ui.filechooser.FragmentFiles.java

/**
 * Creates new {@link #mFileSelector} to select appropriate file after
 * loading a folder's content. It's either the parent path of last path, or
 * the file provided by key {@link FileChooserActivity#EXTRA_SELECT_FILE}.
 * Note that this also cancels previous selector if there is such one.
 *//* w  w  w  .  ja v  a 2  s .  co m*/
private void createFileSelector() {
    if (mFileSelector != null)
        mFileSelector.cancel(true);

    mFileSelector = new LoadingDialog<Void, Void, Integer>(getActivity(), true) {

        @Override
        protected Integer doInBackground(Void... params) {
            final Cursor cursor = mFileAdapter.getCursor();
            if (cursor == null || cursor.isClosed())
                return -1;

            final Uri selectedFile = (Uri) getArguments().getParcelable(FileChooserActivity.EXTRA_SELECT_FILE);
            final int colUri = cursor.getColumnIndex(BaseFile.COLUMN_URI);
            if (selectedFile != null)
                getArguments().remove(FileChooserActivity.EXTRA_SELECT_FILE);

            int shouldBeSelectedIdx = -1;
            final Uri uri = selectedFile != null ? selectedFile : getLastLocation();
            if (uri == null || !BaseFileProviderUtils.fileExists(getActivity(), uri))
                return -1;

            final String fileName = BaseFileProviderUtils.getFileName(getActivity(), uri);
            if (fileName == null)
                return -1;

            Uri parentUri = BaseFileProviderUtils.getParentFile(getActivity(), uri);
            if ((uri == getLastLocation() && !getCurrentLocation().equals(getLastLocation())
                    && BaseFileProviderUtils.isAncestorOf(getActivity(), getCurrentLocation(), uri))
                    || getCurrentLocation().equals(parentUri)) {
                if (cursor.moveToFirst()) {
                    while (!cursor.isLast()) {
                        if (isCancelled())
                            return -1;

                        Uri subUri = Uri.parse(cursor.getString(colUri));
                        if (uri == getLastLocation()) {
                            if (cursor.getInt(cursor
                                    .getColumnIndex(BaseFile.COLUMN_TYPE)) == BaseFile.FILE_TYPE_DIRECTORY) {
                                if (subUri.equals(uri)
                                        || BaseFileProviderUtils.isAncestorOf(getActivity(), subUri, uri)) {
                                    shouldBeSelectedIdx = Math.max(0, cursor.getPosition() - 2);
                                    break;
                                }
                            }
                        } else {
                            if (uri.equals(subUri)) {
                                shouldBeSelectedIdx = Math.max(0, cursor.getPosition() - 2);
                                break;
                            }
                        }

                        cursor.moveToNext();
                    } // while
                } // if
            } // if

            return shouldBeSelectedIdx;
        }// doInBackground()

        @Override
        protected void onPostExecute(final Integer result) {
            super.onPostExecute(result);

            if (isCancelled() || mFileAdapter.isEmpty())
                return;

            /*
             * Use a Runnable to make sure this works. Because if the list
             * view is handling data, this might not work.
             * 
             * Also sometimes it doesn't work without a delay.
             */
            mViewFiles.postDelayed(new Runnable() {

                @Override
                public void run() {
                    if (result >= 0 && result < mFileAdapter.getCount())
                        mViewFiles.setSelection(result);
                    else if (!mFileAdapter.isEmpty())
                        mViewFiles.setSelection(0);
                }// run()
            }, DisplayPrefs.DELAY_TIME_FOR_VERY_SHORT_ANIMATION);
        }// onPostExecute()

    };

    mFileSelector.execute();
}

From source file:com.haibison.android.anhuu.FragmentFiles.java

/**
 * Creates new {@link #mFileSelector} to select appropriate file after
 * loading a folder's content. It's either the parent path of last path, or
 * the file provided by key {@link FileChooserActivity#EXTRA_SELECT_FILE}.
 * Note that this also cancels previous selector if there is such one.
 *//*  w w w.ja  v  a2  s .c o  m*/
private void createFileSelector() {
    if (mFileSelector != null)
        mFileSelector.cancel(true);

    mFileSelector = new LoadingDialog<Void, Void, Integer>(getActivity(), true) {

        @Override
        protected Integer doInBackground(Void... params) {
            final Cursor cursor = mFileAdapter.getCursor();
            if (cursor == null || cursor.isClosed())
                return -1;

            final Uri selectedFile = (Uri) getArguments().getParcelable(FileChooserActivity.EXTRA_SELECT_FILE);
            final int colUri = cursor.getColumnIndex(BaseFile.COLUMN_URI);
            if (selectedFile != null)
                getArguments().remove(FileChooserActivity.EXTRA_SELECT_FILE);

            int shouldBeSelectedIdx = -1;
            final Uri uri = selectedFile != null ? selectedFile : getLastLocation();
            if (uri == null || !BaseFileProviderUtils.fileExists(getActivity(), uri))
                return -1;

            final String fileName = BaseFileProviderUtils.getFileName(getActivity(), uri);
            if (fileName == null)
                return -1;

            Uri parentUri = BaseFileProviderUtils.getParentFile(getActivity(), uri);
            if ((uri == getLastLocation() && !getCurrentLocation().equals(getLastLocation())
                    && BaseFileProviderUtils.isAncestorOf(getActivity(), getCurrentLocation(), uri))
                    || getCurrentLocation().equals(parentUri)) {
                if (cursor.moveToFirst()) {
                    while (!cursor.isLast()) {
                        if (isCancelled())
                            return -1;

                        Uri subUri = Uri.parse(cursor.getString(colUri));
                        if (uri == getLastLocation()) {
                            if (cursor.getInt(cursor
                                    .getColumnIndex(BaseFile.COLUMN_TYPE)) == BaseFile.FILE_TYPE_DIRECTORY) {
                                if (subUri.equals(uri)
                                        || BaseFileProviderUtils.isAncestorOf(getActivity(), subUri, uri)) {
                                    shouldBeSelectedIdx = Math.max(0, cursor.getPosition() - 2);
                                    break;
                                }
                            }
                        } else {
                            if (uri.equals(subUri)) {
                                shouldBeSelectedIdx = Math.max(0, cursor.getPosition() - 2);
                                break;
                            }
                        }

                        cursor.moveToNext();
                    } // while
                } // if
            } // if

            return shouldBeSelectedIdx;
        }// doInBackground()

        @Override
        protected void onPostExecute(final Integer result) {
            super.onPostExecute(result);

            if (isCancelled() || mFileAdapter.isEmpty())
                return;

            /*
             * Use a Runnable to make sure this works. Because if the list
             * view is handling data, this might not work.
             * 
             * Also sometimes it doesn't work without a delay.
             */
            mViewFiles.postDelayed(new Runnable() {

                @Override
                public void run() {
                    if (result >= 0 && result < mFileAdapter.getCount())
                        mViewFiles.setSelection(result);
                    else if (!mFileAdapter.isEmpty())
                        mViewFiles.setSelection(0);
                }// run()
            }, Display.DELAY_TIME_FOR_VERY_SHORT_ANIMATION);
        }// onPostExecute()

    };

    mFileSelector.execute();
}

From source file:com.amsterdam.marktbureau.makkelijkemarkt.DagvergunningFragmentOverzicht.java

/**
 * Populate the koopman fragment item details item when the loader has finished
 * @param loader the cursor loader/* w w  w.  j a va2 s .com*/
 * @param data data object containing one or more koopman rows with joined sollicitatie data
 */
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    if (data != null && data.moveToFirst()) {

        // get the markt id from the sharedprefs
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getContext());
        int marktId = settings.getInt(getContext().getString(R.string.sharedpreferences_key_markt_id), 0);

        // koopman photo
        Glide.with(getContext())
                .load(data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL)))
                .error(R.drawable.no_koopman_image).into(mKoopmanFotoImage);

        // koopman naam
        String naam = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " "
                + data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM));
        mKoopmanVoorlettersAchternaamText.setText(naam);

        // koopman erkenningsnummer
        String erkenningsnummer = data
                .getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER));
        mErkenningsnummerText.setText(erkenningsnummer);

        // koopman sollicitaties
        View view = getView();
        if (view != null) {
            LayoutInflater layoutInflater = (LayoutInflater) getActivity()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            LinearLayout placeholderLayout = (LinearLayout) view.findViewById(R.id.sollicitaties_placeholder);
            placeholderLayout.removeAllViews();

            // add multiple markt sollicitatie views to the koopman items
            while (!data.isAfterLast()) {

                // inflate sollicitatie layout and populate its view items
                View childLayout = layoutInflater.inflate(R.layout.dagvergunning_koopman_item_sollicitatie,
                        null);

                // highlight the sollicitatie for the current markt
                if (data.getCount() > 1 && marktId > 0 && marktId == data
                        .getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) {
                    childLayout.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.primary));
                }

                // markt afkorting
                String marktAfkorting = data
                        .getString(data.getColumnIndex(MakkelijkeMarktProvider.Markt.COL_AFKORTING));
                TextView marktAfkortingText = (TextView) childLayout
                        .findViewById(R.id.sollicitatie_markt_afkorting);
                marktAfkortingText.setText(marktAfkorting);

                // koopman sollicitatienummer
                String sollicitatienummer = data.getString(
                        data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_SOLLICITATIE_NUMMER));
                TextView sollicitatienummerText = (TextView) childLayout
                        .findViewById(R.id.sollicitatie_sollicitatie_nummer);
                sollicitatienummerText.setText(sollicitatienummer);

                // koopman sollicitatie status
                String sollicitatieStatus = data.getString(data.getColumnIndex("sollicitatie_status"));
                TextView sollicitatieStatusText = (TextView) childLayout.findViewById(R.id.sollicitatie_status);
                sollicitatieStatusText.setText(sollicitatieStatus);
                if (sollicitatieStatus != null && !sollicitatieStatus.equals("?")
                        && !sollicitatieStatus.equals("")) {
                    sollicitatieStatusText
                            .setTextColor(ContextCompat.getColor(getContext(), android.R.color.white));
                    sollicitatieStatusText.setBackgroundColor(ContextCompat.getColor(getContext(),
                            Utility.getSollicitatieStatusColor(getContext(), sollicitatieStatus)));
                }

                // add view and move cursor to next
                placeholderLayout.addView(childLayout, data.getPosition());
                data.moveToNext();
            }
        }
    }
}

From source file:com.amsterdam.marktbureau.makkelijkemarkt.DagvergunningFragmentKoopman.java

/**
 * Populate the koopman fragment item details item when the loader has finished
 * @param loader the cursor loader//from   w  ww. j  a  v a  2 s . c o m
 * @param data data object containing one or more koopman rows with joined sollicitatie data
 */
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    if (data != null && data.moveToFirst()) {
        boolean validSollicitatie = false;

        // get the markt id from the sharedprefs
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getContext());
        int marktId = settings.getInt(getContext().getString(R.string.sharedpreferences_key_markt_id), 0);

        // make the koopman details visible
        mKoopmanDetail.setVisibility(View.VISIBLE);

        // check koopman status
        String koopmanStatus = data.getString(data.getColumnIndex("koopman_status"));
        mMeldingVerwijderd = koopmanStatus.equals(getString(R.string.koopman_status_verwijderd));

        // koopman photo
        Glide.with(getContext())
                .load(data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL)))
                .error(R.drawable.no_koopman_image).into(mKoopmanFotoImage);

        // koopman naam
        String naam = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " "
                + data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM));
        mKoopmanVoorlettersAchternaamText.setText(naam);

        // koopman erkenningsnummer
        mErkenningsnummer = data
                .getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER));
        mErkenningsnummerText.setText(mErkenningsnummer);

        // koopman sollicitaties
        View view = getView();
        if (view != null) {
            LayoutInflater layoutInflater = (LayoutInflater) getActivity()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            LinearLayout placeholderLayout = (LinearLayout) view.findViewById(R.id.sollicitaties_placeholder);
            placeholderLayout.removeAllViews();

            // get vaste producten for selected markt, and add multiple markt sollicitatie views to the koopman items
            while (!data.isAfterLast()) {

                // get vaste producten for selected markt
                if (marktId > 0 && marktId == data
                        .getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) {
                    String[] productParams = getResources().getStringArray(R.array.array_product_param);
                    for (String product : productParams) {
                        mProducten.put(product, data.getInt(data.getColumnIndex(product)));
                    }
                }

                // inflate sollicitatie layout and populate its view items
                View childLayout = layoutInflater.inflate(R.layout.dagvergunning_koopman_item_sollicitatie,
                        null);

                // highlight the sollicitatie for the current markt
                if (data.getCount() > 1 && marktId > 0 && marktId == data
                        .getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) {
                    childLayout.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.primary));
                }

                // markt afkorting
                String marktAfkorting = data
                        .getString(data.getColumnIndex(MakkelijkeMarktProvider.Markt.COL_AFKORTING));
                TextView marktAfkortingText = (TextView) childLayout
                        .findViewById(R.id.sollicitatie_markt_afkorting);
                marktAfkortingText.setText(marktAfkorting);

                // koopman sollicitatienummer
                String sollicitatienummer = data.getString(
                        data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_SOLLICITATIE_NUMMER));
                TextView sollicitatienummerText = (TextView) childLayout
                        .findViewById(R.id.sollicitatie_sollicitatie_nummer);
                sollicitatienummerText.setText(sollicitatienummer);

                // koopman sollicitatie status
                String sollicitatieStatus = data.getString(data.getColumnIndex("sollicitatie_status"));
                TextView sollicitatieStatusText = (TextView) childLayout.findViewById(R.id.sollicitatie_status);
                sollicitatieStatusText.setText(sollicitatieStatus);
                if (sollicitatieStatus != null && !sollicitatieStatus.equals("?")
                        && !sollicitatieStatus.equals("")) {
                    sollicitatieStatusText
                            .setTextColor(ContextCompat.getColor(getContext(), android.R.color.white));
                    sollicitatieStatusText.setBackgroundColor(ContextCompat.getColor(getContext(),
                            Utility.getSollicitatieStatusColor(getContext(), sollicitatieStatus)));

                    // check if koopman has at least one valid sollicitatie on selected markt
                    if (marktId == data
                            .getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) {
                        validSollicitatie = true;
                    }
                }

                // add view and move cursor to next
                placeholderLayout.addView(childLayout, data.getPosition());
                data.moveToNext();
            }
        }

        // check valid sollicitatie
        mMeldingNoValidSollicitatie = !validSollicitatie;

        // get the date of today for the dag param
        SimpleDateFormat sdf = new SimpleDateFormat(getString(R.string.date_format_dag));
        String dag = sdf.format(new Date());

        // check multiple dagvergunningen
        Cursor dagvergunningen = getContext().getContentResolver().query(
                MakkelijkeMarktProvider.mUriDagvergunningJoined, null,
                "dagvergunning_doorgehaald != '1' AND " + MakkelijkeMarktProvider.mTableDagvergunning + "."
                        + MakkelijkeMarktProvider.Dagvergunning.COL_MARKT_ID + " = ? AND "
                        + MakkelijkeMarktProvider.Dagvergunning.COL_DAG + " = ? AND "
                        + MakkelijkeMarktProvider.Dagvergunning.COL_ERKENNINGSNUMMER_INVOER_WAARDE + " = ? ",
                new String[] { String.valueOf(marktId), dag, mErkenningsnummer, }, null);
        mMeldingMultipleDagvergunningen = (dagvergunningen != null && dagvergunningen.moveToFirst())
                && (dagvergunningen.getCount() > 1 || mDagvergunningId == -1);
        if (dagvergunningen != null) {
            dagvergunningen.close();
        }

        // callback to dagvergunning activity to updaten the meldingen view
        ((Callback) getActivity()).onMeldingenUpdated();
    }
}

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

private void synchronizeDontWantToSee(final boolean replace) {
    new Thread() {
        public void run() {
            if (!SettingConstants.UPDATING_FILTER) {
                SettingConstants.UPDATING_FILTER = true;

                Context applicationContext = getApplicationContext();

                NotificationCompat.Builder builder;

                builder = new NotificationCompat.Builder(TvBrowser.this);
                builder.setSmallIcon(R.drawable.ic_stat_notify);
                builder.setOngoing(true);
                builder.setContentTitle(getResources().getText(R.string.action_dont_want_to_see));
                builder.setContentText(getResources().getText(R.string.dont_want_to_see_notification_text));

                int notifyID = 2;

                NotificationManager notification = (NotificationManager) getSystemService(
                        Context.NOTIFICATION_SERVICE);
                notification.notify(notifyID, builder.build());

                updateProgressIcon(true);

                URL documentUrl;/*from  w  w  w  .  j  a v a  2  s. c  om*/

                try {
                    documentUrl = new URL(
                            "http://android.tvbrowser.org/data/scripts/syncDown.php?type=dontWantToSee");
                    URLConnection connection = documentUrl.openConnection();

                    SharedPreferences pref = getSharedPreferences("transportation", Context.MODE_PRIVATE);

                    String car = pref.getString(SettingConstants.USER_NAME, null);
                    String bicycle = pref.getString(SettingConstants.USER_PASSWORD, null);

                    if (car != null && bicycle != null) {
                        String userpass = car + ":" + bicycle;
                        String basicAuth = "basic "
                                + Base64.encodeToString(userpass.getBytes(), Base64.NO_WRAP);

                        connection.setRequestProperty("Authorization", basicAuth);

                        BufferedReader read = new BufferedReader(new InputStreamReader(
                                new GZIPInputStream(connection.getInputStream()), "UTF-8"));

                        String line = null;

                        StringBuilder exclusionBuilder = new StringBuilder();
                        HashSet<String> exclusions = new HashSet<String>();
                        ArrayList<DontWantToSeeExclusion> exclusionList = new ArrayList<DontWantToSeeExclusion>();

                        while ((line = read.readLine()) != null) {
                            if (line.contains(";;") && line.trim().length() > 0) {
                                exclusions.add(line);
                                exclusionList.add(new DontWantToSeeExclusion(line));
                                exclusionBuilder.append(line).append("\n");
                            }
                        }

                        String key = getString(R.string.I_DONT_WANT_TO_SEE_ENTRIES);
                        SharedPreferences pref1 = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this);

                        Set<String> oldValues = pref1.getStringSet(key, null);

                        if (exclusions.size() > 0) {
                            if (!replace && oldValues != null) {
                                for (String old : oldValues) {
                                    if (!exclusions.contains(old)) {
                                        exclusions.add(old);
                                        exclusionList.add(new DontWantToSeeExclusion(old));
                                        exclusionBuilder.append(old).append("\n");
                                    }
                                }
                            }

                            Editor edit = pref1.edit();

                            edit.putStringSet(key, exclusions);
                            edit.commit();

                            DontWantToSeeExclusion[] exclusionArr = exclusionList
                                    .toArray(new DontWantToSeeExclusion[exclusionList.size()]);

                            Cursor c = getContentResolver().query(TvBrowserContentProvider.CONTENT_URI_DATA,
                                    new String[] { TvBrowserContentProvider.KEY_ID,
                                            TvBrowserContentProvider.DATA_KEY_TITLE },
                                    null, null, TvBrowserContentProvider.KEY_ID);
                            c.moveToPosition(-1);

                            builder.setProgress(c.getCount(), 0, true);
                            notification.notify(notifyID, builder.build());

                            ArrayList<ContentProviderOperation> updateValuesList = new ArrayList<ContentProviderOperation>();

                            int keyColumn = c.getColumnIndex(TvBrowserContentProvider.KEY_ID);
                            int titleColumn = c.getColumnIndex(TvBrowserContentProvider.DATA_KEY_TITLE);

                            while (c.moveToNext()) {
                                builder.setProgress(c.getCount(), c.getPosition(), false);
                                notification.notify(notifyID, builder.build());

                                String title = c.getString(titleColumn);

                                boolean filter = UiUtils.filter(getApplicationContext(), title, exclusionArr);
                                long progID = c.getLong(keyColumn);

                                ContentValues values = new ContentValues();
                                values.put(TvBrowserContentProvider.DATA_KEY_DONT_WANT_TO_SEE, filter ? 1 : 0);

                                ContentProviderOperation.Builder opBuilder = ContentProviderOperation
                                        .newUpdate(ContentUris.withAppendedId(
                                                TvBrowserContentProvider.CONTENT_URI_DATA_UPDATE, progID));
                                opBuilder.withValues(values);

                                updateValuesList.add(opBuilder.build());
                            }

                            c.close();

                            if (!updateValuesList.isEmpty()) {
                                try {
                                    getContentResolver().applyBatch(TvBrowserContentProvider.AUTHORITY,
                                            updateValuesList);
                                    UiUtils.sendDontWantToSeeChangedBroadcast(applicationContext, true);
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(getApplicationContext(),
                                                    R.string.dont_want_to_see_sync_success, Toast.LENGTH_LONG)
                                                    .show();
                                        }
                                    });
                                } catch (RemoteException e) {
                                    e.printStackTrace();
                                } catch (OperationApplicationException e) {
                                    e.printStackTrace();
                                }
                            }

                            if (!replace && exclusionBuilder.length() > 0) {
                                startSynchronizeUp(false, exclusionBuilder.toString(),
                                        "http://android.tvbrowser.org/data/scripts/syncUp.php?type=dontWantToSee",
                                        null, null);
                            }
                        } else {
                            if (!replace && oldValues != null && !oldValues.isEmpty()) {
                                for (String old : oldValues) {
                                    exclusionBuilder.append(old).append("\n");
                                }

                                startSynchronizeUp(false, exclusionBuilder.toString(),
                                        "http://android.tvbrowser.org/data/scripts/syncUp.php?type=dontWantToSee",
                                        null, null);
                            }

                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getApplicationContext(), R.string.no_dont_want_to_see_sync,
                                            Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                    }
                } catch (Throwable t) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), R.string.no_dont_want_to_see_sync,
                                    Toast.LENGTH_LONG).show();
                        }
                    });
                }

                notification.cancel(notifyID);
                updateProgressIcon(false);

                SettingConstants.UPDATING_FILTER = false;
            }
        }
    }.start();
}

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

private void editDontWantToSee() {
    if (!SettingConstants.UPDATING_FILTER) {
        Set<String> currentExclusions = PrefUtils.getStringSetValue(R.string.I_DONT_WANT_TO_SEE_ENTRIES, null);

        final ArrayList<ExclusionEdit> mCurrentExclusionList = new ArrayList<TvBrowser.ExclusionEdit>();

        if (currentExclusions != null && !currentExclusions.isEmpty()) {
            for (String exclusion : currentExclusions) {
                mCurrentExclusionList.add(new ExclusionEdit(exclusion));
            }//from  w ww  .ja v a 2 s. c o m
        }

        Collections.sort(mCurrentExclusionList);

        final ArrayAdapter<ExclusionEdit> exclusionAdapter = new ArrayAdapter<TvBrowser.ExclusionEdit>(
                TvBrowser.this, android.R.layout.simple_list_item_1, mCurrentExclusionList);

        View view = getLayoutInflater().inflate(R.layout.dont_want_to_see_exclusion_edit_list,
                getParentViewGroup(), false);

        ListView list = (ListView) view.findViewById(R.id.dont_want_to_see_exclusion_list);

        list.setAdapter(exclusionAdapter);

        final Runnable cancel = new Runnable() {
            @Override
            public void run() {
            }
        };

        AdapterView.OnItemClickListener onClickListener = new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final ExclusionEdit edit = exclusionAdapter.getItem(position);

                View editView = getLayoutInflater().inflate(R.layout.dont_want_to_see_edit,
                        getParentViewGroup(), false);

                final TextView exclusion = (TextView) editView.findViewById(R.id.dont_want_to_see_value);
                final CheckBox caseSensitive = (CheckBox) editView
                        .findViewById(R.id.dont_want_to_see_case_sensitve);

                exclusion.setText(edit.mExclusion);
                caseSensitive.setSelected(edit.mIsCaseSensitive);

                Runnable editPositive = new Runnable() {
                    @Override
                    public void run() {
                        if (exclusion.getText().toString().trim().length() > 0) {
                            edit.mExclusion = exclusion.getText().toString();
                            edit.mIsCaseSensitive = caseSensitive.isSelected();

                            exclusionAdapter.notifyDataSetChanged();
                        }
                    }
                };

                showAlertDialog(getString(R.string.action_dont_want_to_see), null, editView, null, editPositive,
                        null, cancel, false, false);
            }
        };

        list.setOnItemClickListener(onClickListener);
        list.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
                getMenuInflater().inflate(R.menu.don_want_to_see_context, menu);

                MenuItem item = menu.findItem(R.id.dont_want_to_see_delete);

                item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        ExclusionEdit edit = exclusionAdapter
                                .getItem(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).position);
                        exclusionAdapter.remove(edit);
                        exclusionAdapter.notifyDataSetChanged();

                        return true;
                    }
                });
            }
        });

        Thread positive = new Thread() {
            @Override
            public void run() {
                SettingConstants.UPDATING_FILTER = true;

                final NotificationCompat.Builder builder = new NotificationCompat.Builder(TvBrowser.this);
                builder.setSmallIcon(R.drawable.ic_stat_notify);
                builder.setOngoing(true);
                builder.setContentTitle(getResources().getText(R.string.action_dont_want_to_see));
                builder.setContentText(
                        getResources().getText(R.string.dont_want_to_see_refresh_notification_text));

                final int notifyID = 2;

                final NotificationManager notification = (NotificationManager) getSystemService(
                        Context.NOTIFICATION_SERVICE);
                notification.notify(notifyID, builder.build());

                updateProgressIcon(true);

                HashSet<String> newExclusions = new HashSet<String>();
                final ArrayList<DontWantToSeeExclusion> exclusionList = new ArrayList<DontWantToSeeExclusion>();

                for (ExclusionEdit edit : mCurrentExclusionList) {
                    String exclusion = edit.getExclusion();

                    newExclusions.add(exclusion);
                    exclusionList.add(new DontWantToSeeExclusion(exclusion));
                }

                new Thread() {
                    public void run() {
                        Cursor programs = getContentResolver().query(TvBrowserContentProvider.CONTENT_URI_DATA,
                                new String[] { TvBrowserContentProvider.KEY_ID,
                                        TvBrowserContentProvider.DATA_KEY_TITLE },
                                null, null, TvBrowserContentProvider.KEY_ID);
                        programs.moveToPosition(-1);

                        builder.setProgress(programs.getCount(), 0, true);
                        notification.notify(notifyID, builder.build());

                        ArrayList<ContentProviderOperation> updateValuesList = new ArrayList<ContentProviderOperation>();

                        int keyColumn = programs.getColumnIndex(TvBrowserContentProvider.KEY_ID);
                        int titleColumn = programs.getColumnIndex(TvBrowserContentProvider.DATA_KEY_TITLE);

                        DontWantToSeeExclusion[] exclusionArr = exclusionList
                                .toArray(new DontWantToSeeExclusion[exclusionList.size()]);

                        while (programs.moveToNext()) {
                            builder.setProgress(programs.getCount(), programs.getPosition(), false);
                            notification.notify(notifyID, builder.build());

                            String title = programs.getString(titleColumn);

                            boolean filter = UiUtils.filter(getApplicationContext(), title, exclusionArr);
                            long progID = programs.getLong(keyColumn);

                            ContentValues values = new ContentValues();
                            values.put(TvBrowserContentProvider.DATA_KEY_DONT_WANT_TO_SEE, filter ? 1 : 0);

                            ContentProviderOperation.Builder opBuilder = ContentProviderOperation.newUpdate(
                                    ContentUris.withAppendedId(TvBrowserContentProvider.CONTENT_URI_DATA_UPDATE,
                                            progID));
                            opBuilder.withValues(values);

                            updateValuesList.add(opBuilder.build());
                        }

                        notification.cancel(notifyID);

                        programs.close();

                        if (!updateValuesList.isEmpty()) {
                            try {
                                getContentResolver().applyBatch(TvBrowserContentProvider.AUTHORITY,
                                        updateValuesList);
                                UiUtils.sendDontWantToSeeChangedBroadcast(getApplicationContext(), true);
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(getApplicationContext(),
                                                R.string.dont_want_to_see_sync_success, Toast.LENGTH_LONG)
                                                .show();
                                    }
                                });
                            } catch (RemoteException e) {
                                e.printStackTrace();
                            } catch (OperationApplicationException e) {
                                e.printStackTrace();
                            }
                        }

                        updateProgressIcon(false);
                        SettingConstants.UPDATING_FILTER = false;
                    }
                }.start();

                Editor edit = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit();
                edit.putStringSet(getString(R.string.I_DONT_WANT_TO_SEE_ENTRIES), newExclusions);
                edit.commit();
            }
        };

        showAlertDialog(getString(R.string.action_dont_want_to_see_edit), null, view, null, positive, null,
                cancel, false, true);
    }
}

From source file:com.piusvelte.sonet.core.SonetService.java

private void start(Intent intent) {
    if (intent != null) {
        String action = intent.getAction();
        Log.d(TAG, "action:" + action);
        if (ACTION_REFRESH.equals(action)) {
            if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS))
                putValidatedUpdates(intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS), 1);
            else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID))
                putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID) }, 1);
            else if (intent.getData() != null)
                putValidatedUpdates(new int[] { Integer.parseInt(intent.getData().getLastPathSegment()) }, 1);
            else/* ww  w.  j  a  v a  2  s  . c o m*/
                putValidatedUpdates(null, 0);
        } else if (LauncherIntent.Action.ACTION_READY.equals(action)) {
            if (intent.hasExtra(EXTRA_SCROLLABLE_VERSION)
                    && intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
                int scrollableVersion = intent.getIntExtra(EXTRA_SCROLLABLE_VERSION, 1);
                int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID);
                // check if the scrollable needs to be built
                Cursor widget = this.getContentResolver().query(Widgets.getContentUri(SonetService.this),
                        new String[] { Widgets._ID, Widgets.SCROLLABLE }, Widgets.WIDGET + "=?",
                        new String[] { Integer.toString(appWidgetId) }, null);
                if (widget.moveToFirst()) {
                    if (widget.getInt(widget.getColumnIndex(Widgets.SCROLLABLE)) < scrollableVersion) {
                        ContentValues values = new ContentValues();
                        values.put(Widgets.SCROLLABLE, scrollableVersion);
                        // set the scrollable version
                        this.getContentResolver().update(Widgets.getContentUri(SonetService.this), values,
                                Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) });
                        putValidatedUpdates(new int[] { appWidgetId }, 1);
                    } else
                        putValidatedUpdates(new int[] { appWidgetId }, 1);
                } else {
                    ContentValues values = new ContentValues();
                    values.put(Widgets.SCROLLABLE, scrollableVersion);
                    // set the scrollable version
                    this.getContentResolver().update(Widgets.getContentUri(SonetService.this), values,
                            Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) });
                    putValidatedUpdates(new int[] { appWidgetId }, 1);
                }
                widget.close();
            } else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
                // requery
                putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID) }, 0);
            }
        } else if (SMS_RECEIVED.equals(action)) {
            // parse the sms, and notify any widgets which have sms enabled
            Bundle bundle = intent.getExtras();
            Object[] pdus = (Object[]) bundle.get("pdus");
            for (int i = 0; i < pdus.length; i++) {
                SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[i]);
                AsyncTask<SmsMessage, String, int[]> smsLoader = new AsyncTask<SmsMessage, String, int[]>() {

                    @Override
                    protected int[] doInBackground(SmsMessage... msg) {
                        // check if SMS is enabled anywhere
                        Cursor widgets = getContentResolver().query(
                                Widget_accounts_view.getContentUri(SonetService.this),
                                new String[] { Widget_accounts_view._ID, Widget_accounts_view.WIDGET,
                                        Widget_accounts_view.ACCOUNT },
                                Widget_accounts_view.SERVICE + "=?", new String[] { Integer.toString(SMS) },
                                null);
                        int[] appWidgetIds = new int[widgets.getCount()];
                        if (widgets.moveToFirst()) {
                            // insert this message to the statuses db and requery scrollable/rebuild widget
                            // check if this is a contact
                            String phone = msg[0].getOriginatingAddress();
                            String friend = phone;
                            byte[] profile = null;
                            Uri content_uri = null;
                            // unknown numbers crash here in the emulator
                            Cursor phones = getContentResolver().query(
                                    Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
                                            Uri.encode(phone)),
                                    new String[] { ContactsContract.PhoneLookup._ID }, null, null, null);
                            if (phones.moveToFirst())
                                content_uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,
                                        phones.getLong(0));
                            else {
                                Cursor emails = getContentResolver().query(
                                        Uri.withAppendedPath(
                                                ContactsContract.CommonDataKinds.Email.CONTENT_FILTER_URI,
                                                Uri.encode(phone)),
                                        new String[] { ContactsContract.CommonDataKinds.Email._ID }, null, null,
                                        null);
                                if (emails.moveToFirst())
                                    content_uri = ContentUris.withAppendedId(
                                            ContactsContract.Contacts.CONTENT_URI, emails.getLong(0));
                                emails.close();
                            }
                            phones.close();
                            if (content_uri != null) {
                                // load contact
                                Cursor contacts = getContentResolver().query(content_uri,
                                        new String[] { ContactsContract.Contacts.DISPLAY_NAME }, null, null,
                                        null);
                                if (contacts.moveToFirst())
                                    friend = contacts.getString(0);
                                contacts.close();
                                profile = getBlob(ContactsContract.Contacts
                                        .openContactPhotoInputStream(getContentResolver(), content_uri));
                            }
                            long accountId = widgets.getLong(2);
                            long id;
                            ContentValues values = new ContentValues();
                            values.put(Entities.ESID, phone);
                            values.put(Entities.FRIEND, friend);
                            values.put(Entities.PROFILE, profile);
                            values.put(Entities.ACCOUNT, accountId);
                            Cursor entity = getContentResolver().query(
                                    Entities.getContentUri(SonetService.this), new String[] { Entities._ID },
                                    Entities.ACCOUNT + "=? and " + Entities.ESID + "=?",
                                    new String[] { Long.toString(accountId), mSonetCrypto.Encrypt(phone) },
                                    null);
                            if (entity.moveToFirst()) {
                                id = entity.getLong(0);
                                getContentResolver().update(Entities.getContentUri(SonetService.this), values,
                                        Entities._ID + "=?", new String[] { Long.toString(id) });
                            } else
                                id = Long.parseLong(getContentResolver()
                                        .insert(Entities.getContentUri(SonetService.this), values)
                                        .getLastPathSegment());
                            entity.close();
                            values.clear();
                            Long created = msg[0].getTimestampMillis();
                            values.put(Statuses.CREATED, created);
                            values.put(Statuses.ENTITY, id);
                            values.put(Statuses.MESSAGE, msg[0].getMessageBody());
                            values.put(Statuses.SERVICE, SMS);
                            while (!widgets.isAfterLast()) {
                                int widget = widgets.getInt(1);
                                appWidgetIds[widgets.getPosition()] = widget;
                                // get settings
                                boolean time24hr = true;
                                int status_bg_color = Sonet.default_message_bg_color;
                                int profile_bg_color = Sonet.default_message_bg_color;
                                int friend_bg_color = Sonet.default_friend_bg_color;
                                boolean icon = true;
                                int status_count = Sonet.default_statuses_per_account;
                                int notifications = 0;
                                Cursor c = getContentResolver().query(
                                        Widgets_settings.getContentUri(SonetService.this),
                                        new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR,
                                                Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND,
                                                Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR,
                                                Widgets.FRIEND_BG_COLOR },
                                        Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                        new String[] { Integer.toString(widget), Long.toString(accountId) },
                                        null);
                                if (!c.moveToFirst()) {
                                    c.close();
                                    c = getContentResolver().query(
                                            Widgets_settings.getContentUri(SonetService.this),
                                            new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR,
                                                    Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND,
                                                    Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR,
                                                    Widgets.FRIEND_BG_COLOR },
                                            Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                            new String[] { Integer.toString(widget),
                                                    Long.toString(Sonet.INVALID_ACCOUNT_ID) },
                                            null);
                                    if (!c.moveToFirst()) {
                                        c.close();
                                        c = getContentResolver().query(
                                                Widgets_settings.getContentUri(SonetService.this),
                                                new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR,
                                                        Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT,
                                                        Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS,
                                                        Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR },
                                                Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                                new String[] {
                                                        Integer.toString(AppWidgetManager.INVALID_APPWIDGET_ID),
                                                        Long.toString(Sonet.INVALID_ACCOUNT_ID) },
                                                null);
                                        if (!c.moveToFirst())
                                            initAccountSettings(SonetService.this,
                                                    AppWidgetManager.INVALID_APPWIDGET_ID,
                                                    Sonet.INVALID_ACCOUNT_ID);
                                        if (widget != AppWidgetManager.INVALID_APPWIDGET_ID)
                                            initAccountSettings(SonetService.this, widget,
                                                    Sonet.INVALID_ACCOUNT_ID);
                                    }
                                    initAccountSettings(SonetService.this, widget, accountId);
                                }
                                if (c.moveToFirst()) {
                                    time24hr = c.getInt(0) == 1;
                                    status_bg_color = c.getInt(1);
                                    icon = c.getInt(2) == 1;
                                    status_count = c.getInt(3);
                                    if (c.getInt(4) == 1)
                                        notifications |= Notification.DEFAULT_SOUND;
                                    if (c.getInt(5) == 1)
                                        notifications |= Notification.DEFAULT_VIBRATE;
                                    if (c.getInt(6) == 1)
                                        notifications |= Notification.DEFAULT_LIGHTS;
                                    profile_bg_color = c.getInt(7);
                                    friend_bg_color = c.getInt(8);
                                }
                                c.close();
                                values.put(Statuses.CREATEDTEXT, Sonet.getCreatedText(created, time24hr));
                                // update the bg and icon
                                // create the status_bg
                                values.put(Statuses.STATUS_BG, createBackground(status_bg_color));
                                // friend_bg
                                values.put(Statuses.FRIEND_BG, createBackground(friend_bg_color));
                                // profile_bg
                                values.put(Statuses.PROFILE_BG, createBackground(profile_bg_color));
                                values.put(Statuses.ICON,
                                        icon ? getBlob(getResources(), map_icons[SMS]) : null);
                                // insert the message
                                values.put(Statuses.WIDGET, widget);
                                values.put(Statuses.ACCOUNT, accountId);
                                getContentResolver().insert(Statuses.getContentUri(SonetService.this), values);
                                // check the status count, removing old sms
                                Cursor statuses = getContentResolver().query(
                                        Statuses.getContentUri(SonetService.this),
                                        new String[] { Statuses._ID },
                                        Statuses.WIDGET + "=? and " + Statuses.ACCOUNT + "=?",
                                        new String[] { Integer.toString(widget), Long.toString(accountId) },
                                        Statuses.CREATED + " desc");
                                if (statuses.moveToFirst()) {
                                    while (!statuses.isAfterLast()) {
                                        if (statuses.getPosition() >= status_count) {
                                            getContentResolver().delete(
                                                    Statuses.getContentUri(SonetService.this),
                                                    Statuses._ID + "=?", new String[] { Long.toString(statuses
                                                            .getLong(statuses.getColumnIndex(Statuses._ID))) });
                                        }
                                        statuses.moveToNext();
                                    }
                                }
                                statuses.close();
                                if (notifications != 0)
                                    publishProgress(Integer.toString(notifications),
                                            friend + " sent a message");
                                widgets.moveToNext();
                            }
                        }
                        widgets.close();
                        return appWidgetIds;
                    }

                    @Override
                    protected void onProgressUpdate(String... updates) {
                        int notifications = Integer.parseInt(updates[0]);
                        if (notifications != 0) {
                            Notification notification = new Notification(R.drawable.notification, updates[1],
                                    System.currentTimeMillis());
                            notification.setLatestEventInfo(getBaseContext(), "New messages", updates[1],
                                    PendingIntent.getActivity(SonetService.this, 0, (Sonet
                                            .getPackageIntent(SonetService.this, SonetNotifications.class)),
                                            0));
                            notification.defaults |= notifications;
                            ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
                                    .notify(NOTIFY_ID, notification);
                        }
                    }

                    @Override
                    protected void onPostExecute(int[] appWidgetIds) {
                        // remove self from thread list
                        if (!mSMSLoaders.isEmpty())
                            mSMSLoaders.remove(this);
                        putValidatedUpdates(appWidgetIds, 0);
                    }

                };
                mSMSLoaders.add(smsLoader);
                smsLoader.execute(msg);
            }
        } else if (ACTION_PAGE_DOWN.equals(action))
            (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()),
                    intent.getIntExtra(ACTION_PAGE_DOWN, 0));
        else if (ACTION_PAGE_UP.equals(action))
            (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()),
                    intent.getIntExtra(ACTION_PAGE_UP, 0));
        else {
            // this might be a widget update from the widget refresh button
            int appWidgetId;
            try {
                appWidgetId = Integer.parseInt(action);
                putValidatedUpdates(new int[] { appWidgetId }, 1);
            } catch (NumberFormatException e) {
                Log.d(TAG, "unknown action:" + action);
            }
        }
    }
}

From source file:com.shafiq.myfeedle.core.MyfeedleService.java

private void start(Intent intent) {
    if (intent != null) {
        String action = intent.getAction();
        Log.d(TAG, "action:" + action);
        if (ACTION_REFRESH.equals(action)) {
            if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS))
                putValidatedUpdates(intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS), 1);
            else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID))
                putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID) }, 1);
            else if (intent.getData() != null)
                putValidatedUpdates(new int[] { Integer.parseInt(intent.getData().getLastPathSegment()) }, 1);
            else//  w ww .  j  ava2  s  .  c om
                putValidatedUpdates(null, 0);
        } else if (LauncherIntent.Action.ACTION_READY.equals(action)) {
            if (intent.hasExtra(EXTRA_SCROLLABLE_VERSION)
                    && intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
                int scrollableVersion = intent.getIntExtra(EXTRA_SCROLLABLE_VERSION, 1);
                int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID);
                // check if the scrollable needs to be built
                Cursor widget = this.getContentResolver().query(Widgets.getContentUri(MyfeedleService.this),
                        new String[] { Widgets._ID, Widgets.SCROLLABLE }, Widgets.WIDGET + "=?",
                        new String[] { Integer.toString(appWidgetId) }, null);
                if (widget.moveToFirst()) {
                    if (widget.getInt(widget.getColumnIndex(Widgets.SCROLLABLE)) < scrollableVersion) {
                        ContentValues values = new ContentValues();
                        values.put(Widgets.SCROLLABLE, scrollableVersion);
                        // set the scrollable version
                        this.getContentResolver().update(Widgets.getContentUri(MyfeedleService.this), values,
                                Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) });
                        putValidatedUpdates(new int[] { appWidgetId }, 1);
                    } else
                        putValidatedUpdates(new int[] { appWidgetId }, 1);
                } else {
                    ContentValues values = new ContentValues();
                    values.put(Widgets.SCROLLABLE, scrollableVersion);
                    // set the scrollable version
                    this.getContentResolver().update(Widgets.getContentUri(MyfeedleService.this), values,
                            Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) });
                    putValidatedUpdates(new int[] { appWidgetId }, 1);
                }
                widget.close();
            } else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
                // requery
                putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID) }, 0);
            }
        } else if (SMS_RECEIVED.equals(action)) {
            // parse the sms, and notify any widgets which have sms enabled
            Bundle bundle = intent.getExtras();
            Object[] pdus = (Object[]) bundle.get("pdus");
            for (int i = 0; i < pdus.length; i++) {
                SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[i]);
                AsyncTask<SmsMessage, String, int[]> smsLoader = new AsyncTask<SmsMessage, String, int[]>() {

                    @Override
                    protected int[] doInBackground(SmsMessage... msg) {
                        // check if SMS is enabled anywhere
                        Cursor widgets = getContentResolver().query(
                                Widget_accounts_view.getContentUri(MyfeedleService.this),
                                new String[] { Widget_accounts_view._ID, Widget_accounts_view.WIDGET,
                                        Widget_accounts_view.ACCOUNT },
                                Widget_accounts_view.SERVICE + "=?", new String[] { Integer.toString(SMS) },
                                null);
                        int[] appWidgetIds = new int[widgets.getCount()];
                        if (widgets.moveToFirst()) {
                            // insert this message to the statuses db and requery scrollable/rebuild widget
                            // check if this is a contact
                            String phone = msg[0].getOriginatingAddress();
                            String friend = phone;
                            byte[] profile = null;
                            Uri content_uri = null;
                            // unknown numbers crash here in the emulator
                            Cursor phones = getContentResolver().query(
                                    Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
                                            Uri.encode(phone)),
                                    new String[] { ContactsContract.PhoneLookup._ID }, null, null, null);
                            if (phones.moveToFirst())
                                content_uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,
                                        phones.getLong(0));
                            else {
                                Cursor emails = getContentResolver().query(
                                        Uri.withAppendedPath(
                                                ContactsContract.CommonDataKinds.Email.CONTENT_FILTER_URI,
                                                Uri.encode(phone)),
                                        new String[] { ContactsContract.CommonDataKinds.Email._ID }, null, null,
                                        null);
                                if (emails.moveToFirst())
                                    content_uri = ContentUris.withAppendedId(
                                            ContactsContract.Contacts.CONTENT_URI, emails.getLong(0));
                                emails.close();
                            }
                            phones.close();
                            if (content_uri != null) {
                                // load contact
                                Cursor contacts = getContentResolver().query(content_uri,
                                        new String[] { ContactsContract.Contacts.DISPLAY_NAME }, null, null,
                                        null);
                                if (contacts.moveToFirst())
                                    friend = contacts.getString(0);
                                contacts.close();
                                profile = getBlob(ContactsContract.Contacts
                                        .openContactPhotoInputStream(getContentResolver(), content_uri));
                            }
                            long accountId = widgets.getLong(2);
                            long id;
                            ContentValues values = new ContentValues();
                            values.put(Entities.ESID, phone);
                            values.put(Entities.FRIEND, friend);
                            values.put(Entities.PROFILE, profile);
                            values.put(Entities.ACCOUNT, accountId);
                            Cursor entity = getContentResolver().query(
                                    Entities.getContentUri(MyfeedleService.this), new String[] { Entities._ID },
                                    Entities.ACCOUNT + "=? and " + Entities.ESID + "=?",
                                    new String[] { Long.toString(accountId), mMyfeedleCrypto.Encrypt(phone) },
                                    null);
                            if (entity.moveToFirst()) {
                                id = entity.getLong(0);
                                getContentResolver().update(Entities.getContentUri(MyfeedleService.this),
                                        values, Entities._ID + "=?", new String[] { Long.toString(id) });
                            } else
                                id = Long.parseLong(getContentResolver()
                                        .insert(Entities.getContentUri(MyfeedleService.this), values)
                                        .getLastPathSegment());
                            entity.close();
                            values.clear();
                            Long created = msg[0].getTimestampMillis();
                            values.put(Statuses.CREATED, created);
                            values.put(Statuses.ENTITY, id);
                            values.put(Statuses.MESSAGE, msg[0].getMessageBody());
                            values.put(Statuses.SERVICE, SMS);
                            while (!widgets.isAfterLast()) {
                                int widget = widgets.getInt(1);
                                appWidgetIds[widgets.getPosition()] = widget;
                                // get settings
                                boolean time24hr = true;
                                int status_bg_color = Myfeedle.default_message_bg_color;
                                int profile_bg_color = Myfeedle.default_message_bg_color;
                                int friend_bg_color = Myfeedle.default_friend_bg_color;
                                boolean icon = true;
                                int status_count = Myfeedle.default_statuses_per_account;
                                int notifications = 0;
                                Cursor c = getContentResolver().query(
                                        Widgets_settings.getContentUri(MyfeedleService.this),
                                        new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR,
                                                Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND,
                                                Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR,
                                                Widgets.FRIEND_BG_COLOR },
                                        Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                        new String[] { Integer.toString(widget), Long.toString(accountId) },
                                        null);
                                if (!c.moveToFirst()) {
                                    c.close();
                                    c = getContentResolver().query(
                                            Widgets_settings.getContentUri(MyfeedleService.this),
                                            new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR,
                                                    Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND,
                                                    Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR,
                                                    Widgets.FRIEND_BG_COLOR },
                                            Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                            new String[] { Integer.toString(widget),
                                                    Long.toString(Myfeedle.INVALID_ACCOUNT_ID) },
                                            null);
                                    if (!c.moveToFirst()) {
                                        c.close();
                                        c = getContentResolver().query(
                                                Widgets_settings.getContentUri(MyfeedleService.this),
                                                new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR,
                                                        Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT,
                                                        Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS,
                                                        Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR },
                                                Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                                new String[] {
                                                        Integer.toString(AppWidgetManager.INVALID_APPWIDGET_ID),
                                                        Long.toString(Myfeedle.INVALID_ACCOUNT_ID) },
                                                null);
                                        if (!c.moveToFirst())
                                            initAccountSettings(MyfeedleService.this,
                                                    AppWidgetManager.INVALID_APPWIDGET_ID,
                                                    Myfeedle.INVALID_ACCOUNT_ID);
                                        if (widget != AppWidgetManager.INVALID_APPWIDGET_ID)
                                            initAccountSettings(MyfeedleService.this, widget,
                                                    Myfeedle.INVALID_ACCOUNT_ID);
                                    }
                                    initAccountSettings(MyfeedleService.this, widget, accountId);
                                }
                                if (c.moveToFirst()) {
                                    time24hr = c.getInt(0) == 1;
                                    status_bg_color = c.getInt(1);
                                    icon = c.getInt(2) == 1;
                                    status_count = c.getInt(3);
                                    if (c.getInt(4) == 1)
                                        notifications |= Notification.DEFAULT_SOUND;
                                    if (c.getInt(5) == 1)
                                        notifications |= Notification.DEFAULT_VIBRATE;
                                    if (c.getInt(6) == 1)
                                        notifications |= Notification.DEFAULT_LIGHTS;
                                    profile_bg_color = c.getInt(7);
                                    friend_bg_color = c.getInt(8);
                                }
                                c.close();
                                values.put(Statuses.CREATEDTEXT, Myfeedle.getCreatedText(created, time24hr));
                                // update the bg and icon
                                // create the status_bg
                                values.put(Statuses.STATUS_BG, createBackground(status_bg_color));
                                // friend_bg
                                values.put(Statuses.FRIEND_BG, createBackground(friend_bg_color));
                                // profile_bg
                                values.put(Statuses.PROFILE_BG, createBackground(profile_bg_color));
                                values.put(Statuses.ICON,
                                        icon ? getBlob(getResources(), map_icons[SMS]) : null);
                                // insert the message
                                values.put(Statuses.WIDGET, widget);
                                values.put(Statuses.ACCOUNT, accountId);
                                getContentResolver().insert(Statuses.getContentUri(MyfeedleService.this),
                                        values);
                                // check the status count, removing old sms
                                Cursor statuses = getContentResolver().query(
                                        Statuses.getContentUri(MyfeedleService.this),
                                        new String[] { Statuses._ID },
                                        Statuses.WIDGET + "=? and " + Statuses.ACCOUNT + "=?",
                                        new String[] { Integer.toString(widget), Long.toString(accountId) },
                                        Statuses.CREATED + " desc");
                                if (statuses.moveToFirst()) {
                                    while (!statuses.isAfterLast()) {
                                        if (statuses.getPosition() >= status_count) {
                                            getContentResolver().delete(
                                                    Statuses.getContentUri(MyfeedleService.this),
                                                    Statuses._ID + "=?", new String[] { Long.toString(statuses
                                                            .getLong(statuses.getColumnIndex(Statuses._ID))) });
                                        }
                                        statuses.moveToNext();
                                    }
                                }
                                statuses.close();
                                if (notifications != 0)
                                    publishProgress(Integer.toString(notifications),
                                            friend + " sent a message");
                                widgets.moveToNext();
                            }
                        }
                        widgets.close();
                        return appWidgetIds;
                    }

                    @Override
                    protected void onProgressUpdate(String... updates) {
                        int notifications = Integer.parseInt(updates[0]);
                        if (notifications != 0) {
                            Notification notification = new Notification(R.drawable.notification, updates[1],
                                    System.currentTimeMillis());
                            notification.setLatestEventInfo(getBaseContext(), "New messages", updates[1],
                                    PendingIntent.getActivity(MyfeedleService.this, 0,
                                            (Myfeedle.getPackageIntent(MyfeedleService.this,
                                                    MyfeedleNotifications.class)),
                                            0));
                            notification.defaults |= notifications;
                            ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
                                    .notify(NOTIFY_ID, notification);
                        }
                    }

                    @Override
                    protected void onPostExecute(int[] appWidgetIds) {
                        // remove self from thread list
                        if (!mSMSLoaders.isEmpty())
                            mSMSLoaders.remove(this);
                        putValidatedUpdates(appWidgetIds, 0);
                    }

                };
                mSMSLoaders.add(smsLoader);
                smsLoader.execute(msg);
            }
        } else if (ACTION_PAGE_DOWN.equals(action))
            (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()),
                    intent.getIntExtra(ACTION_PAGE_DOWN, 0));
        else if (ACTION_PAGE_UP.equals(action))
            (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()),
                    intent.getIntExtra(ACTION_PAGE_UP, 0));
        else {
            // this might be a widget update from the widget refresh button
            int appWidgetId;
            try {
                appWidgetId = Integer.parseInt(action);
                putValidatedUpdates(new int[] { appWidgetId }, 1);
            } catch (NumberFormatException e) {
                Log.d(TAG, "unknown action:" + action);
            }
        }
    }
}