Example usage for android.database Cursor getCount

List of usage examples for android.database Cursor getCount

Introduction

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

Prototype

int getCount();

Source Link

Document

Returns the numbers of rows in the cursor.

Usage

From source file:edu.mit.mobile.android.locast.data.Sync.java

/**
 * Sync the given URI to the server. Will compare dates and do a two-way sync.
 * Does not yet handle the case where both server and and local are modified
 * (collisions)/*  www. j av a2s .c o  m*/
 *
 * @param toSync URI of the object to sync. Generally, this should be the dir URI
 * @param sync A new object that extends JsonSyncableItem. This is needed for the JSON
 * serialization routine in it, as well as the sync map.
 * @throws IOException
 */
private void sync(Uri toSync, JsonSyncableItem sync, SyncProgressNotifier syncProgress, Bundle extras)
        throws SyncException, IOException {
    String netPath;
    boolean haveItemPubUri = false;

    if ("http".equals(toSync.getScheme()) || "https".equals(toSync.getScheme())) {
        netPath = toSync.getPath();
        toSync = (Uri) extras.get(EXTRA_DESTINATION_URI);
        haveItemPubUri = true;
    } else {
        netPath = null;
    }
    final String contentType = getContentResolver().getType(toSync);

    final Cursor c = cr.query(toSync, sync.getFullProjection(), null, null, null);
    try {
        syncProgress.addPendingTasks(c.getCount());

        // Handle a list of items.
        if (contentType.startsWith(CONTENT_TYPE_PREFIX_DIR)) {
            // load from the network first...
            if (netPath == null) {
                netPath = MediaProvider.getPublicPath(this, toSync);
            }
            syncNetworkList(toSync, netPath, sync, syncProgress);
        } else if (haveItemPubUri) {
            syncNetworkItem(toSync, netPath, sync, syncProgress);
        }

        // then load locally.

        if (DEBUG) {
            Log.d(TAG, "have " + c.getCount() + " local items to sync");
        }
        for (c.moveToFirst(); (currentSyncTask != null && !currentSyncTask.isCancelled()) && !c.isAfterLast(); c
                .moveToNext()) {
            try {
                syncItem(toSync, c, null, sync, syncProgress, netPath);
                syncProgress.completeTask();

            } catch (final SyncItemDeletedException side) {
                if (DEBUG) {
                    Log.d(TAG, side.getLocalizedMessage() + " Deleting...");
                }
                cr.delete(side.getItem(), null, null);
                //side.printStackTrace();
                syncProgress.completeTask();
                continue;
            }
        }
    } catch (final NoPublicPath npp) {
        // XXX this should be a hard error
        Log.e(TAG, "Sync Error: " + npp.getLocalizedMessage());
        return;
    } finally {
        c.close();
    }
}

From source file:org.tomahawk.libtomahawk.database.DatabaseHelper.java

/**
 * Checks if an artist with the same artistName as the given artist is loved
 *
 * @return whether or not the given artist is loved
 *//*www .j av a2  s  .  c  o m*/
public boolean isItemLoved(Artist artist) {
    boolean isLoved = false;
    String[] columns = new String[] { TomahawkSQLiteHelper.LOVED_ARTISTS_COLUMN_ARTISTNAME };

    Cursor artistsCursor = mDatabase.query(TomahawkSQLiteHelper.TABLE_LOVED_ARTISTS, columns,
            TomahawkSQLiteHelper.LOVED_ARTISTS_COLUMN_ARTISTNAME + " = ?", new String[] { artist.getName() },
            null, null, null);
    if (artistsCursor.getCount() > 0) {
        isLoved = true;
    }
    artistsCursor.close();
    return isLoved;
}

From source file:org.tomahawk.libtomahawk.database.DatabaseHelper.java

/**
 * @param playlistId the id by which to get the correct {@link org.tomahawk.libtomahawk.collection.Playlist}
 * @return the stored {@link org.tomahawk.libtomahawk.collection.Playlist} with playlistId as
 * its id/*w w w . jav a2 s . c o m*/
 */
