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:de.elanev.studip.android.app.frontend.messages.MessagesListFragment.java

public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    if (getActivity() == null) {
        return;//  w w w .  j a v a  2 s. c  om
    }

    cursor.moveToFirst();
    if (cursor.getCount() > 0) {
        List<SectionedCursorAdapter.Section> sections = new ArrayList<SectionedCursorAdapter.Section>();
        if (!cursor.isAfterLast())
            getActivity().setTitle(cursor.getString(
                    cursor.getColumnIndex(MessagesContract.Columns.MessageFolders.MESSAGE_FOLDER_NAME)));

        long previousDay = -1;
        long currentDay = -1;
        while (!cursor.isAfterLast()) {
            currentDay = cursor
                    .getLong(cursor.getColumnIndex(MessagesContract.Columns.Messages.MESSAGE_MKDATE));
            if (!DateTools.isSameDay(previousDay * 1000L, currentDay * 1000L)) {
                sections.add(new SectionedCursorAdapter.Section(cursor.getPosition(),
                        TextTools.getLocalizedTime(currentDay * 1000L, mContext)));
            }

            previousDay = currentDay;

            cursor.moveToNext();
        }

        mMessagesAdapter.setSections(sections);
    }

    mMessagesAdapter.swapCursor(cursor);

    setLoadingViewVisible(false);
}

From source file:com.google.samples.apps.iosched.ui.SessionLivestreamActivity.java

/**
 * Locates which item should be selected in the action bar drop-down spinner based on the
 * current active session uri//from   w ww .  j a  v  a  2 s.  c  o  m
 * @param data The data
 * @return The row num of the item that should be selected or 0 if not found
 */
private int locateSelectedItem(Cursor data) {
    int selected = 0;
    if (data != null && mSessionId != null) {
        while (data.moveToNext()) {
            if (mSessionId.equals(data.getString(SessionsQuery.SESSION_ID))) {
                selected = data.getPosition();
                mCaptionsUrl = null;
            }
        }
    }
    return selected;
}

From source file:fr.eoit.activity.fragment.blueprint.RequiredDecryptorFragment.java

@Override
public void onLoadFinished(Cursor cursor) {
    if (DbUtil.hasAtLeastOneRow(cursor)) {
        String[] from = new String[] { Item.COLUMN_NAME_NAME, "decryptorDesc" };
        int[] to = new int[] { android.R.id.text1, android.R.id.text2 };

        MatrixCursor decryptorCursor = new MatrixCursor(
                new String[] { Item._ID, Item.COLUMN_NAME_NAME, "decryptorDesc" });
        DbUtil.addRowToMatrixCursor(decryptorCursor, 0L, "None", "");

        cursor.moveToFirst();/*from   www .j a va 2  s . co  m*/
        int selectedItem = 0;
        while (!cursor.isAfterLast()) {
            long itemId = cursor.getLong(cursor.getColumnIndexOrThrow(Item._ID));
            DbUtil.addRowToMatrixCursor(decryptorCursor, itemId,
                    cursor.getString(cursor.getColumnIndexOrThrow(Item.COLUMN_NAME_NAME)),
                    getDecryptorDescription(DecryptorUtil.getDecryptorBonuses(itemId),
                            getActivity().getResources()));

            if (itemId == decryptorId) {
                selectedItem = cursor.getPosition() + 1;
            }

            cursor.moveToNext();
        }

        SimpleCursorAdapter adapter = new SimpleCursorAdapter(getActivity(),
                android.R.layout.simple_spinner_item, decryptorCursor, from, to,
                SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        Spinner spinner = (Spinner) getActivity().findViewById(R.id.DECRYPTOR_SPINNER);
        adapter.setDropDownViewResource(R.layout.decryptor_drop_down_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new SpinnerDecryptorOnItemSelectedListener());
        spinner.setSelection(selectedItem);
    }
}

From source file:com.granita.tasks.EditTaskFragment.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    mTaskListAdapter.changeCursor(cursor);
    if (cursor != null) {
        // set the list that was used the last time the user created an event
        if (mSelectedList != -1) {
            // iterate over all lists and select the one that matches the given id
            cursor.moveToFirst();//from   w w w  .ja  va2 s  .  c  o m
            while (!cursor.isAfterLast()) {
                Long listId = cursor.getLong(TASK_LIST_PROJECTION_VALUES.id);
                if (listId != null && listId == mSelectedList) {
                    mListSpinner.setSelection(cursor.getPosition());
                    break;
                }
                cursor.moveToNext();
            }
        }
    }
}

From source file:com.tct.email.provider.EmailMessageCursor.java

