Example usage for android.database Cursor moveToNext

List of usage examples for android.database Cursor moveToNext

Introduction

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

Prototype

boolean moveToNext();

Source Link

Document

Move the cursor to the next row.

Usage

From source file:com.amazonaws.mobileconnectors.pinpoint.internal.event.EventRecorder.java

void processEvents() {
    final long start = System.currentTimeMillis();

    Cursor cursor = null;

    try {/*from   w  w  w.  ja v  a  2  s  .c  o m*/
        cursor = dbUtil.queryAllEvents();

        final List<Integer> idsToDeletes = new ArrayList<Integer>();
        final List<Integer> sizeToDeletes = new ArrayList<Integer>();
        boolean successful;
        int submissions = 0;
        final long maxSubmissionsAllowed = pinpointContext.getConfiguration()
                .optInt(KEY_MAX_SUBMISSIONS_ALLOWED, DEFAULT_MAX_SUBMISSIONS_ALLOWED);

        while (cursor.moveToNext()) {
            final List<Integer> batchIdsToDeletes = new ArrayList<Integer>();
            final List<Integer> batchSizeToDeletes = new ArrayList<Integer>();
            successful = submitEvents(this.getBatchOfEvents(cursor, batchIdsToDeletes, batchSizeToDeletes));
            if (successful) {
                idsToDeletes.addAll(batchIdsToDeletes);
                sizeToDeletes.addAll(batchSizeToDeletes);
                submissions++;
            }
            if (submissions >= maxSubmissionsAllowed) {
                break;
            }
        }

        if (sizeToDeletes.size() > 0) {
            for (int i = 0; i < sizeToDeletes.size(); i++) {
                try {
                    dbUtil.deleteEvent(idsToDeletes.get(i), sizeToDeletes.get(i));
                } catch (final Exception exc) {
                    log.error("Failed to delete event: " + idsToDeletes.get(i), exc);
                }
            }
        }

        log.info(String.format("Time of attemptDelivery: %d", System.currentTimeMillis() - start));
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:com.amazonaws.mobileconnectors.s3.transferutility.TransferUtility.java

/**
 * Gets a list of TransferObserver instances which are observing records
 * with the given type./*from   w  w  w.  j  a v a  2  s .c o  m*/
 *
 * @param type The type of the transfer "any".
 * @return A list of TransferObserver instances.
 */
public List<TransferObserver> getTransfersWithType(TransferType type) {
    final List<TransferObserver> transferObservers = new ArrayList<TransferObserver>();
    Cursor c = null;
    try {
        c = dbUtil.queryAllTransfersWithType(type);
        while (c.moveToNext()) {
            final int id = c.getInt(c.getColumnIndexOrThrow(TransferTable.COLUMN_ID));
            final TransferObserver to = new TransferObserver(id, dbUtil);
            to.updateFromDB(c);
            transferObservers.add(to);
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }
    return transferObservers;
}

From source file:com.digipom.manteresting.android.processor.json.NailsJsonProcessor.java

@Override
public ArrayList<ContentProviderOperation> parse(JSONObject response, Meta meta) throws JSONException {
    final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
    final TreeSet<Integer> nailIds = new TreeSet<Integer>();
    final Cursor nails = resolver.query(ManterestingContract.Nails.CONTENT_URI, new String[] { Nails.NAIL_ID },
            null, null, Nails.NAIL_ID + " DESC");
    int greatestOfExisting = Integer.MIN_VALUE;

    if (nails != null && !nails.isClosed()) {
        try {/*from w w w. j ava 2 s. c  om*/
            nails.moveToFirst();

            final int idColumn = nails.getColumnIndex(Nails.NAIL_ID);

            while (!nails.isAfterLast()) {
                final int nailId = nails.getInt(idColumn);
                nailIds.add(nailId);
                greatestOfExisting = nailId > greatestOfExisting ? nailId : greatestOfExisting;
                nails.moveToNext();
            }
        } finally {
            if (nails != null) {
                nails.close();
            }
        }
    }

    final JSONArray objects = response.getJSONArray("objects");
    int smallestOfNew = Integer.MAX_VALUE;

    for (int i = 0; i < objects.length(); i++) {
        final JSONObject nailObject = objects.getJSONObject(i);

        final boolean isPrivate = nailObject.getJSONObject("workbench").getBoolean("private");

        if (!isPrivate) {
            final ContentProviderOperation.Builder builder = ContentProviderOperation
                    .newInsert(Nails.CONTENT_URI);
            final int nailId = nailObject.getInt("id");
            smallestOfNew = nailId < smallestOfNew ? nailId : smallestOfNew;

            builder.withValue(Nails.NAIL_ID, nailId);
            builder.withValue(Nails.NAIL_JSON, nailObject.toString());

            batch.add(builder.build());
            nailIds.add(nailId);
        }
    }

    // If more than LIMIT were fetched, and this was the initial fetch, then
    // we flush everything in the DB before adding the new nails (as
    // otherwise we would introduce a gap).
    if (meta.nextOffset == meta.nextLimit // For initial fetch
            && smallestOfNew > greatestOfExisting) {
        if (LoggerConfig.canLog(Log.DEBUG)) {
            Log.d(TAG, "Flushing all existing nails on initial fetch, so as to avoid a gap.");
        }

        resolver.delete(Nails.CONTENT_URI, null, null);
    } else {
        // If more than 500 nails, find the 500th biggest and delete those
        // after it.
        if (nailIds.size() > MAX_COUNT) {
            Iterator<Integer> it = nailIds.descendingIterator();

            for (int i = 0; i < MAX_COUNT; i++) {
                it.next();
            }

            final Integer toDelete = it.next();

            if (LoggerConfig.canLog(Log.DEBUG)) {
                Log.d(TAG, "deleting from nails where NAIL_ID is less than or equal to " + toDelete);
            }

            SelectionBuilder selectionBuilder = new SelectionBuilder();
            selectionBuilder.where(ManterestingContract.Nails.NAIL_ID + " <= ?",
                    new String[] { String.valueOf(toDelete) });
            resolver.delete(ManterestingContract.Nails.CONTENT_URI, selectionBuilder.getSelection(),
                    selectionBuilder.getSelectionArgs());
        }
    }

    return batch;
}

From source file:org.mythtv.service.dvr.v27.RecordedHelperV27.java

private int load(final Context context, final LocationProfile locationProfile, final Program[] programs)
        throws RemoteException, OperationApplicationException {
    Log.d(TAG, "load : enter");

    if (null == context)
        throw new RuntimeException("RecordedHelperV27 is not initialized");

    processProgramGroups(context, locationProfile, programs);

    String tag = UUID.randomUUID().toString();
    int processed = -1;
    int count = 0;

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

    boolean inError;

    List<Integer> channelsChecked = new ArrayList<Integer>();

    for (Program program : programs) {

        if (null != program.getRecording() && "livetv".equalsIgnoreCase(program.getRecording().getRecGroup())
                && !"deleted".equalsIgnoreCase(program.getRecording().getRecGroup())) {
            Log.w(TAG,/*from  ww w  . j  a  v  a 2 s .  c  o  m*/
                    "load : program has no recording or program is in livetv or deleted recording groups:"
                            + program.getTitle() + ":" + program.getSubTitle() + ":"
                            + program.getChannel().getChanId() + ":" + program.getStartTime() + ":"
                            + program.getHostName() + " ("
                            + (null == program.getRecording() ? "No Recording"
                                    : ("livetv".equalsIgnoreCase(program.getRecording().getRecGroup())
                                            ? "LiveTv"
                                            : "Deleted"))
                            + ")");

            continue;
        }

        if (null == program.getStartTime() || null == program.getEndTime()) {
            Log.w(TAG, "load : null starttime and or endtime");

            inError = true;
        } else {
            inError = false;
        }

        ProgramHelperV27.getInstance().processProgram(context, locationProfile,
                ProgramConstants.CONTENT_URI_RECORDED, ProgramConstants.TABLE_NAME_RECORDED, ops, program, tag);
        count++;

        if (null != program.getChannel()) {

            if (!channelsChecked.contains(program.getChannel().getChanId())) {

                if (null == mChannelDaoHelper.findByChannelId(context, locationProfile,
                        Long.parseLong(String.valueOf(program.getChannel().getChanId())))) {

                    ChannelHelperV27.getInstance().processChannel(context, locationProfile, ops,
                            program.getChannel());
                    count++;

                }

                channelsChecked.add(program.getChannel().getChanId());

            }

        }

        if (!inError && null != program.getRecording()) {

            if (program.getRecording().getRecordId() > 0) {

                RecordingHelperV27.getInstance().processRecording(context, locationProfile, ops,
                        RecordingConstants.ContentDetails.RECORDED, program, tag);
                count++;

            }

        }

        if (count > BATCH_COUNT_LIMIT) {
            Log.i(TAG, "load : applying batch for '" + count + "' transactions");

            processBatch(context, ops, processed, count);

            count = 0;

        }

    }

    if (!ops.isEmpty()) {
        Log.i(TAG, "load : applying final batch for '" + count + "' transactions");

        processBatch(context, ops, processed, count);
    }

    ProgramHelperV27.getInstance().findAllPrograms(context, locationProfile,
            ProgramConstants.CONTENT_URI_RECORDED, ProgramConstants.TABLE_NAME_RECORDED);

    Log.v(TAG, "load : remove deleted recording live streams");
    String[] deletedProjection = new String[] { ProgramConstants.FIELD_CHANNEL_ID,
            ProgramConstants.FIELD_START_TIME, ProgramConstants.FIELD_TITLE, ProgramConstants.FIELD_SUB_TITLE,
            ProgramConstants.FIELD_LAST_MODIFIED_DATE };
    String deletedSelection = "not " + ProgramConstants.TABLE_NAME_RECORDED + "."
            + ProgramConstants.FIELD_LAST_MODIFIED_TAG + " = ?";
    String[] deletedSelectionArgs = new String[] { tag };

    deletedSelection = appendLocationHostname(context, locationProfile, deletedSelection,
            ProgramConstants.TABLE_NAME_RECORDED);

    int deleteCount = 0;
    Cursor deletedCursor = context.getContentResolver().query(ProgramConstants.CONTENT_URI_RECORDED,
            deletedProjection, deletedSelection, deletedSelectionArgs, null);
    while (deletedCursor.moveToNext()) {

        long channelId = deletedCursor.getLong(deletedCursor.getColumnIndex(ProgramConstants.FIELD_CHANNEL_ID));
        long startTime = deletedCursor.getLong(deletedCursor.getColumnIndex(ProgramConstants.FIELD_START_TIME));

        // Delete any live stream details
        String liveStreamSelection = LiveStreamConstants.FIELD_CHAN_ID + " = ? AND "
                + LiveStreamConstants.FIELD_START_TIME + " = ?";
        String[] liveStreamSelectionArgs = new String[] { String.valueOf(channelId),
                String.valueOf(startTime) };

        liveStreamSelection = appendLocationHostname(context, locationProfile, liveStreamSelection,
                LiveStreamConstants.TABLE_NAME);

        Cursor liveStreamCursor = context.getContentResolver().query(LiveStreamConstants.CONTENT_URI, null,
                liveStreamSelection, liveStreamSelectionArgs, null);
        if (liveStreamCursor.moveToFirst()) {
            Log.v(TAG, "load : remove live stream");

            int liveStreamId = liveStreamCursor.getInt(liveStreamCursor
                    .getColumnIndex(LiveStreamConstants.TABLE_NAME + "." + LiveStreamConstants.FIELD_ID));

            RemoveStreamTask removeStreamTask = new RemoveStreamTask(context, locationProfile);
            removeStreamTask.execute(liveStreamId);
        }
        liveStreamCursor.close();

        deleteCount++;
    }
    deletedCursor.close();
    Log.v(TAG, "load : queued deleted programs - " + deleteCount);

    ProgramHelperV27.getInstance().deletePrograms(context, locationProfile,
            ProgramConstants.CONTENT_URI_RECORDED, ProgramConstants.TABLE_NAME_RECORDED, tag);
    //      RecordingHelperV27.getInstance().deleteRecordings( context, locationProfile, ops, RecordingConstants.ContentDetails.RECORDED, lastModified );

    if (!ops.isEmpty()) {
        Log.i(TAG, "load : applying delete batch for transactions");

        processBatch(context, ops, processed, count);
    }

    //      Log.v( TAG, "load : exit" );
    return processed;
}

From source file:com.sweetiepiggy.raspberrybusmalaysia.SubmitTripActivity.java

private void update_operator_autocomplete(int id) {
    ArrayAdapter<String> operators = new ArrayAdapter<String>(this,
            android.R.layout.simple_dropdown_item_1line);
    Cursor c = mDbHelper.fetch_operators();
    if (c.moveToFirst())
        do {//from  www  .  java 2s.  c o m
            operators.add(c.getString(c.getColumnIndex(DbAdapter.KEY_OPERATOR)));
        } while (c.moveToNext());
    c.close();
    AutoCompleteTextView operators_entry = (AutoCompleteTextView) findViewById(id);
    operators_entry.setThreshold(1);
    operators_entry.setAdapter(operators);
}

From source file:org.noorganization.instalistsynch.controller.synch.impl.IngredientSynch.java

@Override
public void indexLocal(int _groupId, Date _lastIndexTime) {
    String lastIndexTime = ISO8601Utils.format(_lastIndexTime, false, TimeZone.getTimeZone("GMT+0000"));//.concat("+0000");
    boolean isLocal = false;
    GroupAuth groupAuth = mGroupAuthDbController.getLocalGroup();
    if (groupAuth != null) {
        isLocal = groupAuth.getGroupId() == _groupId;
    }//from  w ww  . j a  v a  2 s .  co m
    Cursor logCursor = mClientLogDbController.getLogsSince(lastIndexTime, mModelType);
    if (logCursor.getCount() == 0) {
        logCursor.close();
        return;
    }

    try {
        while (logCursor.moveToNext()) {
            // fetch the action type
            int actionId = logCursor.getInt(logCursor.getColumnIndex(LogInfo.COLUMN.ACTION));
            eActionType actionType = eActionType.getTypeById(actionId);

            List<ModelMapping> modelMappingList = mIngredientModelMapping.get(
                    ModelMapping.COLUMN.GROUP_ID + " = ? AND " + ModelMapping.COLUMN.CLIENT_SIDE_UUID
                            + " LIKE ?",
                    new String[] { String.valueOf(_groupId),
                            logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ITEM_UUID)) });
            ModelMapping modelMapping = modelMappingList.size() == 0 ? null : modelMappingList.get(0);

            switch (actionType) {
            case INSERT:
                // skip insertion because this should be decided by the user if the non local groups should have access to the category
                // and also skip if a mapping for this case already exists!
                if (!isLocal || modelMapping != null) {
                    continue;
                }

                String clientUuid = logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ITEM_UUID));
                Date clientDate = ISO8601Utils.parse(
                        logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE)),
                        new ParsePosition(0));
                modelMapping = new ModelMapping(null, groupAuth.getGroupId(), null, clientUuid,
                        new Date(Constants.INITIAL_DATE), clientDate, false);
                mIngredientModelMapping.insert(modelMapping);
                break;
            case UPDATE:
                if (modelMapping == null) {
                    Log.i(TAG, "indexLocal: the model is null but shouldn't be");
                    continue;
                }
                String timeString = logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE));
                clientDate = ISO8601Utils.parse(timeString, new ParsePosition(0));
                modelMapping.setLastClientChange(clientDate);
                mIngredientModelMapping.update(modelMapping);
                break;
            case DELETE:
                if (modelMapping == null) {
                    Log.i(TAG, "indexLocal: the model is null but shouldn't be");
                    continue;
                }
                modelMapping.setDeleted(true);
                timeString = logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE));
                clientDate = ISO8601Utils.parse(timeString, new ParsePosition(0));
                modelMapping.setLastClientChange(clientDate);
                mIngredientModelMapping.update(modelMapping);
                break;
            default:
            }

        }
    } catch (Exception e) {
        logCursor.close();
    }
}

