Example usage for android.database Cursor moveToPosition

List of usage examples for android.database Cursor moveToPosition

Introduction

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

Prototype

boolean moveToPosition(int position);

Source Link

Document

Move the cursor to an absolute position.

Usage

From source file:org.dvbviewer.controller.ui.fragments.ChannelList.java

public boolean onContextItemSelected(MenuItem item) {
    if (item.getMenuInfo() != null) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        selectedPosition = info.position;
    }//from  w  w  w  . j  a  v  a 2 s  . co  m
    Cursor c = mAdapter.getCursor();
    c.moveToPosition(selectedPosition);
    Channel chan = cursorToChannel(c);
    Timer timer;
    switch (item.getItemId()) {
    case R.id.menuTimer:
        timer = cursorToTimer(c);
        if (UIUtils.isTablet(getActivity())) {
            TimerDetails timerdetails = TimerDetails.newInstance();
            Bundle args = new Bundle();
            args.putString(TimerDetails.EXTRA_TITLE, timer.getTitle());
            args.putString(TimerDetails.EXTRA_CHANNEL_NAME, timer.getChannelName());
            args.putLong(TimerDetails.EXTRA_CHANNEL_ID, timer.getChannelId());
            args.putLong(TimerDetails.EXTRA_START, timer.getStart().getTime());
            args.putLong(TimerDetails.EXTRA_END, timer.getEnd().getTime());
            timerdetails.setArguments(args);
            timerdetails.show(getSherlockActivity().getSupportFragmentManager(), TimerDetails.class.getName());
        } else {
            Intent timerIntent = new Intent(getActivity(), TimerDetailsActivity.class);
            timerIntent.putExtra(TimerDetails.EXTRA_TITLE, timer.getTitle());
            timerIntent.putExtra(TimerDetails.EXTRA_CHANNEL_NAME, timer.getChannelName());
            timerIntent.putExtra(TimerDetails.EXTRA_CHANNEL_ID, timer.getChannelId());
            timerIntent.putExtra(TimerDetails.EXTRA_START, timer.getStart().getTime());
            timerIntent.putExtra(TimerDetails.EXTRA_END, timer.getEnd().getTime());
            startActivity(timerIntent);
        }
        return true;
    case R.id.menuStream:
        if (UIUtils.isTablet(getActivity())) {
            StreamConfig cfg = StreamConfig.newInstance();
            Bundle arguments = new Bundle();
            arguments.putInt(StreamConfig.EXTRA_FILE_ID, chan.getPosition());
            arguments.putInt(StreamConfig.EXTRA_FILE_TYPE, StreamConfig.FILE_TYPE_LIVE);
            arguments.putInt(StreamConfig.EXTRA_DIALOG_TITLE_RES, R.string.streamConfig);
            cfg.setArguments(arguments);
            cfg.show(getSherlockActivity().getSupportFragmentManager(), StreamConfig.class.getName());
        } else {
            Intent streamConfig = new Intent(getActivity(), StreamConfigActivity.class);
            streamConfig.putExtra(StreamConfig.EXTRA_FILE_ID, chan.getPosition());
            streamConfig.putExtra(StreamConfig.EXTRA_FILE_TYPE, StreamConfig.FILE_TYPE_LIVE);
            streamConfig.putExtra(StreamConfig.EXTRA_DIALOG_TITLE_RES, R.string.streamConfig);
            startActivity(streamConfig);
        }
        return true;
    case R.id.menuSwitch:
        String switchRequest = ServerConsts.URL_SWITCH_COMMAND + chan.getPosition();
        DVBViewerCommand command = new DVBViewerCommand(switchRequest);
        Thread exexuterTHread = new Thread(command);
        exexuterTHread.start();
        return true;
    case R.id.menuRecord:
        timer = cursorToTimer(c);
        String url = timer.getId() <= 0l ? ServerConsts.URL_TIMER_CREATE : ServerConsts.URL_TIMER_EDIT;
        String title = timer.getTitle();
        String days = String.valueOf(DateUtils.getDaysSinceDelphiNull(timer.getStart()));
        String start = String.valueOf(DateUtils.getMinutesOfDay(timer.getStart()));
        String stop = String.valueOf(DateUtils.getMinutesOfDay(timer.getEnd()));
        String endAction = String.valueOf(timer.getTimerAction());
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("ch", String.valueOf(timer.getChannelId())));
        params.add(new BasicNameValuePair("dor", days));
        params.add(new BasicNameValuePair("encoding", "255"));
        params.add(new BasicNameValuePair("enable", "1"));
        params.add(new BasicNameValuePair("start", start));
        params.add(new BasicNameValuePair("stop", stop));
        params.add(new BasicNameValuePair("title", title));
        params.add(new BasicNameValuePair("endact", endAction));
        if (timer.getId() > 0) {
            params.add(new BasicNameValuePair("id", String.valueOf(timer.getId())));
        }

        String query = URLEncodedUtils.format(params, "utf-8");
        String request = url + query;
        RecordingServiceGet rsGet = new RecordingServiceGet(request);
        Thread executionThread = new Thread(rsGet);
        executionThread.start();
        return true;

    default:
        break;
    }
    return false;
}