public EmailMessageCursor(final Context c, final Cursor cursor, final String htmlColumn,
        final String textColumn) {
    super(cursor);
    mHtmlColumnIndex = cursor.getColumnIndex(htmlColumn);
    mTextColumnIndex = cursor.getColumnIndex(textColumn);
    final int cursorSize = cursor.getCount();
    mHtmlParts = new SparseArray<String>(cursorSize);
    mTextParts = new SparseArray<String>(cursorSize);
    //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_S
    mHtmlLinkifyColumnIndex = cursor.getColumnIndex(UIProvider.MessageColumns.BODY_HTML_LINKIFY);
    mHtmlLinkifyParts = new SparseArray<String>(cursorSize);
    mTextLinkifyColumnIndex = cursor.getColumnIndex(UIProvider.MessageColumns.BODY_TEXT_LINKIFY);
    mTextLinkifyParts = new SparseArray<String>(cursorSize);
    //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_E

    final ContentResolver cr = c.getContentResolver();

    while (cursor.moveToNext()) {
        final int position = cursor.getPosition();
        final long messageId = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID));
        // TS: chao.zhang 2015-09-14 EMAIL BUGFIX-1039046  MOD_S
        InputStream htmlIn = null;
        InputStream textIn = null;
        try {//from w ww. j  a  va2  s. c  om
            if (mHtmlColumnIndex != -1) {
                final Uri htmlUri = Body.getBodyHtmlUriForMessageWithId(messageId);
                //WARNING: Actually openInput will used 2 PIPE(FD) to connect,but if some exception happen during connect,
                //such as fileNotFoundException,maybe the connection will not be closed. just a try!!!
                htmlIn = cr.openInputStream(htmlUri);
                final String underlyingHtmlString;
                try {
                    underlyingHtmlString = IOUtils.toString(htmlIn);
                } finally {
                    htmlIn.close();
                    htmlIn = null;
                }
                //TS: zhaotianyong 2015-04-05 EMAIL BUGFIX_964325 MOD_S
                final String sanitizedHtml = HtmlSanitizer.sanitizeHtml(underlyingHtmlString);
                mHtmlParts.put(position, sanitizedHtml);
                //TS: zhaotianyong 2015-04-05 EMAIL BUGFIX_964325 MOD_E
                //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_S
                //NOTE: add links for sanitized html
                if (!TextUtils.isEmpty(sanitizedHtml)) {
                    final String linkifyHtml = com.tct.mail.utils.Linkify.addLinks(sanitizedHtml);
                    mHtmlLinkifyParts.put(position, linkifyHtml);
                } else {
                    mHtmlLinkifyParts.put(position, "");
                }
                //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_E
            }
        } catch (final IOException e) {
            LogUtils.v(LogUtils.TAG, e, "Did not find html body for message %d", messageId);
        } catch (final OutOfMemoryError oom) {
            LogUtils.v(LogUtils.TAG, oom,
                    "Terrible,OOM happen durning query EmailMessageCursor in bodyHtml,current message %d",
                    messageId);
            mHtmlLinkifyParts.put(position, "");
        }
        try {
            if (mTextColumnIndex != -1) {
                final Uri textUri = Body.getBodyTextUriForMessageWithId(messageId);
                textIn = cr.openInputStream(textUri);
                final String underlyingTextString;
                try {
                    underlyingTextString = IOUtils.toString(textIn);
                } finally {
                    textIn.close();
                    textIn = null;
                }
                mTextParts.put(position, underlyingTextString);
                //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_S
                //NOTE: add links for underlying text string
                if (!TextUtils.isEmpty(underlyingTextString)) {
                    final SpannableString spannable = new SpannableString(underlyingTextString);
                    Linkify.addLinks(spannable,
                            Linkify.EMAIL_ADDRESSES | Linkify.WEB_URLS | Linkify.PHONE_NUMBERS);
                    final String linkifyText = Html.toHtml(spannable);
                    mTextLinkifyParts.put(position, linkifyText);
                } else {
                    mTextLinkifyParts.put(position, "");
                }
                //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_E
            }
        } catch (final IOException e) {
            LogUtils.v(LogUtils.TAG, e, "Did not find text body for message %d", messageId);
        } catch (final OutOfMemoryError oom) {
            LogUtils.v(LogUtils.TAG, oom,
                    "Terrible,OOM happen durning query EmailMessageCursor in bodyText,current message %d",
                    messageId);
            mTextLinkifyParts.put(position, "");
        }
        //NOTE:Remember that this just a protective code,for better release Not used Resources.
        if (htmlIn != null) {
            try {
                htmlIn.close();
            } catch (IOException e1) {
                LogUtils.v(LogUtils.TAG, e1, "IOException happen while close the htmlInput connection ");
            }
        }
        if (textIn != null) {
            try {
                textIn.close();
            } catch (IOException e2) {
                LogUtils.v(LogUtils.TAG, e2, "IOException happen while close the textInput connection ");
            }
        } // TS: chao.zhang 2015-09-14 EMAIL BUGFIX-1039046  MOD_E
    }
    cursor.moveToPosition(-1);
}

From source file:ac.robinson.mediaphone.provider.NarrativeAdapter.java

public void bindView(View view, Context context, Cursor cursor) {
    NarrativeViewHolder holder = (NarrativeViewHolder) view.getTag();

    // only load column indices once
    if (mInternalIdIndex < 0) {
        mInternalIdIndex = cursor.getColumnIndexOrThrow(NarrativeItem.INTERNAL_ID);
        mCreationDateIndex = cursor.getColumnIndexOrThrow(NarrativeItem.DATE_CREATED);
        mSequenceIdIndex = cursor.getColumnIndexOrThrow(NarrativeItem.SEQUENCE_ID);
    }//w w  w .ja  v a2  s .  co m

    holder.narrativeInternalId = cursor.getString(mInternalIdIndex);
    holder.narrativeDateCreated = cursor.getLong(mCreationDateIndex);
    holder.narrativeSequenceId = cursor.getInt(mSequenceIdIndex);

    final BrowserActivity activity = mActivity;
    if (activity.getScrollState() == AbsListView.OnScrollListener.SCROLL_STATE_FLING
            || activity.isPendingIconsUpdate()) {
        holder.queryIcons = true;
        holder.frameList.setAdapter(mEmptyAdapter);
    } else {
        attachAdapter(holder);
        holder.queryIcons = false;
    }

    // alternating row colours
    int cursorPosition = cursor.getPosition();
    if ((cursor.getCount() - cursorPosition) % 2 == 0) { // so the colour stays the same when adding a new narrative
        holder.frameList.setBackgroundResource(
                mIsTemplateView ? R.color.template_list_dark : R.color.narrative_list_dark);
    } else {
        holder.frameList.setBackgroundResource(
                mIsTemplateView ? R.color.template_list_light : R.color.narrative_list_light);
    }
}

