Example usage for android.database Cursor moveToLast

List of usage examples for android.database Cursor moveToLast

Introduction

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

Prototype

boolean moveToLast();

Source Link

Document

Move the cursor to the last row.

Usage

From source file:com.hybris.mobile.lib.commerce.provider.CatalogProvider.java

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    SQLiteDatabase sqLiteDatabase = mDatabaseHelper.getWritableDatabase();
    String tableName;/*  w  w w . ja va2 s .  co  m*/
    String where;
    String order = "";
    Bundle bundleSyncAdapter = new Bundle();
    String lastPathSegment = uri.getLastPathSegment();

    if (StringUtils.isNotBlank(sortOrder)) {
        order = " ORDER BY " + sortOrder;
    }

    switch (URI_MATCHER.match(uri)) {

    // Getting the content for a group (list of simple data)
    case CatalogContract.Provider.CODE_GROUP_ID:
        tableName = CatalogContract.DataBaseDataSimple.TABLE_NAME;
        where = CatalogContract.DataBaseDataLinkGroup.TABLE_NAME + "."
                + CatalogContract.DataBaseDataLinkGroup.ATT_GROUP_ID + "='" + lastPathSegment + "'";

        // Limit for the query on the sync adapter
        String currentPage = uri.getQueryParameter(CatalogContract.Provider.QUERY_PARAM_CURRENT_PAGE);
        String pageSize = uri.getQueryParameter(CatalogContract.Provider.QUERY_PARAM_PAGE_SIZE);

        // Bundle information for the syncing part
        bundleSyncAdapter.putString(CatalogSyncConstants.SYNC_PARAM_GROUP_ID, lastPathSegment);

        if (StringUtils.isNotBlank(currentPage) && StringUtils.isNotBlank(pageSize)) {
            bundleSyncAdapter.putInt(CatalogSyncConstants.SYNC_PARAM_CURRENT_PAGE,
                    Integer.valueOf(currentPage));
            bundleSyncAdapter.putInt(CatalogSyncConstants.SYNC_PARAM_PAGE_SIZE, Integer.valueOf(pageSize));
        }

        break;

    // Getting a specific data detail
    case CatalogContract.Provider.CODE_DATA_ID:
    case CatalogContract.Provider.CODE_DATA_DETAILS_ID:
        tableName = CatalogContract.DataBaseDataDetails.TABLE_NAME;
        where = CatalogContract.DataBaseDataDetails.TABLE_NAME + "."
                + CatalogContract.DataBaseDataDetails.ATT_DATA_ID + "='" + lastPathSegment + "'";

        // Bundle information for the syncing part
        bundleSyncAdapter.putString(CatalogSyncConstants.SYNC_PARAM_DATA_ID, lastPathSegment);

        // We don't load the variants for a specific data
        bundleSyncAdapter.putBoolean(CatalogSyncConstants.SYNC_PARAM_LOAD_VARIANTS, false);
        break;

    default:
        Log.e(TAG, "URI not recognized" + uri.toString());
        throw new IllegalArgumentException("URI not recognized" + uri.toString());

    }

    // We do the query by joining the data to the group
    Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM " + tableName + " INNER JOIN "
            + CatalogContract.DataBaseDataLinkGroup.TABLE_NAME + " ON " + tableName + "."
            + CatalogContract.DataBaseData.ATT_DATA_ID + "=" + CatalogContract.DataBaseDataLinkGroup.TABLE_NAME
            + "." + CatalogContract.DataBaseDataLinkGroup.ATT_DATA_ID + " WHERE " + where + order, null);

    // Register the cursor to watch the uri for changes
    cursor.setNotificationUri(getContext().getContentResolver(), uri);

    // Existing data
    if (cursor.getCount() > 0) {
        // TODO - For now we check if one the items is out-of-sync and we sync all of them if this is the case
        // Future - Check every out-of-date items and sync them
        cursor.moveToLast();
        int status = cursor.getInt(cursor.getColumnIndex(CatalogContract.DataBaseData.ATT_STATUS));
        cursor.moveToFirst();

        // Data expired, we request a sync
        if (status == CatalogContract.SyncStatus.OUTOFDATE.getValue()) {
            Log.i(TAG, "Data for " + uri.toString() + " is out-of-date, requesting a sync");
            requestSync(bundleSyncAdapter);

            // TODO - the uptodate/outofdate should be done in the sync adapter
            // We up-to-date all the data in case the sync does not return any results (we base our out of sync on the last item of the cursor)
            if (URI_MATCHER.match(uri) == CatalogContract.Provider.CODE_GROUP_ID) {
                updateInternalDataSyncStatus(cursor, tableName, SyncStatus.UPTODATE);
            }
        }
        // Data updated, we invalidate the data
        else {
            Log.i(TAG, "Data for " + uri.toString() + " is up-of-date, invalidating it");
            updateInternalDataSyncStatus(cursor, tableName, SyncStatus.OUTOFDATE);
        }

    }
    // No data found, we request a sync if it's not already up-to-date
    else {
        boolean triggerSyncAdapter;

        switch (URI_MATCHER.match(uri)) {

        // Saving the sync info for the group
        case CatalogContract.Provider.CODE_GROUP_ID:
            triggerSyncAdapter = updateTrackSyncStatus(CatalogContract.Provider.getUriSyncGroup(authority),
                    CatalogContract.DataBaseSyncStatusGroup.ATT_GROUP_ID,
                    CatalogContract.DataBaseSyncStatusGroup.TABLE_NAME, lastPathSegment);

            break;

        // Saving the sync info for the data
        case CatalogContract.Provider.CODE_DATA_ID:
            triggerSyncAdapter = updateTrackSyncStatus(CatalogContract.Provider.getUriData(authority),
                    CatalogContract.DataBaseData.ATT_DATA_ID, CatalogContract.DataBaseDataSimple.TABLE_NAME,
                    lastPathSegment);
            break;

        // Saving the sync info for the data details
        case CatalogContract.Provider.CODE_DATA_DETAILS_ID:
            triggerSyncAdapter = updateTrackSyncStatus(CatalogContract.Provider.getUriDataDetails(authority),
                    CatalogContract.DataBaseData.ATT_DATA_ID, CatalogContract.DataBaseDataDetails.TABLE_NAME,
                    lastPathSegment);
            break;

        default:
            Log.e(TAG, "URI not recognized" + uri.toString());
            throw new IllegalArgumentException("URI not recognized" + uri.toString());

        }

        // Trigger the sync adapter
        if (triggerSyncAdapter) {
            Log.i(TAG, "No data found for " + uri.toString() + " and data out-of-date, requesting a sync");
            requestSync(bundleSyncAdapter);
        } else {
            Log.i(TAG, "No data found for " + uri.toString() + " and data up-to-date");
        }

    }

    return cursor;
}