From source file:com.openerp.addons.messages.MessageComposeActivty.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_message_compose);
    scope = new AppScope((MainActivity) MainActivity.context);
    getActionBar().setHomeButtonEnabled(true);
    getActionBar().setDisplayHomeAsUpEnabled(true);
    Intent replyIntent = getIntent();/*from ww w .j a v a  2s.c  om*/
    receipients_view = (TagsView) findViewById(R.id.receipients_view);
    partner_adapter = new ReceipientsTagsCustomAdapter(this, R.layout.message_receipient_item_layout, parters);
    receipients_view.setAdapter(partner_adapter);
    /* tags component */
    if (replyIntent.hasExtra("send_reply")) {
        is_reply = true;
    } else {
        parters.addAll(getAllPartners());
    }
    receipients_view.setPrefix("To: ");
    receipients_view.allowDuplicates(false);
    receipients_view.setTokenListener(this);
    if (is_reply) {
        message_id = replyIntent.getExtras().getInt("message_id");
        MessageDBHelper msgDb = new MessageDBHelper(this);
        parent_row = ((List<HashMap<String, Object>>) msgDb.search(msgDb,

                new String[] { "id = ?" }, new String[] { message_id + "" }).get("records")).get(0);
        getActionBar().setTitle("?");
        EditText edtSubject = (EditText) findViewById(R.id.edtMessageSubject);
        edtSubject.setText("?: " + parent_row.get("subject").toString());
        JSONArray partner_ids = new JSONArray();
        try {

            List<TagsItems> partners = getPartnersOfMessage(message_id + "");
            for (TagsItems item : partners) {
                selectedPartners.put("key_" + item.getId(), item);
                partner_ids.put(item.getId());
                receipients_view.addObject(item);
                findViewById(R.id.edtMessageBody).requestFocus();
            }
            parent_row.put("partners", partner_ids);
        } catch (Exception e) {
            e.printStackTrace();
        }

    } else {
        getActionBar().setTitle("??");
        if (getIntent().getData() != null) {
            Cursor cursor = managedQuery(getIntent().getData(), null, null, null, null);
            if (cursor.moveToNext()) {
                int partner_id = cursor.getInt(cursor.getColumnIndex("data2"));
                List<TagsItems> partners = getPartnersByIds(Arrays.asList(new Integer[] { partner_id }));
                for (TagsItems item : partners) {
                    selectedPartners.put("key_" + item.getId(), item);
                    receipients_view.addObject(item);
                    findViewById(R.id.edtMessageSubject).requestFocus();
                }

            }
        }
    }
    lstAttachments = (ListView) findViewById(R.id.lstAttachments);
    String[] from = new String[] { "name" };
    int[] to = new int[] { R.id.txvFileName };
    lstAttachmentAdapter = new OEListViewAdapter(MainActivity.context,
            R.layout.message_attachment_listview_item, attachments, from, to, null);
    lstAttachments.setAdapter(lstAttachmentAdapter);
    lstAttachmentAdapter.setItemClickListener(R.id.imgBtnRemoveAttachment, new ControlClickEventListener() {

        @Override
        public OEListViewRows controlClicked(int position, OEListViewRows row, View view) {
            file_uris.remove(position);
            attachments.remove(position);
            lstAttachmentAdapter.refresh(attachments);
            return null;
        }
    });

    Res_PartnerDBHelper partners = new Res_PartnerDBHelper(this);
    HashMap<String, Object> data = partners.search(partners);
    if ((Integer) data.get("total") > 0) {
        for (HashMap<String, Object> row : (List<HashMap<String, Object>>) data.get("records")) {
            OEListViewRows newRow = new OEListViewRows(Integer.parseInt(row.get("id").toString()), row);
            partners_list.add(newRow);
        }
    }
    handleIntentFilter(getIntent());
}