From source file:com.mpower.daktar.android.tasks.InstanceUploaderTask.java

@Override
protected HashMap<String, String> doInBackground(final Long... values) {
    mResults = new HashMap<String, String>();

    String postResponse;/* w w w  .j av  a2s . co  m*/
    String selection = BaseColumns._ID + "=?";
    final String[] selectionArgs = new String[values.length];
    for (int i = 0; i < values.length; i++) {
        if (i != values.length - 1) {
            selection += " or " + BaseColumns._ID + "=?";
        }
        selectionArgs[i] = values[i].toString();
    }

    // get shared HttpContext so that authentication and cookies are
    // retained.
    final HttpContext localContext = MIntel.getInstance().getHttpContext();
    final HttpClient httpclient = WebUtils.createHttpClient(CONNECTION_TIMEOUT);

    final Map<URI, URI> uriRemap = new HashMap<URI, URI>();

    final Cursor c = MIntel.getInstance().getContentResolver().query(InstanceColumns.CONTENT_URI, null,
            selection, selectionArgs, null);

    if (c.getCount() > 0) {
        c.moveToPosition(-1);
        next_submission: while (c.moveToNext()) {
            if (isCancelled())
                return mResults;
            publishProgress(c.getPosition() + 1, c.getCount());
            final String instance = c.getString(c.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
            final String id = c.getString(c.getColumnIndex(BaseColumns._ID));
            final Uri toUpdate = Uri.withAppendedPath(InstanceColumns.CONTENT_URI, id);

            String urlString = c.getString(c.getColumnIndex(InstanceColumns.SUBMISSION_URI));
            if (urlString == null) {
                final SharedPreferences settings = PreferenceManager
                        .getDefaultSharedPreferences(MIntel.getInstance());
                urlString = settings.getString(PreferencesActivity.KEY_SERVER_URL, null);
                urlString = urlString + WebUtils.URL_PART_SUBMISSION;
            }

            final ContentValues cv = new ContentValues();
            URI u = null;
            try {
                final URL url = new URL(URLDecoder.decode(urlString, "utf-8"));
                u = url.toURI();
            } catch (final MalformedURLException e) {
                e.printStackTrace();
                mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage());
                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                continue;
            } catch (final URISyntaxException e) {
                e.printStackTrace();
                mResults.put(id, fail + "invalid uri: " + urlString + " :: details: " + e.getMessage());
                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                continue;
            } catch (final UnsupportedEncodingException e) {
                e.printStackTrace();
                mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage());
                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                continue;
            }

            boolean openRosaServer = false;
            if (uriRemap.containsKey(u)) {
                // we already issued a head request and got a response,
                // so we know the proper URL to send the submission to
                // and the proper scheme. We also know that it was an
                // OpenRosa compliant server.
                openRosaServer = true;
                u = uriRemap.get(u);
            } else {
                // we need to issue a head request
                final HttpHead httpHead = WebUtils.createOpenRosaHttpHead(u);

                // prepare response
                HttpResponse response = null;
                try {
                    response = httpclient.execute(httpHead, localContext);
                    final int statusCode = response.getStatusLine().getStatusCode();
                    if (statusCode == 401) {
                        // we need authentication, so stop and return what
                        // we've
                        // done so far.
                        mAuthRequestingServer = u;
                        return null;
                    } else if (statusCode == 204) {
                        final Header[] locations = response.getHeaders("Location");
                        if (locations != null && locations.length == 1) {
                            try {
                                final URL url = new URL(URLDecoder.decode(locations[0].getValue(), "utf-8"));
                                final URI uNew = url.toURI();
                                if (u.getHost().equalsIgnoreCase(uNew.getHost())) {
                                    openRosaServer = true;
                                    // trust the server to tell us a new
                                    // location
                                    // ... and possibly to use https
                                    // instead.
                                    uriRemap.put(u, uNew);
                                    u = uNew;
                                } else {
                                    // Don't follow a redirection attempt to
                                    // a different host.
                                    // We can't tell if this is a spoof or
                                    // not.
                                    mResults.put(id,
                                            fail + "Unexpected redirection attempt to a different host: "
                                                    + uNew.toString());
                                    cv.put(InstanceColumns.STATUS,
                                            InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                                    continue;
                                }
                            } catch (final Exception e) {
                                e.printStackTrace();
                                mResults.put(id, fail + urlString + " " + e.getMessage());
                                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                                MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                                continue;
                            }
                        }
                    } else {
                        // may be a server that does not handle
                        try {
                            // have to read the stream in order to reuse the
                            // connection
                            final InputStream is = response.getEntity().getContent();
                            // read to end of stream...
                            final long count = 1024L;
                            while (is.skip(count) == count) {
                                ;
                            }
                            is.close();
                        } catch (final IOException e) {
                            e.printStackTrace();
                        } catch (final Exception e) {
                            e.printStackTrace();
                        }

                        Log.w(t, "Status code on Head request: " + statusCode);
                        if (statusCode >= 200 && statusCode <= 299) {
                            mResults.put(id, fail
                                    + "Invalid status code on Head request.  If you have a web proxy, you may need to login to your network. ");
                            cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                            MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                            continue;
                        }
                    }
                } catch (final ClientProtocolException e) {
                    e.printStackTrace();
                    Log.e(t, e.getMessage());
                    mResults.put(id, fail + "Client Protocol Exception");
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    continue;
                } catch (final ConnectTimeoutException e) {
                    e.printStackTrace();
                    Log.e(t, e.getMessage());
                    mResults.put(id, fail + "Connection Timeout");
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    continue;
                } catch (final UnknownHostException e) {
                    e.printStackTrace();
                    mResults.put(id, fail + e.getMessage() + " :: Network Connection Failed");
                    Log.e(t, e.getMessage());
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    continue;
                } catch (final Exception e) {
                    e.printStackTrace();
                    mResults.put(id, fail + "Generic Exception");
                    Log.e(t, e.getMessage());
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    continue;
                }
            }

            // At this point, we may have updated the uri to use https.
            // This occurs only if the Location header keeps the host name
            // the same. If it specifies a different host name, we error
            // out.
            //
            // And we may have set authentication cookies in our
            // cookiestore (referenced by localContext) that will enable
            // authenticated publication to the server.
            //
            // get instance file
            final File instanceFile = new File(instance);

            if (!instanceFile.exists()) {
                mResults.put(id, fail + "instance XML file does not exist!");
                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                continue;
            }

            // find all files in parent directory
            final File[] allFiles = instanceFile.getParentFile().listFiles();

            // add media files
            final List<File> files = new ArrayList<File>();
            for (final File f : allFiles) {
                final String fileName = f.getName();

                final int dotIndex = fileName.lastIndexOf(".");
                String extension = "";
                if (dotIndex != -1) {
                    extension = fileName.substring(dotIndex + 1);
                }

                if (fileName.startsWith(".")) {
                    // ignore invisible files
                    continue;
                }
                if (fileName.equals(instanceFile.getName())) {
                    continue; // the xml file has already been added
                } else if (openRosaServer) {
                    files.add(f);
                } else if (extension.equals("jpg")) { // legacy 0.9x
                    files.add(f);
                } else if (extension.equals("3gpp")) { // legacy 0.9x
                    files.add(f);
                } else if (extension.equals("3gp")) { // legacy 0.9x
                    files.add(f);
                } else if (extension.equals("mp4")) { // legacy 0.9x
                    files.add(f);
                } else if (extension.equals("amr")) { // legacy 0.9x
                    files.add(f);
                } else {
                    Log.w(t, "unrecognized file type " + f.getName());
                }
            }

            postResponse = "";
            boolean first = true;
            int j = 0;
            while (j < files.size() || first) {
                first = false;

                final HttpPost httppost = WebUtils.createOpenRosaHttpPost(u, mAuth);

                final MimeTypeMap m = MimeTypeMap.getSingleton();

                long byteCount = 0L;

                // mime post
                final MultipartEntity entity = new MultipartEntity();

                // add the submission file first...
                FileBody fb = new FileBody(instanceFile, "text/xml");
                entity.addPart("xml_submission_file", fb);
                Log.i(t, "added xml_submission_file: " + instanceFile.getName());
                byteCount += instanceFile.length();

                for (; j < files.size(); j++) {
                    final File f = files.get(j);
                    final String fileName = f.getName();
                    final int idx = fileName.lastIndexOf(".");
                    String extension = "";
                    if (idx != -1) {
                        extension = fileName.substring(idx + 1);
                    }
                    String contentType = m.getMimeTypeFromExtension(extension);

                    // we will be processing every one of these, so
                    // we only need to deal with the content type
                    // determination...
                    if (extension.equals("xml")) {
                        fb = new FileBody(f, "text/xml");
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added xml file " + f.getName());
                    } else if (extension.equals("jpg")) {
                        fb = new FileBody(f, "image/jpeg");
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added image file " + f.getName());
                    } else if (extension.equals("3gpp")) {
                        fb = new FileBody(f, "audio/3gpp");
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added audio file " + f.getName());
                    } else if (extension.equals("3gp")) {
                        fb = new FileBody(f, "video/3gpp");
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added video file " + f.getName());
                    } else if (extension.equals("mp4")) {
                        fb = new FileBody(f, "video/mp4");
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added video file " + f.getName());
                    } else if (extension.equals("csv")) {
                        fb = new FileBody(f, "text/csv");
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added csv file " + f.getName());
                    } else if (f.getName().endsWith(".amr")) {
                        fb = new FileBody(f, "audio/amr");
                        entity.addPart(f.getName(), fb);
                        Log.i(t, "added audio file " + f.getName());
                    } else if (extension.equals("xls")) {
                        fb = new FileBody(f, "application/vnd.ms-excel");
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added xls file " + f.getName());
                    } else if (contentType != null) {
                        fb = new FileBody(f, contentType);
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added recognized filetype (" + contentType + ") " + f.getName());
                    } else {
                        contentType = "application/octet-stream";
                        fb = new FileBody(f, contentType);
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.w(t, "added unrecognized file (" + contentType + ") " + f.getName());
                    }

                    // we've added at least one attachment to the request...
                    if (j + 1 < files.size()) {
                        if (byteCount + files.get(j + 1).length() > 10000000L) {
                            // the next file would exceed the 10MB
                            // threshold...
                            Log.i(t, "Extremely long post is being split into multiple posts");
                            try {
                                final StringBody sb = new StringBody("yes", Charset.forName("UTF-8"));
                                entity.addPart("*isIncomplete*", sb);
                            } catch (final Exception e) {
                                e.printStackTrace(); // never happens...
                            }
                            ++j; // advance over the last attachment
                            // added...
                            break;
                        }
                    }
                }

                httppost.setEntity(entity);

                // prepare response and return uploaded
                HttpResponse response = null;
                try {
                    response = httpclient.execute(httppost, localContext);
                    final int responseCode = response.getStatusLine().getStatusCode();

                    // try {
                    // // have to read the stream in order to reuse the
                    // connection
                    // InputStream is = response.getEntity().getContent();
                    // // read to end of stream...
                    // final long count = 1024L;
                    // while (is.skip(count) == count)
                    // ;
                    // is.close();
                    // } catch (IOException e) {
                    // e.printStackTrace();
                    // } catch (Exception e) {
                    // e.printStackTrace();
                    // }

                    final HttpEntity httpEntity = response.getEntity();
                    try {
                        postResponse = EntityUtils.toString(httpEntity, HTTP.UTF_8).trim();
                    } catch (final IOException e) {
                        e.printStackTrace();
                    }

                    Log.i(t, "Response code:" + responseCode);
                    // verify that the response was a 201 or 202.
                    // If it wasn't, the submission has failed.
                    if (responseCode != 201 && responseCode != 202) {
                        if (responseCode == 200) {
                            mResults.put(id, fail + "Network login failure? Again?");
                        } else {
                            if (postResponse.length() > 0) {
                                mResults.put(id, postResponse);
                            } else {
                                mResults.put(id, fail + response.getStatusLine().getReasonPhrase() + " ("
                                        + responseCode + ") at " + urlString);
                            }
                        }
                        cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                        MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                        continue next_submission;
                    }
                } catch (final Exception e) {
                    e.printStackTrace();
                    mResults.put(id, fail + " " + e.getMessage());
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    continue next_submission;
                }
            }

            // if it got here, it must have worked
            if (postResponse.length() > 0) {
                // Custom msg from server
                mResults.put(id, postResponse);
            } else {
                // There is no response from server, use default string
                mResults.put(id, MIntel.getInstance().getString(R.string.success));
            }
            // mResults.put(id,
            // MIntel.getInstance().getString(R.string.success));
            cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMITTED);
            MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);

        }
        if (c != null) {
            c.close();
        }

    } // end while

    return mResults;
}