From source file:nl.sogeti.android.gpstracker.viewer.LoggerMap.java

private void updateTitleBar() {
    ContentResolver resolver = this.getContentResolver();
    Cursor trackCursor = null;
    try {//www .  j  av a  2  s  .  c  o  m
        trackCursor = resolver.query(ContentUris.withAppendedId(Tracks.CONTENT_URI, this.mTrackId),
                new String[] { Tracks.NAME }, null, null, null);
        if (trackCursor != null && trackCursor.moveToLast()) {
            String trackName = trackCursor.getString(0);
            setTitle(trackName);
        }
    } finally {
        if (trackCursor != null) {
            trackCursor.close();
        }
    }
}

From source file:nl.sogeti.android.gpstracker.viewer.LoggerMap.java

private void moveToLastTrack() {
    int trackId = -1;
    Cursor track = null;
    try {/*from   ww  w  .j ava 2 s .  c o  m*/
        ContentResolver resolver = this.getContentResolver();
        track = resolver.query(Tracks.CONTENT_URI, new String[] { "max(" + Tracks._ID + ")", Tracks.NAME, },
                null, null, null);
        if (track != null && track.moveToLast()) {
            trackId = track.getInt(0);
            mAverageSpeed = 0.0;
            moveToTrack(trackId, false);
        }
    } finally {
        if (track != null) {
            track.close();
        }
    }
}