From source file:com.nonninz.robomodel.RoboManager.java

public long[] getSelectedModelIds(String selection, String[] selectionArgs, String groupBy, String having,
        String orderBy) {/*from   ww  w. jav a  2s .  c  om*/
    final SQLiteDatabase db = mDatabaseManager.openOrCreateDatabase(getDatabaseName());

    final String columns[] = new String[] { BaseColumns._ID };
    Cursor query;

    /*
     * Try the query. If the Table doesn't exist, fix the DB and re-run the query.
     */
    try {
        query = db.query(getTableName(), columns, selection, selectionArgs, groupBy, having, orderBy);
    } catch (final SQLiteException e) {
        prepareTable(db);
        query = db.query(getTableName(), columns, selection, selectionArgs, groupBy, having, orderBy);
    }

    final int columnIndex = query.getColumnIndex(BaseColumns._ID);
    final long result[] = new long[query.getCount()];
    for (query.moveToFirst(); !query.isAfterLast(); query.moveToNext()) {
        result[query.getPosition()] = query.getLong(columnIndex);
    }

    return result;
}

From source file:com.example.android.ennis.barrett.popularmovies.asynchronous.TMDbSyncUtil.java

/**
 * Parses and stores the JSON data in the TMDbContentProvider
 * @param dataJSON The JSON data from server
 * @param type Flag for the try of movie to fetch.  Should match flag used in fetchMovies
 * @throws JSONException//from  w w w .java2  s  .c  o m
 */