public int getPlaylistTrackCount(String playlistId) {
    int count = 0;
    String[] columns = new String[] { TomahawkSQLiteHelper.PLAYLISTS_COLUMN_NAME,
            TomahawkSQLiteHelper.PLAYLISTS_COLUMN_CURRENTREVISION,
            TomahawkSQLiteHelper.PLAYLISTS_COLUMN_CURRENTTRACKINDEX };

    Cursor playlistsCursor = mDatabase.query(TomahawkSQLiteHelper.TABLE_PLAYLISTS, columns,
            TomahawkSQLiteHelper.PLAYLISTS_COLUMN_ID + " = ?", new String[] { playlistId }, null, null, null);
    if (playlistsCursor.moveToFirst()) {
        columns = new String[] { TomahawkSQLiteHelper.TRACKS_COLUMN_ID };
        Cursor tracksCursor = mDatabase.query(TomahawkSQLiteHelper.TABLE_TRACKS, columns,
                TomahawkSQLiteHelper.TRACKS_COLUMN_PLAYLISTID + " = ?", new String[] { playlistId }, null, null,
                null);
        count = tracksCursor.getCount();
        tracksCursor.close();
    }
    playlistsCursor.close();
    return count;
}

From source file:de.stadtrallye.rallyesoft.model.chat.Chatroom.java

@Override
public IPictureGallery getPictureGallery(String initialPictureHash) {
    Cursor c = getDb().query(DatabaseHelper.Chats.TABLE, new String[] { DatabaseHelper.Chats.KEY_PICTURE },
            DatabaseHelper.Chats.KEY_PICTURE + " <> 0 AND " + DatabaseHelper.Chats.FOREIGN_ROOM + " = ?",
            new String[] { Integer.toString(chatroomID) }, DatabaseHelper.Chats.KEY_PICTURE, null,
            DatabaseHelper.Chats.KEY_TIME);
    String[] pictures = new String[c.getCount()];
    int initialPos = 0;

    String hash;/*w  w w .  j a v  a 2  s .  c  o m*/
    int i = 0;
    while (c.moveToNext()) {
        hash = c.getString(0);
        pictures[i] = hash;
        if (initialPictureHash.equals(hash)) {
            initialPos = i;
        }
        i++;
    }
    c.close();

    return new PictureGallery(initialPos, pictures, Server.getCurrentServer().getPictureResolver());
}

From source file:com.example.android.network.sync.basicsyncadapter.SyncAdapter.java

/**
 * Read XML from an input stream, storing it into the content provider.
 *
 * <p>This is where incoming data is persisted, committing the results of a sync. In order to
 * minimize (expensive) disk operations, we compare incoming data with what's already in our
 * database, and compute a merge. Only changes (insert/update/delete) will result in a database
 * write.//from   ww w  . ja  v a2  s.  com
 *
 * <p>As an additional optimization, we use a batch operation to perform all database writes at
 * once.
 *
 * <p>Merge strategy:
 * 1. Get cursor to all items in feed<br/>
 * 2. For each item, check if it's in the incoming data.<br/>
 *    a. YES: Remove from "incoming" list. Check if data has mutated, if so, perform
 *            database UPDATE.<br/>
 *    b. NO: Schedule DELETE from database.<br/>
 * (At this point, incoming database only contains missing items.)<br/>
 * 3. For any items remaining in incoming list, ADD to database.
 */