From source file:com.google.android.apps.mytracks.services.TrackRecordingService.java

/**
 * Restart a track.//from w  ww.j a v a  2  s. c  o  m
 * 
 * @param track the track
 */
private void restartTrack(Track track) {
    Log.d(TAG, "Restarting track: " + track.getId());

    TripStatistics tripStatistics = track.getTripStatistics();
    trackTripStatisticsUpdater = new TripStatisticsUpdater(tripStatistics.getStartTime());

    long markerStartTime;
    Waypoint waypoint = myTracksProviderUtils.getLastStatisticsWaypoint(recordingTrackId);
    if (waypoint != null && waypoint.getTripStatistics() != null) {
        markerStartTime = waypoint.getTripStatistics().getStopTime();
    } else {
        markerStartTime = tripStatistics.getStartTime();
    }
    markerTripStatisticsUpdater = new TripStatisticsUpdater(markerStartTime);

    Cursor cursor = null;
    try {
        // TODO: how to handle very long track.
        cursor = myTracksProviderUtils.getTrackPointCursor(recordingTrackId, -1,
                Constants.MAX_LOADED_TRACK_POINTS, true);
        if (cursor == null) {
            Log.e(TAG, "Cursor is null.");
        } else {
            if (cursor.moveToLast()) {
                do {
                    Location location = myTracksProviderUtils.createTrackPoint(cursor);
                    trackTripStatisticsUpdater.addLocation(location, minRecordingDistance);
                    if (location.getTime() > markerStartTime) {
                        markerTripStatisticsUpdater.addLocation(location, minRecordingDistance);
                    }
                } while (cursor.moveToPrevious());
            }
        }
    } catch (RuntimeException e) {
        Log.e(TAG, "RuntimeException", e);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    startRecording(true);
}

From source file:com.g_node.gca.abstracts.AbstractContent.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // TODO Auto-generated method stub

    switch (item.getItemId()) {
    /*//from  w w w.ja va2s. co  m
     * Menu Item for switching next and previous data
     */

    case R.id.star:
        Log.i(gtag, "in Onclick of STAR");

        if (isFav) {
            Log.i(gtag, "in isFAV");
            DatabaseHelper.deleteFromABSTRACT_FAVORITES(value);
            Toast.makeText(getApplicationContext(), "Removed from Favorites", Toast.LENGTH_SHORT).show();
            starG.setIcon(R.drawable.ic_action_important);
            isFav = false;

        } else {
            Log.i(gtag, "in else of isFAV");
            DatabaseHelper.addInABSTRACT_FAVORITES(value);
            Toast.makeText(getApplicationContext(), "Added to Favorites", Toast.LENGTH_SHORT).show();
            starG.setIcon(R.drawable.ic_action_important_selected);
            isFav = true;
        }

        break;

    case R.id.next: {
        String getCurrentRowIDQuery = "SELECT SORTID FROM ABSTRACT_DETAILS WHERE UUID = '" + value + "';";
        Cursor getRowIdCursor = DatabaseHelper.database.rawQuery(getCurrentRowIDQuery, null);
        getRowIdCursor.moveToFirst();
        int currentSORTID = getRowIdCursor.getInt(0);
        Log.i("Garbers", "CurrentSORTID:" + currentSORTID);
        String get_SORTIDS_bigger = "SELECT SORTID,UUID from abstract_details WHERE SORTID>" + currentSORTID
                + " ORDER BY SORTID";
        Cursor getSORTID_BiggerCursor = DatabaseHelper.database.rawQuery(get_SORTIDS_bigger, null);
        if (getSORTID_BiggerCursor.getCount() > 0) {
            getSORTID_BiggerCursor.moveToFirst();
            value = getSORTID_BiggerCursor.getString(getSORTID_BiggerCursor.getColumnIndexOrThrow("UUID"));
            Log.i("Garbers", "NextSORTID:" + getSORTID_BiggerCursor.getInt((0)));
            Log.i("Garbers", "NextUUID:" + getSORTID_BiggerCursor.getString((1)));
            mAdapter.setValue(value);
            mAdapter.notifyDataSetChanged();
            invalidateOptionsMenu();

        } else {
            Toast.makeText(getApplicationContext(), "No more Abstracts Left", Toast.LENGTH_SHORT).show();
        }

        break;
    }

    case R.id.Previous: {
        String getCurrentRowIDQuery = "SELECT SORTID FROM ABSTRACT_DETAILS WHERE UUID = '" + value + "';";
        Cursor getRowIdCursor = DatabaseHelper.database.rawQuery(getCurrentRowIDQuery, null);
        getRowIdCursor.moveToFirst();
        int currentSORTID = getRowIdCursor.getInt(0);
        Log.i("Garbers", "CurrentSORTID:" + currentSORTID);
        String get_SORTIDS_bigger = "SELECT SORTID,UUID from abstract_details WHERE SORTID<" + currentSORTID
                + " ORDER BY SORTID";
        Cursor getSORTID_BiggerCursor = DatabaseHelper.database.rawQuery(get_SORTIDS_bigger, null);
        if (getSORTID_BiggerCursor.getCount() > 0) {
            getSORTID_BiggerCursor.moveToLast();
            value = getSORTID_BiggerCursor.getString(getSORTID_BiggerCursor.getColumnIndexOrThrow("UUID"));
            Log.i("Garbers", "NextSORTID:" + getSORTID_BiggerCursor.getInt((0)));
            Log.i("Garbers", "NextUUID:" + getSORTID_BiggerCursor.getString((1)));
            mAdapter.setValue(value);
            mAdapter.notifyDataSetChanged();
            invalidateOptionsMenu();

        } else {
            Toast.makeText(getApplicationContext(), "No more Abstracts Left", Toast.LENGTH_SHORT).show();
        }

        break;
    }

    default:

        break;
    }

    return super.onOptionsItemSelected(item);

}