From source file:org.dvbviewer.controller.ui.fragments.ChannelList.java

/**
 * Cursor to channellist.//w  w  w .  j a  v a  2s . co m
 *
 * @param position the position
 * @return the array list
 * @author RayBa
 * @date 07.04.2013
 */
private ArrayList<Channel> cursorToChannellist(int position) {
    Cursor c = (Cursor) mAdapter.getItem(position);
    ArrayList<Channel> chans = new ArrayList<Channel>();
    c.moveToPosition(-1);
    while (c.moveToNext()) {
        Channel channel = new Channel();
        channel.setId(c.getLong(c.getColumnIndex(ChannelTbl._ID)));
        channel.setEpgID(c.getLong(c.getColumnIndex(ChannelTbl.EPG_ID)));
        channel.setLogoUrl(c.getString(c.getColumnIndex(ChannelTbl.LOGO_URL)));
        String name = c.getString(c.getColumnIndex(ChannelTbl.NAME));
        channel.setName(name);
        channel.setPosition(c.getInt(c.getColumnIndex(ChannelTbl.POSITION)));
        chans.add(channel);
    }
    return chans;
}

From source file:net.ddns.mlsoftlaberge.contactslist.ui.ContactsListFragment.java

@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    // Gets the Cursor object currently bound to the ListView
    final Cursor cursor = mAdapter.getCursor();

    // Moves to the Cursor row corresponding to the ListView item that was clicked
    cursor.moveToPosition(position);

    // Creates a contact lookup Uri from contact ID and lookup_key
    final Uri uri = Contacts.getLookupUri(cursor.getLong(ContactsQuery.ID),
            cursor.getString(ContactsQuery.LOOKUP_KEY));

    // Notifies the parent activity that the user selected a contact. In a two-pane layout, the
    // parent activity loads a ContactAdminFragment that displays the details for the selected
    // contact. In a single-pane layout, the parent activity starts a new activity that
    // displays contact details in its own Fragment.
    mOnContactSelectedListener.onContactSelected(uri);

    // If two-pane layout sets the selected item to checked so it remains highlighted. In a
    // single-pane layout a new activity is started so this is not needed.
    if (mIsTwoPaneLayout) {
        getListView().setItemChecked(position, true);
    }/* w w  w  . j ava  2  s  .  com*/
}

From source file:com.android.contacts.list.ContactEntryListAdapter.java

/**
 * Checks whether the contact entry at the given position represents the user's profile.
 *//*  w  w  w . j a v a  2  s  . com*/