public void updateLocalFeedData(final InputStream stream, final SyncResult syncResult) throws IOException,
        XmlPullParserException, RemoteException, OperationApplicationException, ParseException {

    final ContentResolver contentResolver = getContext().getContentResolver();

    Log.i(TAG, "Parsing stream as Atom feed");
    final List<Transformer> entries = null;
    /*=this.parseTransformersResponse(stream)*/;
    ;
    Log.i(TAG, "Parsing complete. Found " + entries.size() + " entries");

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

    // Build hash table of incoming entries
    HashMap<String, Transformer> entryMap = new HashMap<String, Transformer>();
    for (Transformer e : entries) {
        entryMap.put(e.transformerID, e);
    }
    Cursor c = null;

    try {

        // Get list of all items
        Log.i(TAG, "Fetching local entries for merge");
        Uri uri = Transformer.CONTENT_URI; // Get all entries
        c = contentResolver.query(uri, null, null, null, null);
        assert c != null;
        Log.i(TAG, "Found " + c.getCount() + " local entries. Computing merge solution...");
    }

    catch (Exception ex) {

    }
    // Find stale data
    String id;
    String name;
    String location;

    while (c.moveToNext()) {
        syncResult.stats.numEntries++;

        id = c.getColumnName(COLUMN_ID);
        name = c.getString(COLUMN_ENTRY_ID);
        location = c.getString(COLUMN_TITLE);

        Transformer match = entryMap.get(id);
        if (match != null) {
            // Entry exists. Remove from entry map to prevent insert later.
            entryMap.remove(id);
            // Check to see if the entry needs to be updated
            Uri existingUri = Transformer.CONTENT_URI.buildUpon().appendPath(id).build();
            if ((match.trsName != null && !match.trsLocation.equals(name))) {
                // Update existing record
                Log.i(TAG, "Scheduling update: " + existingUri);
                batch.add(ContentProviderOperation.newUpdate(existingUri).withValue(Transformer.KEY_NAME, name)
                        .withValue(Transformer.KEY_LOCATION, location)

                        .build());
                syncResult.stats.numUpdates++;
            } else {
                Log.i(TAG, "No action: " + existingUri);
            }
        } else {
            // Entry doesn't exist. Remove it from the database.
            Uri deleteUri = Transformer.CONTENT_URI.buildUpon().appendPath(id).build();
            Log.i(TAG, "Scheduling delete: " + deleteUri);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
            syncResult.stats.numDeletes++;
        }
    }
    c.close();

    // Add new items
    for (Transformer e : entryMap.values()) {
        Log.i(TAG, "Scheduling insert: entry_id=" + e.transformerID);
        batch.add(ContentProviderOperation.newInsert(Transformer.CONTENT_URI)
                .withValue(Transformer.KEY_TRANSFORMER_ID, e.transformerID)
                .withValue(Transformer.KEY_NAME, e.trsName).withValue(Transformer.KEY_LOCATION, e.trsLocation)
                .withValue(Transformer.KEY_CURRENT_TEMP, e.trsCurrentTemp)
                .withValue(Transformer.KEY_LAST_SERVER_SYNC_DATE, e.lastServerSyncDate)
                .withValue(Transformer.KEY_LAST_UPDATED_TIME, e.lastServerSyncDate)
                .withValue(Transformer.KEY_SYNC_STATUS, 0).withValue(Transformer.KEY_MAKE, e.trsMake)
                .withValue(Transformer.KEY_WINDING_MAKE, e.trsWindingMake)
                .withValue(Transformer.KEY_WINDING_COUNT, e.trsWindingCount)
                .withValue(Transformer.KEY_OIL_LEVEL, e.trsOilLevel)
                .withValue(Transformer.KEY_OPERATING_POWER, e.trsOperatingPower)
                .withValue(Transformer.KEY_TYPE, e.trsType)

                .build());
        syncResult.stats.numInserts++;
    }
    Log.i(TAG, "Merge solution ready. Applying batch update");
    mContentResolver.applyBatch(Transformer.CONTENT_AUTHORITY, batch);
    mContentResolver.notifyChange(Transformer.CONTENT_URI, // URI where data was modified
            null, // No local observer
            false); // IMPORTANT: Do not sync to network
    // This sample doesn't support uploads, but if *your* code does, make sure you set
    // syncToNetwork=false in the line above to prevent duplicate syncs.
}

From source file:com.cordova.photo.CameraLauncher.java

/**
 * Used to find out if we are in a situation where the Camera Intent adds to images
 * to the content store. If we are using a FILE_URI and the number of images in the DB
 * increases by 2 we have a duplicate, when using a DATA_URL the number is 1.
 *
 * @param type FILE_URI or DATA_URL/*from   w ww  .  j  a  v  a2 s.co m*/
 */
private void checkForDuplicateImage(int type) {
    int diff = 1;
    Uri contentStore = whichContentStore();
    Cursor cursor = queryImgDB(contentStore);
    int currentNumOfImages = cursor.getCount();

    if (type == FILE_URI && this.saveToPhotoAlbum) {
        diff = 2;
    }

    // delete the duplicate file if the difference is 2 for file URI or 1 for Data URL
    if ((currentNumOfImages - numPics) == diff) {
        cursor.moveToLast();
        int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID)));
        if (diff == 2) {
            id--;
        }
        Uri uri = Uri.parse(contentStore + "/" + id);
        this.activity.getContentResolver().delete(uri, null, null);
        cursor.close();
    }
}