From source file:nl.sogeti.android.gpstracker.viewer.LoggerMap.java

private void createListeners() {
    mFab.setOnClickListener(new View.OnClickListener() {
        @Override//from   w  w  w.  j a  va 2s  .  com
        public void onClick(View v) {
            Intent intent = new Intent(LoggerMap.this, ControlTracking.class);
            startActivityForResult(intent, MENU_TRACKING);
        }
    });
    /*******************************************************
     * 8 Runnable listener actions
     */
    speedCalculator = new Runnable() {
        @Override
        public void run() {
            double avgspeed = 0.0;
            ContentResolver resolver = LoggerMap.this.getContentResolver();
            Cursor waypointsCursor = null;
            try {
                waypointsCursor = resolver.query(
                        Uri.withAppendedPath(Tracks.CONTENT_URI, LoggerMap.this.mTrackId + "/waypoints"),
                        new String[] { "avg(" + Waypoints.SPEED + ")", "max(" + Waypoints.SPEED + ")" }, null,
                        null, null);

                if (waypointsCursor != null && waypointsCursor.moveToLast()) {
                    double average = waypointsCursor.getDouble(0);
                    double maxBasedAverage = waypointsCursor.getDouble(1) / 2;
                    avgspeed = Math.min(average, maxBasedAverage);
                }
                if (avgspeed < 2) {
                    avgspeed = 5.55d / 2;
                }
            } finally {
                if (waypointsCursor != null) {
                    waypointsCursor.close();
                }
            }
            mAverageSpeed = avgspeed;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    updateSpeedColoring();
                }
            });
        }
    };
    mServiceConnected = new Runnable() {
        @Override
        public void run() {
            updateBlankingBehavior();
        }
    };
    /*******************************************************
     * 8 Various dialog listeners
     */
    mNoteSelectDialogListener = new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            Uri selected = (Uri) mGallery.getSelectedItem();
            SegmentOverlay.handleMedia(LoggerMap.this, selected);
        }
    };
    mGroupCheckedChangeListener = new android.widget.RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {
            case R.id.layer_google_satellite:
                setSatelliteOverlay(true);
                break;
            case R.id.layer_google_regular:
                setSatelliteOverlay(false);
                break;
            default:
                break;
            }
        }
    };
    mCheckedChangeListener = new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            int checkedId;
            checkedId = buttonView.getId();
            switch (checkedId) {
            case R.id.layer_traffic:
                setTrafficOverlay(isChecked);
                break;
            case R.id.layer_speed:
                setSpeedOverlay(isChecked);
                break;
            case R.id.layer_altitude:
                setAltitudeOverlay(isChecked);
                break;
            case R.id.layer_distance:
                setDistanceOverlay(isChecked);
                break;
            case R.id.layer_compass:
                setCompassOverlay(isChecked);
                break;
            case R.id.layer_location:
                setLocationOverlay(isChecked);
                break;
            default:
                break;
            }
        }
    };
    mNoTrackDialogListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            //            Log.d( TAG, "mNoTrackDialogListener" + which);
            Intent tracklistIntent = new Intent(LoggerMap.this, TrackList.class);
            tracklistIntent.putExtra(Tracks._ID, LoggerMap.this.mTrackId);
            startActivityForResult(tracklistIntent, MENU_TRACKLIST);
        }
    };
    /**
     * Listeners to events outside this mapview
     */
    mSharedPreferenceChangeListener = new OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            if (key.equals(Constants.TRACKCOLORING)) {
                mAverageSpeed = 0.0;
                updateSpeedColoring();
            } else if (key.equals(Constants.DISABLEBLANKING) || key.equals(Constants.DISABLEDIMMING)) {
                updateBlankingBehavior();
            } else if (key.equals(Constants.SPEED)) {
                updateSpeedDisplayVisibility();
            } else if (key.equals(Constants.ALTITUDE)) {
                updateAltitudeDisplayVisibility();
            } else if (key.equals(Constants.DISTANCE)) {
                updateDistanceDisplayVisibility();
            } else if (key.equals(Constants.COMPASS)) {
                updateCompassDisplayVisibility();
            } else if (key.equals(Constants.TRAFFIC)) {
                updateGoogleOverlays();
            } else if (key.equals(Constants.SATELLITE)) {
                updateGoogleOverlays();
            } else if (key.equals(Constants.LOCATION)) {
                updateLocationDisplayVisibility();
            }
        }
    };
    mTrackMediasObserver = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfUpdate) {
            if (!selfUpdate) {
                if (mLastSegmentOverlay != null) {
                    mLastSegmentOverlay.calculateMedia();
                    mMapView.postInvalidate();
                }
            } else {
                Log.w(this, "mTrackMediasObserver skipping change on " + mLastSegment);
            }
        }
    };
    mTrackSegmentsObserver = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfUpdate) {
            if (!selfUpdate) {
                LoggerMap.this.updateDataOverlays();
            } else {
                Log.w(this, "mTrackSegmentsObserver skipping change on " + mLastSegment);
            }
        }
    };
    mSegmentWaypointsObserver = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfUpdate) {
            if (!selfUpdate) {
                LoggerMap.this.updateTrackNumbers();
                if (mLastSegmentOverlay != null) {
                    moveActiveViewWindow();
                } else {
                    Log.e(this, "Error the last segment changed but it is not on screen! " + mLastSegment);
                }
            } else {
                Log.w(this, "mSegmentWaypointsObserver skipping change on " + mLastSegment);
            }
        }
    };
    mUnitsChangeListener = new UnitsI18n.UnitsChangeListener() {
        @Override
        public void onUnitsChange() {
            mAverageSpeed = 0.0;
            updateTrackNumbers();
            updateSpeedColoring();
        }
    };
}