protected boolean isUserProfile(int position) {
    // The profile only ever appears in the first position if it is present.  So if the position
    // is anything beyond 0, it can't be the profile.
    boolean isUserProfile = false;
    if (position == 0) {
        int partition = getPartitionForPosition(position);
        if (partition >= 0) {
            // Save the old cursor position - the call to getItem() may modify the cursor
            // position.
            int offset = getCursor(partition).getPosition();
            Cursor cursor = (Cursor) getItem(position);
            if (cursor != null) {
                int profileColumnIndex = cursor.getColumnIndex(Contacts.IS_USER_PROFILE);
                if (profileColumnIndex != -1) {
                    isUserProfile = cursor.getInt(profileColumnIndex) == 1;
                }
                // Restore the old cursor position.
                cursor.moveToPosition(offset);
            }
        }
    }
    return isUserProfile;
}

From source file:co.carlosjimenez.android.currencyalerts.app.DetailActivityFragment.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {

    if (data == null) {
        Log.d(LOG_TAG, "Detail Forex Loader Finished: No data returned");

        return;//ww  w.ja  v a 2s  .  c o  m
    }
    if (!data.moveToFirst()) {
        Log.d(LOG_TAG, "Detail Forex Loader Finished: No data returned");

        data.close();
        return;
    }

    long lDate = 0;
    String sDate = "";
    String sCurrency = "";
    int i = 0;
    double dRateAverage = 0;
    double dVal = 0;
    double dMinVal = 0;
    double dMaxVal = 0;

    data.moveToPosition(0);

    mCurrencyFromId = data.getString(COL_CURRENCY_FROM_ID);
    String currencyFromName = data.getString(COL_CURRENCY_FROM_NAME);
    String currencyFromSymbol = data.getString(COL_CURRENCY_FROM_SYMBOL);
    String countryFromName = data.getString(COL_COUNTRY_FROM_NAME);
    double currencyFromRate = ForexContract.RateEntry.getRateFromUri(mUri);

    mCurrencyToId = data.getString(COL_CURRENCY_TO_ID);
    String currencyToName = data.getString(COL_CURRENCY_TO_NAME);
    String currencyToSymbol = data.getString(COL_CURRENCY_TO_SYMBOL);
    String countryToName = data.getString(COL_COUNTRY_TO_NAME);
    double currencyToRate = ForexContract.RateEntry.getRateFromUri(mUri) * data.getDouble(COL_RATE_VAL);

    Glide.with(getActivity()).load(data.getString(COL_COUNTRY_FROM_FLAG)).error(R.drawable.globe).crossFade()
            .into(mIvFlagFrom);
    mIvFlagFrom.setContentDescription(Utility.formatCountryFlagName(mContext, countryFromName));

    Glide.with(getActivity()).load(data.getString(COL_COUNTRY_TO_FLAG)).error(R.drawable.globe).crossFade()
            .into(mIvFlagTo);
    mIvFlagFrom.setContentDescription(Utility.formatCountryFlagName(mContext, countryToName));

    mTvCurrencyFromDesc.setText(currencyFromName);
    mTvCurrencyFromDesc.setContentDescription(currencyFromName);

    mTvCurrencyFromRate
            .setText(Utility.formatCurrencyRate(getActivity(), currencyFromSymbol, currencyFromRate));
    mTvCurrencyFromRate.setContentDescription(String.valueOf(currencyFromRate) + " " + currencyFromName);

    mTvCurrencyToDesc.setText(currencyToName);
    mTvCurrencyToDesc.setContentDescription(currencyToName);

    mTvCurrencyToRate.setText(Utility.formatCurrencyRate(getActivity(), currencyToSymbol, currencyToRate));
    mTvCurrencyToRate.setContentDescription(String.valueOf(currencyToRate) + " " + currencyToName);

    Time dayTime = new Time();
    dayTime.setToNow();

    int julianDate = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);

    dayTime = new Time();
    long lMinDate = dayTime.setJulianDay(julianDate - DEFAULT_DAYS_FOREX_AVERAGE);

    sDate = Utility.getDateString(getActivity(), data.getLong(COL_RATE_DATE));

    for (i = 0; i < data.getCount() && i < DEFAULT_DAYS_FOREX_AVERAGE; i++) {
        data.moveToPosition(i);

        lDate = data.getLong(COL_RATE_DATE);
        if (lDate < lMinDate) {
            break;
        }

        sCurrency = data.getString(COL_CURRENCY_TO_ID);
        sDate = Utility.getDateString(getActivity(), lDate);
        dVal = data.getDouble(COL_RATE_VAL);
        dRateAverage += dVal;

        if (i == 0) {
            dMinVal = dVal;
            dMaxVal = dVal;
        } else {
            dMinVal = dMinVal < dVal ? dMinVal : dVal;
            dMaxVal = dMaxVal > dVal ? dMaxVal : dVal;
        }
    }
    dRateAverage = dRateAverage / i;

    if (data.getCount() > 1)
        mTvPeriod.setText(data.getCount() + " days");
    else
        mTvPeriod.setText(data.getCount() + " day");
    mTvMaxRate.setContentDescription(mTvPeriod.getText());

    mTvMaxRate.setText(
            Utility.formatCurrencyRate(getActivity(), data.getString(COL_CURRENCY_TO_SYMBOL), dMaxVal));
    mTvMaxRate.setContentDescription(mTvMaxRate.getText());

    mTvMinRate.setText(
            Utility.formatCurrencyRate(getActivity(), data.getString(COL_CURRENCY_TO_SYMBOL), dMinVal));
    mTvMinRate.setContentDescription(mTvMinRate.getText());

    mTvAverageRate.setText(
            Utility.formatCurrencyRate(getActivity(), data.getString(COL_CURRENCY_TO_SYMBOL), dRateAverage));
    mTvAverageRate.setContentDescription(mTvAverageRate.getText());

    // String text to share if user clicks on share menu icon
    mDisplayedRate = String.format("%s - %s %s = %s %s", sDate, currencyFromRate, mCurrencyFromId,
            currencyToRate, mCurrencyToId);
    mDisplayedCurrencyIds = mCurrencyFromId + "-" + mCurrencyToId;
    mDisplayedCurrencyNames = currencyToName;

    mContext.supportStartPostponedEnterTransition();

    if (null != mToolbar) {
        Menu menu = mToolbar.getMenu();
        if (null != menu)
            menu.clear();
        mToolbar.inflateMenu(R.menu.detailfragment);
        finishCreatingMenu(mToolbar.getMenu());
    }
}