From source file:com.mpower.mintel.android.tasks.InstanceUploaderTask.java

@Override
protected HashMap<String, String> doInBackground(Long... values) {
    mResults = new HashMap<String, String>();

    String postResponse;/*  w w  w.  j a  v a  2 s .c  o m*/
    String selection = InstanceColumns._ID + "=?";
    String[] selectionArgs = new String[values.length];
    for (int i = 0; i < values.length; i++) {
        if (i != values.length - 1) {
            selection += " or " + InstanceColumns._ID + "=?";
        }
        selectionArgs[i] = values[i].toString();
    }

    // get shared HttpContext so that authentication and cookies are
    // retained.
    HttpContext localContext = MIntel.getInstance().getHttpContext();
    HttpClient httpclient = WebUtils.createHttpClient(CONNECTION_TIMEOUT);

    Map<URI, URI> uriRemap = new HashMap<URI, URI>();

    Cursor c = MIntel.getInstance().getContentResolver().query(InstanceColumns.CONTENT_URI, null, selection,
            selectionArgs, null);

    if (c.getCount() > 0) {
        c.moveToPosition(-1);
        next_submission: while (c.moveToNext()) {
            if (isCancelled()) {
                return mResults;
            }
            publishProgress(c.getPosition() + 1, c.getCount());
            String instance = c.getString(c.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
            String id = c.getString(c.getColumnIndex(InstanceColumns._ID));
            Uri toUpdate = Uri.withAppendedPath(InstanceColumns.CONTENT_URI, id);

            String urlString = c.getString(c.getColumnIndex(InstanceColumns.SUBMISSION_URI));
            if (urlString == null) {
                SharedPreferences settings = PreferenceManager
                        .getDefaultSharedPreferences(MIntel.getInstance());
                urlString = settings.getString(PreferencesActivity.KEY_SERVER_URL, null);
                urlString = urlString + WebUtils.URL_PART_SUBMISSION;
            }

            ContentValues cv = new ContentValues();
            URI u = null;
            try {
                URL url = new URL(URLDecoder.decode(urlString, "utf-8"));
                u = url.toURI();
            } catch (MalformedURLException e) {
                e.printStackTrace();
                mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage());
                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                continue;
            } catch (URISyntaxException e) {
                e.printStackTrace();
                mResults.put(id, fail + "invalid uri: " + urlString + " :: details: " + e.getMessage());
                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                continue;
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage());
                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                continue;
            }

            boolean openRosaServer = false;
            if (uriRemap.containsKey(u)) {
                // we already issued a head request and got a response,
                // so we know the proper URL to send the submission to
                // and the proper scheme. We also know that it was an
                // OpenRosa compliant server.
                openRosaServer = true;
                u = uriRemap.get(u);
            } else {
                // we need to issue a head request
                HttpHead httpHead = WebUtils.createOpenRosaHttpHead(u);

                // prepare response
                HttpResponse response = null;
                try {
                    response = httpclient.execute(httpHead, localContext);
                    int statusCode = response.getStatusLine().getStatusCode();
                    if (statusCode == 401) {
                        // we need authentication, so stop and return what
                        // we've
                        // done so far.
                        mAuthRequestingServer = u;
                        return null;
                    } else if (statusCode == 204) {
                        Header[] locations = response.getHeaders("Location");
                        if (locations != null && locations.length == 1) {
                            try {
                                URL url = new URL(URLDecoder.decode(locations[0].getValue(), "utf-8"));
                                URI uNew = url.toURI();
                                if (u.getHost().equalsIgnoreCase(uNew.getHost())) {
                                    openRosaServer = true;
                                    // trust the server to tell us a new
                                    // location
                                    // ... and possibly to use https
                                    // instead.
                                    uriRemap.put(u, uNew);
                                    u = uNew;
                                } else {
                                    // Don't follow a redirection attempt to
                                    // a different host.
                                    // We can't tell if this is a spoof or
                                    // not.
                                    mResults.put(id,
                                            fail + "Unexpected redirection attempt to a different host: "
                                                    + uNew.toString());
                                    cv.put(InstanceColumns.STATUS,
                                            InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                                    continue;
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                mResults.put(id, fail + urlString + " " + e.getMessage());
                                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                                MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                                continue;
                            }
                        }
                    } else {
                        // may be a server that does not handle
                        try {
                            // have to read the stream in order to reuse the
                            // connection
                            InputStream is = response.getEntity().getContent();
                            // read to end of stream...
                            final long count = 1024L;
                            while (is.skip(count) == count)
                                ;
                            is.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        Log.w(t, "Status code on Head request: " + statusCode);
                        if (statusCode >= 200 && statusCode <= 299) {
                            mResults.put(id, fail
                                    + "Invalid status code on Head request.  If you have a web proxy, you may need to login to your network. ");
                            cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                            MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                            continue;
                        }
                    }
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                    Log.e(t, e.getMessage());
                    mResults.put(id, fail + "Client Protocol Exception");
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    continue;
                } catch (ConnectTimeoutException e) {
                    e.printStackTrace();
                    Log.e(t, e.getMessage());
                    mResults.put(id, fail + "Connection Timeout");
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    continue;
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                    mResults.put(id, fail + e.getMessage() + " :: Network Connection Failed");
                    Log.e(t, e.getMessage());
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    continue;
                } catch (Exception e) {
                    e.printStackTrace();
                    mResults.put(id, fail + "Generic Exception");
                    Log.e(t, e.getMessage());
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    continue;
                }
            }

            // At this point, we may have updated the uri to use https.
            // This occurs only if the Location header keeps the host name
            // the same. If it specifies a different host name, we error
            // out.
            //
            // And we may have set authentication cookies in our
            // cookiestore (referenced by localContext) that will enable
            // authenticated publication to the server.
            //
            // get instance file
            File instanceFile = new File(instance);

            if (!instanceFile.exists()) {
                mResults.put(id, fail + "instance XML file does not exist!");
                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                continue;
            }

            // find all files in parent directory
            File[] allFiles = instanceFile.getParentFile().listFiles();

            // add media files
            List<File> files = new ArrayList<File>();
            for (File f : allFiles) {
                String fileName = f.getName();

                int dotIndex = fileName.lastIndexOf(".");
                String extension = "";
                if (dotIndex != -1) {
                    extension = fileName.substring(dotIndex + 1);
                }

                if (fileName.startsWith(".")) {
                    // ignore invisible files
                    continue;
                }
                if (fileName.equals(instanceFile.getName())) {
                    continue; // the xml file has already been added
                } else if (openRosaServer) {
                    files.add(f);
                } else if (extension.equals("jpg")) { // legacy 0.9x
                    files.add(f);
                } else if (extension.equals("3gpp")) { // legacy 0.9x
                    files.add(f);
                } else if (extension.equals("3gp")) { // legacy 0.9x
                    files.add(f);
                } else if (extension.equals("mp4")) { // legacy 0.9x
                    files.add(f);
                } else if (extension.equals("amr")) { // legacy 0.9x
                    files.add(f);
                } else {
                    Log.w(t, "unrecognized file type " + f.getName());
                }
            }

            postResponse = "";
            boolean first = true;
            int j = 0;
            while (j < files.size() || first) {
                first = false;

                HttpPost httppost = WebUtils.createOpenRosaHttpPost(u, mAuth);

                MimeTypeMap m = MimeTypeMap.getSingleton();

                long byteCount = 0L;

                // mime post
                MultipartEntity entity = new MultipartEntity();

                // add the submission file first...
                FileBody fb = new FileBody(instanceFile, "text/xml");
                entity.addPart("xml_submission_file", fb);
                Log.i(t, "added xml_submission_file: " + instanceFile.getName());
                byteCount += instanceFile.length();

                for (; j < files.size(); j++) {
                    File f = files.get(j);
                    String fileName = f.getName();
                    int idx = fileName.lastIndexOf(".");
                    String extension = "";
                    if (idx != -1) {
                        extension = fileName.substring(idx + 1);
                    }
                    String contentType = m.getMimeTypeFromExtension(extension);

                    // we will be processing every one of these, so
                    // we only need to deal with the content type
                    // determination...
                    if (extension.equals("xml")) {
                        fb = new FileBody(f, "text/xml");
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added xml file " + f.getName());
                    } else if (extension.equals("jpg")) {
                        fb = new FileBody(f, "image/jpeg");
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added image file " + f.getName());
                    } else if (extension.equals("3gpp")) {
                        fb = new FileBody(f, "audio/3gpp");
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added audio file " + f.getName());
                    } else if (extension.equals("3gp")) {
                        fb = new FileBody(f, "video/3gpp");
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added video file " + f.getName());
                    } else if (extension.equals("mp4")) {
                        fb = new FileBody(f, "video/mp4");
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added video file " + f.getName());
                    } else if (extension.equals("csv")) {
                        fb = new FileBody(f, "text/csv");
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added csv file " + f.getName());
                    } else if (f.getName().endsWith(".amr")) {
                        fb = new FileBody(f, "audio/amr");
                        entity.addPart(f.getName(), fb);
                        Log.i(t, "added audio file " + f.getName());
                    } else if (extension.equals("xls")) {
                        fb = new FileBody(f, "application/vnd.ms-excel");
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added xls file " + f.getName());
                    } else if (contentType != null) {
                        fb = new FileBody(f, contentType);
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added recognized filetype (" + contentType + ") " + f.getName());
                    } else {
                        contentType = "application/octet-stream";
                        fb = new FileBody(f, contentType);
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.w(t, "added unrecognized file (" + contentType + ") " + f.getName());
                    }

                    // we've added at least one attachment to the request...
                    if (j + 1 < files.size()) {
                        if (byteCount + files.get(j + 1).length() > 10000000L) {
                            // the next file would exceed the 10MB
                            // threshold...
                            Log.i(t, "Extremely long post is being split into multiple posts");
                            try {
                                StringBody sb = new StringBody("yes", Charset.forName("UTF-8"));
                                entity.addPart("*isIncomplete*", sb);
                            } catch (Exception e) {
                                e.printStackTrace(); // never happens...
                            }
                            ++j; // advance over the last attachment
                                 // added...
                            break;
                        }
                    }
                }

                httppost.setEntity(entity);

                // prepare response and return uploaded
                HttpResponse response = null;
                try {
                    response = httpclient.execute(httppost, localContext);
                    int responseCode = response.getStatusLine().getStatusCode();

                    // try {
                    // // have to read the stream in order to reuse the
                    // connection
                    // InputStream is = response.getEntity().getContent();
                    // // read to end of stream...
                    // final long count = 1024L;
                    // while (is.skip(count) == count)
                    // ;
                    // is.close();
                    // } catch (IOException e) {
                    // e.printStackTrace();
                    // } catch (Exception e) {
                    // e.printStackTrace();
                    // }

                    HttpEntity httpEntity = response.getEntity();
                    try {
                        postResponse = EntityUtils.toString(httpEntity, HTTP.UTF_8).trim();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    Log.i(t, "Response code:" + responseCode);
                    // verify that the response was a 201 or 202.
                    // If it wasn't, the submission has failed.
                    if (responseCode != 201 && responseCode != 202) {
                        if (responseCode == 200) {
                            mResults.put(id, fail + "Network login failure? Again?");
                        } else {
                            if (postResponse.length() > 0) {
                                mResults.put(id, postResponse);
                            } else {
                                mResults.put(id, fail + response.getStatusLine().getReasonPhrase() + " ("
                                        + responseCode + ") at " + urlString);
                            }
                        }
                        cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                        MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                        continue next_submission;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    mResults.put(id, fail + " " + e.getMessage());
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    continue next_submission;
                }
            }

            // if it got here, it must have worked
            if (postResponse.length() > 0) {
                // Custom msg from server
                mResults.put(id, postResponse);
            } else {
                // There is no response from server, use default string
                mResults.put(id, MIntel.getInstance().getString(R.string.success));
            }
            // mResults.put(id,
            // MIntel.getInstance().getString(R.string.success));
            cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMITTED);
            MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);

        }
        if (c != null) {
            c.close();
        }

    } // end while

    return mResults;
}

From source file:com.money.manager.ex.common.CategoryListFragment.java

public CategoryExpandableListAdapter getAdapter(Cursor data) {
    if (data == null)
        return null;

    mCategories.clear();/*  w ww .java2  s. c o m*/
    mSubCategories.clear();
    mPositionToExpand.clear();
    // create core and fixed string filter to highlight
    Core core = new Core(getActivity().getApplicationContext());
    String filter = mCurFilter != null ? mCurFilter.replace("%", "") : "";

    int key = -1;
    List<QueryCategorySubCategory> listSubCategories = null;

    // reset cursor if getting back on the fragment.
    if (data.getPosition() > 0) {
        data.moveToPosition(Constants.NOT_SET);
    }

    while (data.moveToNext()) {
        if (key != data.getInt(data.getColumnIndex(QueryCategorySubCategory.CATEGID))) {
            // check if listCategories > 0
            if (mCategories.size() > 0 && listSubCategories != null) {
                mSubCategories.put(mCategories.get(mCategories.size() - 1), listSubCategories);
            }
            // update key
            key = data.getInt(data.getColumnIndex(QueryCategorySubCategory.CATEGID));

            // create instance category
            Category category = new Category();
            category.setId(data.getInt(data.getColumnIndex(QueryCategorySubCategory.CATEGID)));
            category.setName(core
                    .highlight(filter, data.getString(data.getColumnIndex(QueryCategorySubCategory.CATEGNAME)))
                    .toString());

            // add list
            mCategories.add(category);
            listSubCategories = new ArrayList<>();
        }

        if (data.getInt(data.getColumnIndex(QueryCategorySubCategory.SUBCATEGID)) != Constants.NOT_SET) {
            QueryCategorySubCategory subCategory = new QueryCategorySubCategory(getActivity());
            // subcategory
            subCategory.setSubCategId(data.getInt(data.getColumnIndex(QueryCategorySubCategory.SUBCATEGID)));
            subCategory.setSubcategoryName(core.highlight(filter,
                    data.getString(data.getColumnIndex(QueryCategorySubCategory.SUBCATEGNAME))));
            subCategory.setCategId(data.getInt(data.getColumnIndex(QueryCategorySubCategory.CATEGID)));
            subCategory.setCategName(core.highlight(filter,
                    data.getString(data.getColumnIndex(QueryCategorySubCategory.CATEGNAME))));
            // add to hashmap
            listSubCategories.add(subCategory);
            // check if expand group
            if (!TextUtils.isEmpty(filter)) {
                String normalizedText = Normalizer
                        .normalize(subCategory.getSubcategoryName(), Normalizer.Form.NFD)
                        .replaceAll("\\p{InCombiningDiacriticalMarks}+", "").toLowerCase();
                if ((normalizedText.indexOf(filter) >= 0)
                        && (!mPositionToExpand.contains(mCategories.size() - 1))) {
                    mPositionToExpand.add(mCategories.size() - 1);
                }
            }
        }
    }
    if (mCategories.size() > 0 && listSubCategories != null) {
        mSubCategories.put(mCategories.get(mCategories.size() - 1), listSubCategories);
    }

    boolean showSelector = mAction.equals(Intent.ACTION_PICK);
    CategoryExpandableListAdapter adapter = new CategoryExpandableListAdapter(getActivity(), mLayout,
            mCategories, mSubCategories, showSelector);
    adapter.setIdChildChecked(mIdGroupChecked, mIdChildChecked);
    return adapter;
}

From source file:com.dpcsoftware.mn.CategoryStats.java

public void renderGraph() {
    SQLiteDatabase db = DatabaseHelper.quickDb(this, 0);
    if (date == null)
        date = Calendar.getInstance().getTime();

    String queryModifier = "";
    if (isByMonth)
        queryModifier = " AND strftime('%Y-%m'," + Db.Table1.TABLE_NAME + "." + Db.Table1.COLUMN_DATAT + ") = '"
                + app.dateToDb("yyyy-MM", date) + "'";

    Cursor c = db.rawQuery("SELECT " + Db.Table2.TABLE_NAME + "." + Db.Table2._ID + "," + Db.Table2.TABLE_NAME
            + "." + Db.Table2.COLUMN_NCAT + "," + Db.Table2.TABLE_NAME + "." + Db.Table2.COLUMN_CORCAT + ","
            + "SUM(" + Db.Table1.TABLE_NAME + "." + Db.Table1.COLUMN_VALORT + ")" + " FROM "
            + Db.Table1.TABLE_NAME + "," + Db.Table2.TABLE_NAME + " WHERE " + Db.Table1.TABLE_NAME + "."
            + Db.Table1.COLUMN_IDCAT + " = " + Db.Table2.TABLE_NAME + "." + Db.Table2._ID + " AND "
            + Db.Table1.TABLE_NAME + "." + Db.Table1.COLUMN_IDGRUPO + " = " + app.activeGroupId + queryModifier
            + " GROUP BY " + Db.Table1.TABLE_NAME + "." + Db.Table1.COLUMN_IDCAT + " ORDER BY "
            + Db.Table2.COLUMN_NCAT, null);

    float[] values = new float[c.getCount()];
    int[] colors = new int[c.getCount()];
    float total = 0;

    while (c.moveToNext()) {
        values[c.getPosition()] = c.getFloat(3);
        colors[c.getPosition()] = c.getInt(2);
        total += c.getFloat(3);/* w  w w.  j av a 2 s.  co m*/
    }

    BarChart v = new BarChart(this, values, colors);
    v.setPadding(10, 10, 10, 10);
    FrameLayout graphLayout = ((FrameLayout) findViewById(R.id.FrameLayout1));
    if (graphLayout.getChildCount() == 1)
        graphLayout.removeViewAt(0);
    graphLayout.addView(v);

    ListView lv = ((ListView) findViewById(R.id.listView1));
    ((TextView) footer.findViewById(R.id.textView2)).setText(app.printMoney(total));

    int days = 1;
    if (!isByMonth) {
        SimpleDateFormat dateF = new SimpleDateFormat("yyyy-MM-dd");
        dateF.setTimeZone(TimeZone.getDefault());

        Cursor cTemp = db.rawQuery("SELECT " + Db.Table1.COLUMN_DATAT + " FROM " + Db.Table1.TABLE_NAME
                + " WHERE " + Db.Table1.COLUMN_IDGRUPO + " = " + app.activeGroupId + " ORDER BY "
                + Db.Table1.COLUMN_DATAT + " DESC", null);
        try {
            cTemp.moveToFirst();
            Date date2 = dateF.parse(cTemp.getString(0));
            cTemp.moveToLast();
            Date date1 = dateF.parse(cTemp.getString(0));

            days = (int) Math.ceil((date2.getTime() - date1.getTime()) / (1000.0 * 24 * 60 * 60)) + 1;

            App.Log("" + days);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        Calendar now = Calendar.getInstance();
        if (cal.get(Calendar.MONTH) == now.get(Calendar.MONTH)
                && cal.get(Calendar.YEAR) == now.get(Calendar.YEAR))
            days = now.get(Calendar.DAY_OF_MONTH);
        else
            days = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    ((TextView) footer2.findViewById(R.id.textView2)).setText(app.printMoney(total / days));

    ((TextView) findViewById(R.id.textViewMonth)).setText(app.dateToUser("MMMM / yyyy", date));

    if (adapter == null) {
        adapter = new CategoryStatsAdapter(this, c, total);
        lv.setAdapter(adapter);
    } else {
        adapter.changeCursor(c, total);
        adapter.notifyDataSetChanged();
    }
}