From source file:org.digitalcampus.oppia.application.DbHelper.java

public long isClientSyncedWithServer(long clientServerId, String username) {
    String sql = "SELECT * FROM  " + CLIENT_TABLE + " WHERE " + CLIENT_C_HEALTHWORKER + " = ? AND "
            + CLIENT_C_SERVER_ID + " = ? ;";

    Cursor c = db.rawQuery(sql, new String[] { username, Long.toString(clientServerId) });

    if (c.getCount() == 0) {
        c.close();/*from  w ww  . j a va 2s. c om*/
        return -1;
    } else {
        c.moveToLast();
        long userId = c.getInt(c.getColumnIndex(CLIENT_C_ID));
        c.close();
        return userId;
    }
}

From source file:nl.sogeti.android.gpstracker.viewer.LoggerMap.java

/**
 * Retrieve the last point of the current track
 *//*from  www . j av a  2  s.  c  o m*/
private GeoPoint getLastTrackPoint() {
    Cursor waypoint = null;
    GeoPoint lastPoint = null;
    // First try the service which might have a cached version
    Location lastLoc = mLoggerServiceManager.getLastWaypoint();
    if (lastLoc != null) {
        int microLatitude = (int) (lastLoc.getLatitude() * 1E6d);
        int microLongitude = (int) (lastLoc.getLongitude() * 1E6d);
        lastPoint = new GeoPoint(microLatitude, microLongitude);
    }

    // If nothing yet, try the content resolver and query the track
    if (lastPoint == null || lastPoint.getLatitudeE6() == 0 || lastPoint.getLongitudeE6() == 0) {
        try {
            ContentResolver resolver = this.getContentResolver();
            waypoint = resolver.query(Uri.withAppendedPath(Tracks.CONTENT_URI, mTrackId + "/waypoints"),
                    new String[] { Waypoints.LATITUDE, Waypoints.LONGITUDE,
                            "max(" + Waypoints.TABLE + "." + Waypoints._ID + ")" },
                    null, null, null);
            if (waypoint != null && waypoint.moveToLast()) {
                int microLatitude = (int) (waypoint.getDouble(0) * 1E6d);
                int microLongitude = (int) (waypoint.getDouble(1) * 1E6d);
                lastPoint = new GeoPoint(microLatitude, microLongitude);
            }
        } finally {
            if (waypoint != null) {
                waypoint.close();
            }
        }
    }

    // If nothing yet, try the last generally known location
    if (lastPoint == null || lastPoint.getLatitudeE6() == 0 || lastPoint.getLongitudeE6() == 0) {
        lastPoint = getLastKnowGeopointLocation();
    }
    return lastPoint;
}