From source file:co.carlosjimenez.android.currencyalerts.app.MainActivityFragment.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    String maxRateString = "";
    String rateString = "";
    String maxRateSymbol = "";
    double maxRateValue = 0;

    updateEmptyView();//from w  w  w  .  j a v a2 s . c o m

    if (data == null) {
        Log.d(LOG_TAG, "Main Forex Loader Finished: No data returned");

        return;
    }
    if (data.getCount() <= 0) {
        Log.d(LOG_TAG, "Main Forex Loader Finished: No data returned");

        data.close();
        return;
    }

    for (int i = 0; i < data.getCount(); i++) {
        data.moveToPosition(i);
        rateString = Utility.formatCurrencyRate(getActivity(), data.getString(COL_CURRENCY_TO_SYMBOL),
                data.getDouble(COL_RATE_VAL));

        if (rateString.length() > maxRateString.length()) {
            maxRateString = rateString;
            maxRateSymbol = data.getString(COL_CURRENCY_TO_SYMBOL);
            maxRateValue = data.getDouble(COL_RATE_VAL);
        }
    }

    mForexAdapter.setMaxRateVal(maxRateSymbol, maxRateValue);
    mForexAdapter.swapCursor(data);
}

From source file:com.radar.niyo.contacts.ContactsListFragment.java