private static int[] storeJsonMovies(String dataJSON, int type, Context context) throws JSONException {
    //TODO use ContentProviderClient instead of ContentResolver
    try {
        JSONObject moviesJSON = new JSONObject(dataJSON);
        JSONArray results = moviesJSON.getJSONArray("results");
        final int resultLength = results.length();
        ContentValues[] contentValues = new ContentValues[resultLength];
        int[] ids = new int[resultLength];
        int isPopular;
        int isTopRated;
        int isFavorite;

        switch (type) {
        case MOVIES_POPULAR:
            isPopular = 1;
            isTopRated = 0;
            break;
        case MOVIES_TOP_RATED:
            isPopular = 0;
            isTopRated = 1;
            break;
        default:
            isPopular = 0;
            isTopRated = 0;
        }
        Cursor cursor = getFavoriteIds(context);
        ContentResolver contentResolver = context.getContentResolver();

        for (int i = 0; i < resultLength; i++) {
            JSONObject movie = results.getJSONObject(i);
            contentValues[i] = new ContentValues();
            contentValues[i].put(TMDbContract.Movies.ORIGINAL_TITLE,
                    movie.getString(TMDbContract.Movies.ORIGINAL_TITLE));

            contentValues[i].put(TMDbContract.Movies.OVERVIEW, movie.getString(TMDbContract.Movies.OVERVIEW));
            contentValues[i].put(TMDbContract.Movies.POSTER, movie.getString(TMDbContract.Movies.POSTER));
            contentValues[i].put(TMDbContract.Movies.RELEASE_DATE,
                    movie.getString(TMDbContract.Movies.RELEASE_DATE));
            contentValues[i].put(TMDbContract.Movies.POPULARITY,
                    movie.getDouble(TMDbContract.Movies.POPULARITY));
            contentValues[i].put(TMDbContract.Movies.VOTE_AVERAGE,
                    movie.getDouble(TMDbContract.Movies.VOTE_AVERAGE));

            int moveId = movie.getInt(TMDbContract.Movies.MOVIE_ID);
            contentValues[i].put(TMDbContract.Movies.MOVIE_ID, moveId);
            cursor.moveToPosition(-1);
            while (cursor.moveToNext()) {
                int favoriteId = cursor.getInt(cursor.getColumnIndex(TMDbContract.Movies.MOVIE_ID));
                if (favoriteId == moveId) {
                    deleteFavorite(context, moveId);
                    isFavorite = 1;
                    contentValues[i].put(TMDbContract.Movies.IS_FAVORITE, isFavorite);
                    break;
                }
            }

            //TODO read up on how to have the col initialized to 0 by defualt
            contentValues[i].put(TMDbContract.Movies.IS_POPULAR, isPopular);
            contentValues[i].put(TMDbContract.Movies.IS_TOP_RATED, isTopRated);

            ids[i] = movie.getInt(TMDbContract.Movies.MOVIE_ID);
        }

        int numInserted = contentResolver.bulkInsert(TMDbContract.Movies.URI, contentValues);

        if (numInserted != resultLength) {
            Log.e(TAG, "Not all of the result were inserted.\n Amount inserted: " + numInserted
                    + "\nAmount from server: " + resultLength);
        }

        return ids;
    } catch (JSONException e) {
        Log.d(TAG, e.getMessage(), e);
        e.printStackTrace();
        return null;
    }
}