From source file:org.mozilla.mozstumbler.service.sync.UploadReports.java

private BatchRequestStats getRequestBody(Cursor cursor) {
    int wifiCount = 0;
    int cellCount = 0;
    JSONArray items = new JSONArray();

    int columnId = cursor.getColumnIndex(DatabaseContract.Reports._ID);
    int columnTime = cursor.getColumnIndex(DatabaseContract.Reports.TIME);
    int columnLat = cursor.getColumnIndex(DatabaseContract.Reports.LAT);
    int columnLon = cursor.getColumnIndex(DatabaseContract.Reports.LON);
    int columnAltitude = cursor.getColumnIndex(DatabaseContract.Reports.ALTITUDE);
    int columnAccuracy = cursor.getColumnIndex(DatabaseContract.Reports.ACCURACY);
    int columnRadio = cursor.getColumnIndex(DatabaseContract.Reports.RADIO);
    int columnCell = cursor.getColumnIndex(DatabaseContract.Reports.CELL);
    int columnWifi = cursor.getColumnIndex(DatabaseContract.Reports.WIFI);
    int columnCellCount = cursor.getColumnIndex(DatabaseContract.Reports.CELL_COUNT);
    int columnWifiCount = cursor.getColumnIndex(DatabaseContract.Reports.WIFI_COUNT);

    cursor.moveToPosition(-1);//from w  ww.j  a va2s.  co m
    try {
        while (cursor.moveToNext()) {
            JSONObject item = new JSONObject();
            item.put("time", DateTimeUtils.formatTime(DateTimeUtils.removeDay(cursor.getLong(columnTime))));
            item.put("lat", cursor.getDouble(columnLat));
            item.put("lon", cursor.getDouble(columnLon));
            if (!cursor.isNull(columnAltitude)) {
                item.put("altitude", cursor.getInt(columnAltitude));
            }
            if (!cursor.isNull(columnAccuracy)) {
                item.put("accuracy", cursor.getInt(columnAccuracy));
            }
            item.put("radio", cursor.getString(columnRadio));
            item.put("cell", new JSONArray(cursor.getString(columnCell)));
            item.put("wifi", new JSONArray(cursor.getString(columnWifi)));
            items.put(item);

            cellCount += cursor.getInt(columnCellCount);
            wifiCount += cursor.getInt(columnWifiCount);
        }
    } catch (JSONException jsonex) {
        Log.e(LOGTAG, "JSONException", jsonex);
    }

    if (items.length() == 0) {
        return null;
    }

    long minId, maxId;
    cursor.moveToFirst();
    minId = cursor.getLong(columnId);
    cursor.moveToLast();
    maxId = cursor.getLong(columnId);

    JSONObject wrapper = new JSONObject(Collections.singletonMap("items", items));
    return new BatchRequestStats(wrapper.toString().getBytes(), wifiCount, cellCount, items.length(), minId,
            maxId);
}

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