@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    // Gets the Cursor object currently bound to the ListView
    final Cursor cursor = mAdapter.getCursor();

    // Moves to the Cursor row corresponding to the ListView item that was clicked
    cursor.moveToPosition(position);

    // Creates a contact lookup Uri from contact ID and lookup_key
    //        final Uri uri = Contacts.getLookupUri(
    //                cursor.getLong(ContactsQuery.ID),
    //                cursor.getString(ContactsQuery.LOOKUP_KEY));
    //        /*w  w  w  .jav a2 s .c om*/
    //        Log.i("FragmentComplexList", "Item clicked: " + id);

    String name = cursor.getString(ContactsQuery.DISPLAY_NAME);
    String email = cursor.getString(ContactsQuery.EMAIL_ADDRESS);

    InsertNewFriendTask task = new InsertNewFriendTask(getActivity(), new ServiceCaller() {

        @Override
        public void success(Object data) {
            getActivity().finish();
        }

        @Override
        public void failure(Object data, String description) {
            // TODO Auto-generated method stub

        }
    });

    RadarFriend friend = new RadarFriend(name, email);
    task.execute(friend);

    // Notifies the parent activity that the user selected a contact. In a two-pane layout, the
    // parent activity loads a ContactDetailFragment that displays the details for the selected
    // contact. In a single-pane layout, the parent activity starts a new activity that
    // displays contact details in its own Fragment.
    //        mOnContactSelectedListener.onContactSelected(uri);

    // If two-pane layout sets the selected item to checked so it remains highlighted. In a
    // single-pane layout a new activity is started so this is not needed.
    //        if (mIsTwoPaneLayout) {
    //            getListView().setItemChecked(position, true);
    //        }
}

From source file:learn2crack.activities.ContactsListFragment.java

@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    // Gets the Cursor object currently bound to the ListView
    final Cursor cursor = mAdapter.getCursor();

    // Moves to the Cursor row corresponding to the ListView item that was clicked
    cursor.moveToPosition(position);

    // Creates a contact lookup Uri from contact ID and lookup_key
    final Uri uri = Contacts.getLookupUri(cursor.getLong(ContactsQuery.ID),
            cursor.getString(ContactsQuery.LOOKUP_KEY));

    // Notifies the parent activity that the user selected a contact. In a two-pane layout, the
    // parent activity loads a ContactDetailFragment that displays the details for the selected
    // contact. In a single-pane layout, the parent activity starts a new activity that
    // displays contact details in its own Fragment.
    mOnContactSelectedListener.onContactSelected(uri);

    registerForContextMenu(parent);/*w  w  w.  j  ava  2  s  . c o  m*/
    parent.setTag(R.id.TAG_HAS_WN, v.getTag(R.id.TAG_HAS_WN));
    parent.setTag(R.id.TAG_CONTACT_ID, v.getTag(R.id.TAG_CONTACT_ID));
    parent.showContextMenu();
    unregisterForContextMenu(parent);

    // If two-pane layout sets the selected item to checked so it remains highlighted. In a
    // single-pane layout a new activity is started so this is not needed.
    if (mIsTwoPaneLayout) {
        getListView().setItemChecked(position, true);
    }
    //getListView().setItemChecked(position, false);
}

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;//  ww  w  . ja va2 s.c om
    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.cordova.photo.CameraLauncher.java

private int getImageOrientation(Uri uri) {
    int rotate = 0;
    String[] cols = { MediaStore.Images.Media.ORIENTATION };
    try {/*from w w w  .j av a  2 s  . c om*/
        Cursor cursor = activity.getContentResolver().query(uri, cols, null, null, null);
        if (cursor != null) {
            cursor.moveToPosition(0);
            rotate = cursor.getInt(0);
            cursor.close();
        }
    } catch (Exception e) {
        // You can get an IllegalArgumentException if ContentProvider doesn't support querying for orientation.
    }
    return rotate;
}