From source file:com.vyasware.vaani.MainActivity.java

private void doMsg(String noun) {
    System.out.println("msg");

    Cursor cur = null;
    ContentResolver cr = null;//from w w  w  .j  av  a  2  s.c o m

    try {
        cr = getContentResolver();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    try {
        cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    try {
        boolean called = false;
        if (cur.getCount() > 0) {
            while (cur.moveToNext()) {

                String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                // Log.i("Names", name);
                if (Integer.parseInt(
                        cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                    // Query phone here. Covered next
                    Cursor phones = getContentResolver().query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id, null, null);
                    while (phones.moveToNext()) {
                        String phoneNumberX = phones.getString(
                                phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        // Log.i("Number", phoneNumber);
                        boolean a = (name.equalsIgnoreCase(noun));
                        System.out.println(name + "  " + a + "  " + phoneNumberX);

                        if (a)
                            System.out.println(phoneNumberX);

                        if (a) {
                            String b = "sms:";
                            String smsUri = b + phoneNumberX;
                            Intent smsIntent = new Intent(Intent.ACTION_VIEW);
                            smsIntent.setData(Uri.parse(smsUri));
                            called = true;
                            startActivity(smsIntent);
                            tts.speak(noun + "  ? !",
                                    TextToSpeech.QUEUE_FLUSH, null);

                        }

                    }
                    phones.close();

                }

            }

            if (!called)
                tts.speak(noun + "  ?    !",
                        TextToSpeech.QUEUE_FLUSH, null);

        }

    } catch (Exception ex) {
        ex.printStackTrace();

    }
}

From source file:com.vyasware.vaani.MainActivity.java

private void doCall(String noun) {
    System.out.println("call");
    System.out.println(noun);/*from www .j av  a2s. c  o m*/

    Cursor cur = null;
    ContentResolver cr = null;

    try {
        cr = getContentResolver();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    try {
        cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    try {
        boolean called = false;
        if (cur.getCount() > 0) {
            while (cur.moveToNext()) {

                String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                // Log.i("Names", name);
                if (Integer.parseInt(
                        cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                    // Query phone here. Covered next
                    Cursor phones = getContentResolver().query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id, null, null);
                    while (phones.moveToNext()) {
                        String phoneNumberX = phones.getString(
                                phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        // Log.i("Number", phoneNumber);
                        boolean a = (name.equalsIgnoreCase(noun));
                        System.out.println(name + "  " + a + "  " + phoneNumberX);

                        if (a)
                            System.out.println(phoneNumberX);

                        if (a) {
                            String b = "tel:";
                            String phoneCallUri = b + phoneNumberX;
                            Intent phoneCallIntent = new Intent(Intent.ACTION_CALL);
                            phoneCallIntent.setData(Uri.parse(phoneCallUri));
                            called = true;
                            startActivity(phoneCallIntent);

                        }

                    }
                    phones.close();

                }

            }

            if (!called)
                tts.speak(noun + "  ?    !",
                        TextToSpeech.QUEUE_FLUSH, null);

        }

    } catch (Exception ex) {
        ex.printStackTrace();

    }
    // tts.speak(noun + "  ?    !",TextToSpeech.QUEUE_FLUSH, null);
}

From source file:mobisocial.musubi.ui.fragments.FeedViewFragment.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    if (DBG)//from w ww  .  ja  va  2  s  .  c om
        Log.d(TAG, "Query took " + (System.currentTimeMillis() - loaderStartTime) + "ms");
    //the mObjects field is accessed by the ui thread as well
    int previousTotal = -1;
    if (mObjects == null) {
        mObjects = new DbObjCursorAdapter(mActivity, cursor);
        setListAdapter(mObjects);
    } else {
        previousTotal = mObjects.getCount();
        mObjects.changeCursor(cursor);
    }

    mTotal = cursor.getCount();
    if (mResumeToPosition != -1) {
        int position = mTotal - mResumeToPosition;
        getListView().setSelection(position);
        mResumeToPosition = -1;
        mPreviousTotal = previousTotal;
    }
}

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.ja v  a 2 s .com
    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;
}