@Override
public void onLoadFinished(Loader<Cursor> loader, final Cursor data) {
    mLoading = false;//from   w  w  w  .j a  va2s  .  c o m

    /*
     * Update list view.
     */
    mFileAdapter.changeCursor(data);

    mViewGroupFiles.setVisibility(View.VISIBLE);
    mViewLoadingHandler.removeCallbacksAndMessages(null);
    mViewLoading.setVisibility(View.GONE);
    getActivity().supportInvalidateOptionsMenu();

    if (data == null) {
        showFooterView(true, getString(R.string.afc_msg_failed_please_try_again), true);
        return;
    }

    data.moveToLast();
    final Uri uriInfo = BaseFileProviderUtils.getUri(data);
    final Uri selectedFile = (Uri) getArguments().getParcelable(FileChooserActivity.EXTRA_SELECT_FILE);
    if (selectedFile != null)
        getArguments().remove(FileChooserActivity.EXTRA_SELECT_FILE);

    /*
     * Footer.
     */

    if (selectedFile != null && mIsSaveDialog) {
        new LoadingDialog<Void, Void, String>(getActivity(), false) {

            @Override
            protected String doInBackground(Void... params) {
                if (BaseFileProviderUtils.isFile(getActivity(), selectedFile))
                    return BaseFileProviderUtils.getFileName(getActivity(), selectedFile);
                return null;
            }// doInBackground()

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

                if (!TextUtils.isEmpty(result))
                    mTextSaveas.setText(result);
            }// onPostExecute()

        }.execute();
    } // if

    boolean hasMoreFiles = ProviderUtils.getBooleanQueryParam(uriInfo, BaseFile.PARAM_HAS_MORE_FILES);
    showFooterView(hasMoreFiles || mFileAdapter.isEmpty(),
            hasMoreFiles ? getString(R.string.afc_pmsg_max_file_count_allowed, mMaxFileCount)
                    : getString(R.string.afc_msg_empty),
            mFileAdapter.isEmpty());

    if (mNewLoader || selectedFile != null)
        createFileSelector();

    mNewLoader = false;
}