From source file:ru.gkpromtech.exhibition.db.Table.java

public <F extends Entity, S extends Entity> List<Pair<F, S>> selectLinked(Class<F> f, Class<S> s,
        String selection, String[] selectionArgs, String orderBy)
        throws InvalidClassException, IllegalAccessException, InstantiationException {

    if (mFks.length != 2)
        throw new InvalidClassException("Entity " + mEntityClass.getName() + " is not a link");

    List<Pair<F, S>> result = new ArrayList<>();
    FkInfo fk1;/*from  w  w w .j  a  v  a2  s .  c  o  m*/
    FkInfo fk2;

    if (mFks[0].entityClass.equals(f) && mFks[1].entityClass.equals(s)) {
        fk1 = mFks[0];
        fk2 = mFks[1];
    } else if (mFks[1].entityClass.equals(f) && mFks[0].entityClass.equals(s)) {
        //     ?   ?? ?
        fk1 = mFks[1];
        fk2 = mFks[0];
    } else {
        throw new InvalidClassException("Invalid classes passed as arguments");
    }

    Table<F> table1 = ((DbHelper) mSqlHelper).getTableFor(f);
    Table<S> table2 = ((DbHelper) mSqlHelper).getTableFor(s);

    StringBuilder query = new StringBuilder();
    for (String column : table1.mColumns) {
        query.append(",f.").append(column);
    }
    for (String column : table2.mColumns)
        query.append(",s.").append(column);
    query.replace(0, 1, "SELECT ");

    query.append("\nFROM ").append(mTableName).append(" t\nJOIN ").append(table1.mTableName).append(" f ON f.")
            .append(fk1.fkName).append(" = t.").append(fk1.fieldName).append("\nJOIN ")
            .append(table2.mTableName).append(" s ON s.").append(fk2.fkName).append(" = t.")
            .append(fk2.fieldName);
    if (selection != null)
        query.append("\nWHERE ").append(selection);
    if (orderBy != null)
        query.append("\nORDER BY ").append(orderBy);

    String queryString = query.toString();
    if (BuildConfig.DEBUG)
        Log.d("PP", queryString);

    SQLiteDatabase db = mSqlHelper.getReadableDatabase();
    Cursor cursor = db.rawQuery(queryString, selectionArgs);

    //noinspection TryFinallyCanBeTryWithResources
    try {
        while (cursor.moveToNext()) {
            F entity1 = f.newInstance();
            S entity2 = s.newInstance();
            for (int i = 0; i < table1.mFields.length; ++i)
                fillFieldValue(table1.mType[i], table1.mFields[i], entity1, cursor, i);
            for (int i = 0; i < table2.mFields.length; ++i)
                fillFieldValue(table2.mType[i], table2.mFields[i], entity2, cursor, table1.mFields.length + i);
            result.add(new Pair<>(entity1, entity2));
        }
    } finally {
        cursor.close();
        db.close();
    }

    return result;
}