Java Code Examples for android.database.Cursor.getColumnCount()

The following are Jave code examples for showing how to use getColumnCount() of the android.database.Cursor class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: mobile-store   File: LoggingQuery.java   Source Code and License Vote up 8 votes
private String[] getExplainQueryPlan() {
    Cursor cursor = db.rawQuery("EXPLAIN QUERY PLAN " + query, queryArgs);
    String[] plan = new String[cursor.getCount()];
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        // The docs at https://sqlite.org/eqp.html talk about how the output format of
        // EXPLAIN QUERY PLAN can change between SQLite versions. This has been observed
        // between the sqlite versions on Android 2.3.3 and Android 5.0. However, it seems
        // that the last column is always the one with the interesting details that we wish
        // to log. If this fails for some reason, then hey, it is only for debug builds, right?
        if (cursor.getColumnCount() > 0) {
            int index = cursor.getColumnCount() - 1;
            plan[cursor.getPosition()] = cursor.getString(index);
        }
        cursor.moveToNext();
    }
    cursor.close();
    return plan;
}
 
Example 2
Project: FuelUp   File: JsonUtil.java   Source Code and License Vote up 6 votes
private static JSONObject getVehicleAsJson(final Long id, Context context) throws JSONException {
    String[] selectionArgs = { String.valueOf(id) };
    Cursor cursor = context.getContentResolver().query(VehicleEntry.CONTENT_URI,
            FuelUpContract.ALL_COLUMNS_VEHICLES, VehicleEntry._ID + "=?",
            selectionArgs, null);

    JSONObject row = new JSONObject();
    if (cursor != null) {
        cursor.moveToFirst();
        for (int i = 0; i < cursor.getColumnCount(); i++) {
            if (cursor.getColumnName(i) != null
                    && !cursor.getColumnName(i).equals(VehicleEntry._ID)
                    && !cursor.getColumnName(i).equals(VehicleEntry.COLUMN_PICTURE)) {
                row.put(cursor.getColumnName(i), cursor.getString(i));
            }
        }
        cursor.close();
    }

    return row;
}
 
Example 3
Project: CleanArchitechture   File: Logger.java   Source Code and License Vote up 6 votes
public static void dump(Cursor cursor) {
    if (cursor != null && !cursor.isClosed()) {
        cursor.moveToFirst();

        do {
            int cc = cursor.getColumnCount();
            Logger.e(" cursor: %s/%s", cc, cursor.toString());
            for (int i = 0; i < cc; i++) {
                Logger.e("  %s: %s", cursor.getColumnName(i),
                        cursor.getString(i));
            }
        } while (cursor.moveToNext());

        cursor.moveToFirst();
    }

}
 
Example 4
Project: FuelUp   File: JsonUtil.java   Source Code and License Vote up 6 votes
private static JSONArray getJsonArrayFromCursor(final Cursor cursor) {
    JSONArray resultSet = new JSONArray();
    if (cursor != null) {
        while (cursor.moveToNext()) {
            JSONObject row = new JSONObject();
            for (int i = 0; i < cursor.getColumnCount(); i++) {
                if (cursor.getColumnName(i) != null
                        && !cursor.getColumnName(i).equals(ExpenseEntry.COLUMN_VEHICLE)
                        && !cursor.getColumnName(i).equals(FillUpEntry.COLUMN_VEHICLE)
                        && !cursor.getColumnName(i).equals(BaseColumns._ID)) {
                    try {
                        row.put(cursor.getColumnName(i), cursor.getString(i));
                    } catch (Exception e) {
                        Log.d(LOG_TAG, e.getMessage());
                    }
                }
            }
            resultSet.put(row);
        }
        cursor.close();
    }

    return resultSet;
}
 
Example 5
Project: AndroidSnooper   File: DatabaseDataReader.java   Source Code and License Vote up 6 votes
@NonNull
public Table getTableData(SQLiteDatabase database, String tableName) {
  Table table = new Table();
  Cursor tableDataCursor = database.rawQuery("SELECT * FROM " + tableName, null);
  table.setColumns(Arrays.asList(tableDataCursor.getColumnNames()));
  List<Row> rows = new ArrayList<>();
  if (tableDataCursor != null && tableDataCursor.moveToFirst()) {
    int columnCount = tableDataCursor.getColumnCount();

    while (!tableDataCursor.isAfterLast()) {
      List<String> data = new ArrayList<>();
      for (int i = 0; i < columnCount; i++) {
        data.add(tableDataCursor.getString(i));
      }

      Row row = new Row(data);
      rows.add(row);

      tableDataCursor.moveToNext();
    }
  }
  table.setName(tableName);
  table.setRows(rows);
  tableDataCursor.close();
  return table;
}
 
Example 6
Project: MeetMusic   File: DBManager.java   Source Code and License Vote up 6 votes
public ArrayList<String> getMusicInfo(int id) {
    if (id == -1) {
        return null;
    }
    Cursor cursor = null;
    ArrayList<String> musicInfo = new ArrayList<String>();
    cursor = db.query(DatabaseHelper.MUSIC_TABLE, null, ID_COLUMN + " = ?", new String[]{"" + id}, null, null, null);
    if (cursor.moveToFirst()) {
        for (int i = 0; i < cursor.getColumnCount(); i++) {
            musicInfo.add(i, cursor.getString(i));
        }
    } else {
        musicInfo.add("0");
        musicInfo.add("听听音乐");
        musicInfo.add("好音质");
        musicInfo.add("0");
        musicInfo.add("0");
        musicInfo.add("0");
        musicInfo.add("0");
        musicInfo.add("0");
    }
    if (cursor != null) {
        cursor.close();
    }
    return musicInfo;
}
 
Example 7
Project: Xndroid   File: BookmarkLocalSync.java   Source Code and License Vote up 5 votes
@NonNull
private List<HistoryItem> getBookmarksFromContentUri(String contentUri) {
    List<HistoryItem> list = new ArrayList<>();
    Cursor cursor = getBrowserCursor(contentUri);
    try {
        if (cursor != null) {
            for (int n = 0; n < cursor.getColumnCount(); n++) {
                Log.d(TAG, cursor.getColumnName(n));
            }

            while (cursor.moveToNext()) {
                if (cursor.getInt(2) == 1) {
                    String url = cursor.getString(0);
                    String title = cursor.getString(1);
                    if (url.isEmpty()) {
                        continue;
                    }
                    if (title == null || title.isEmpty()) {
                        title = Utils.getDomainName(url);
                    }
                    if (title != null) {
                        list.add(new HistoryItem(url, title));
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    Utils.close(cursor);
    return list;
}
 
Example 8
Project: GitHub   File: CursorUtils.java   Source Code and License Vote up 5 votes
public static DbModel getDbModel(final Cursor cursor) {
    DbModel result = new DbModel();
    int columnCount = cursor.getColumnCount();
    for (int i = 0; i < columnCount; i++) {
        result.add(cursor.getColumnName(i), cursor.getString(i));
    }
    return result;
}
 
Example 9
Project: aos-MediaLib   File: MusicStoreImportImpl.java   Source Code and License Vote up 5 votes
/** copies data from Android's media db to ours */
private static int copyData (ContentResolver cr, String minId) {
    int imported = 0;
    String where = WHERE_ALL;
    String[] whereArgs = null;
    if (minId != null)  {
        where = WHERE_MIN_ID;
        whereArgs = new String[] { minId };
    }
    Cursor allFiles = CustomCursor.wrap(cr.query(MediaStore.Files.getContentUri("external"),
            FILES_PROJECTION, where, whereArgs, BaseColumns._ID));
    if (allFiles != null) {
        int count = allFiles.getCount();
        int ccount = allFiles.getColumnCount();
        if (count > 0) {
            // transaction size limited, acts like buffered output stream and auto-flushes queue
            BulkInserter inserter = new BulkInserter(MusicStoreInternal.FILES_IMPORT, cr, 2000);
            if (DBG) Log.d(TAG, "found items to import:" + count);
            while (allFiles.moveToNext()) {
                ContentValues cv = new ContentValues(ccount);
                DatabaseUtils.cursorRowToContentValues(allFiles, cv);
                inserter.add(cv);
            }
            imported = inserter.execute();
        }
        allFiles.close();
    }
    return imported;
}
 
Example 10
Project: Linphone4Android   File: ContactsManager.java   Source Code and License Vote up 5 votes
private Cursor getContactsCursor(ContentResolver cr) {
	String req = "(" + Data.MIMETYPE + " = '" + CommonDataKinds.Phone.CONTENT_ITEM_TYPE
			+ "' AND " + CommonDataKinds.Phone.NUMBER + " IS NOT NULL "
			+ " OR (" + Data.MIMETYPE + " = '" + CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE
			+ "' AND " + CommonDataKinds.SipAddress.SIP_ADDRESS + " IS NOT NULL))";
	String[] projection = new String[] { Data.CONTACT_ID, Data.DISPLAY_NAME };
	String query = Data.DISPLAY_NAME + " IS NOT NULL AND (" + req + ")";

	Cursor cursor = cr.query(Data.CONTENT_URI, projection, query, null, " lower(" + Data.DISPLAY_NAME + ") COLLATE UNICODE ASC");
	if (cursor == null) {
		return cursor;
	}

	MatrixCursor result = new MatrixCursor(cursor.getColumnNames());
	Set<String> groupBy = new HashSet<String>();
	while (cursor.moveToNext()) {
	    String name = cursor.getString(cursor.getColumnIndex(Data.DISPLAY_NAME));
	    if (!groupBy.contains(name)) {
	    	groupBy.add(name);
	    	Object[] newRow = new Object[cursor.getColumnCount()];

	    	int contactID = cursor.getColumnIndex(Data.CONTACT_ID);
	    	int displayName = cursor.getColumnIndex(Data.DISPLAY_NAME);

	    	newRow[contactID] = cursor.getString(contactID);
	    	newRow[displayName] = cursor.getString(displayName);

	        result.addRow(newRow);
    	}
    }
	cursor.close();
	return result;
}
 
Example 11
Project: OpenHomeAnalysis   File: OhaEnergyUseProviderTest.java   Source Code and License Vote up 5 votes
@Test
public void caseEnergyUseBill() {

    // 16/ 02 ate 20/03
    Context context = InstrumentationRegistry.getTargetContext();
    ContentResolver contentResolver = context.getContentResolver();
    Calendar dateBegin = Calendar.getInstance();
    //Utilização de energia no dia 01/01/2015.
    dateBegin.set(2016, 11, 22, 0, 0, 0);
    dateBegin.set(Calendar.MILLISECOND, 0);

    Calendar dateEnd = Calendar.getInstance();
    //Utilização de energia no dia 01/01/2015.
    dateEnd.set(2016, 12, 21, 0, 0, 0);
    dateEnd.set(Calendar.MILLISECOND, 0);
    ContentValues contentValues = EnergyUseBillEntry.parse("February 2017", dateBegin.getTime(), dateEnd.getTime(), 0.65);
    contentResolver.insert(OhaEnergyUseContract.CONTENT_URI_BILL, contentValues);

    Cursor cursorBills = contentResolver.query(
            OhaEnergyUseContract.CONTENT_URI_BILL,
            null,
            null,
            null,
            null
    );
    String tag = "Energy Bill:";
    while (cursorBills.moveToNext()){
        Log.i(tag,String.format("==============%s================", cursorBills.getString(1)));
        for(int field = 0; field < cursorBills.getColumnCount(); field++ ){
            Log.i(tag,String.format("%s: %s", cursorBills.getColumnName(field), cursorBills.getString(field) ) );
        }
    }
}
 
Example 12
Project: quickhybrid-android   File: PhotoSelector.java   Source Code and License Vote up 5 votes
private void handlePickBack(Context con, Intent intent) {
    Uri uri = intent.getData();
    Cursor cursor = con.getContentResolver().query(uri, null, null, null, null);
    if (cursor != null) {
        cursor.moveToFirst();
        HashMap<String, String> map = new HashMap<String, String>();
        for (int i = 0; i < cursor.getColumnCount(); i++) {
            map.put(cursor.getColumnName(i), cursor.getString(i));
        }
        String spath = map.get("_data");
        decodeFile(spath, dWidth, dQuality);
        cursor.close();
    }
}
 
Example 13
Project: mobile-store   File: InstalledApp.java   Source Code and License Vote up 5 votes
public InstalledApp(Cursor cursor) {

        checkCursorPosition(cursor);

        for (int i = 0; i < cursor.getColumnCount(); i++) {
            String n = cursor.getColumnName(i);
            switch (n) {
                case Schema.InstalledAppTable.Cols._ID:
                    id = cursor.getLong(i);
                    break;
                case Schema.InstalledAppTable.Cols.Package.NAME:
                    packageName = cursor.getString(i);
                    break;
                case Schema.InstalledAppTable.Cols.VERSION_CODE:
                    versionCode = cursor.getInt(i);
                    break;
                case Schema.InstalledAppTable.Cols.VERSION_NAME:
                    versionName = cursor.getString(i);
                    break;
                case Schema.InstalledAppTable.Cols.APPLICATION_LABEL:
                    applicationLabel = cursor.getString(i);
                    break;
                case Schema.InstalledAppTable.Cols.SIGNATURE:
                    signature = cursor.getString(i);
                    break;
                case Schema.InstalledAppTable.Cols.LAST_UPDATE_TIME:
                    lastUpdateTime = cursor.getLong(i);
                    break;
                case Schema.InstalledAppTable.Cols.HASH_TYPE:
                    hashType = cursor.getString(i);
                    break;
                case Schema.InstalledAppTable.Cols.HASH:
                    hash = cursor.getString(i);
                    break;
            }
        }
    }
 
Example 14
Project: musicplayer   File: MusicListTransit.java   Source Code and License Vote up 5 votes
private String getAlbumArt(Context mcontext, int album_id) {
    String mUriAlbums = "content://media/external/audio/albums";
    String[] projection = new String[]{"album_art"};
    Cursor cur = mcontext.getContentResolver().query(
            Uri.parse(mUriAlbums + File.separator + Integer.toString(album_id)),
            projection, null, null, null);
    String album_art = null;
    if (cur.getCount() > 0 && cur.getColumnCount() > 0) {
        cur.moveToNext();
        album_art = cur.getString(0);
    }
    cur.close();
    return album_art;
}
 
Example 15
Project: RetrofitAppArchitecture   File: Utils.java   Source Code and License Vote up 5 votes
public static Map<String, Object> cursor2Map(Cursor cursor) {
    Map<String, Object> map = new HashMap<>();
    if (cursor != null && cursor.getColumnCount() > 0) {
        int count = cursor.getColumnCount();
        for (int i = 0; i < count; i++) {
            int type = cursor.getType(i);

            Object value = null;
            switch (type) {
                case Cursor.FIELD_TYPE_STRING:
                    value = cursor.getString(i);
                    break;
                case Cursor.FIELD_TYPE_INTEGER:
                    value = cursor.getInt(i);
                    break;
                case Cursor.FIELD_TYPE_FLOAT:
                    value = cursor.getFloat(i);
                    break;
                case Cursor.FIELD_TYPE_NULL:
                    LogUtils.d("未知的参数类型,type:" + type);
                    break;
                case Cursor.FIELD_TYPE_BLOB:
                    LogUtils.d("未知的参数类型,type:" + type);
                    break;
            }
            if (value != null) {
                String name = cursor.getColumnName(i);
                map.put(name, value);
            }
        }
    }
    return map;
}
 
Example 16
Project: CP-Tester   File: ContentProviderHelper.java   Source Code and License Vote up 5 votes
public static String getSQLResult(Context context, ProviderInfo provider, String query) {
    Bundle bundle = new Bundle();
    bundle.putString("provider_name", provider.packageName);
    bundle.putString("query", query);
    FirebaseAnalytics.getInstance(context).logEvent("sql_injection", bundle);
    StringBuilder s = new StringBuilder();
    try {
        Uri uri = Uri.parse("content://" + provider.authority);
        Cursor c = context.getContentResolver().query(uri, new String[]{ query }, null, null, null);
        int col_c = c != null ? c.getColumnCount() : 0;
        String[] Columns = new String[col_c];
        for (int i = 0; i < col_c; i++) {
            s.append(c.getColumnName(i));
            s.append(":");
            Columns[i] = c.getColumnName(i);
        }
        s.append("\n");
        if (c != null && c.moveToFirst()) {
            do {
                for (int i = 0; i < col_c; i++) {
                    if (Columns[i].toLowerCase().contains("image")) {
                        byte[] blob = c.getBlob(i);
                        s.append(bytesToHexString(blob));
                    } else {
                        s.append(c.getString(i));
                    }
                    s.append(";");
                }
                s.append("\n");
            } while (c.moveToNext());
        }
        if (c != null) {
            c.close();
        }
    } catch (Throwable e) {
        s.append(e.getMessage());
    }
    return s.toString();
}
 
Example 17
Project: ultra-debugger   File: Module.java   Source Code and License Vote up 4 votes
@NonNull
private Page showItemsList(String database, String tableName) {
    try {
        SQLiteDatabase sqLiteDatabase = getContext().openOrCreateDatabase(database, Context.MODE_PRIVATE, null);
        Cursor cursor = sqLiteDatabase.rawQuery("SELECT " + COLUMN_ROW_ID + ",* FROM " + tableName, null);
        Table table = new Table();
        if (cursor.moveToFirst()) {
            int y = 0;
            do {
                if (y == 0) {
                    String[] columnNames = cursor.getColumnNames();
                    for (int x = 1; x < columnNames.length; x++) {
                        table.add(x - 1, 0, new RawContentPart(columnNames[x]));
                    }
                    y++;
                }
                int columnCount = cursor.getColumnCount();
                for (int x = 1; x < columnCount; x++) {
                    table.add(x - 1, y, new RawContentPart(cursor.getString(x)));
                }
                table.add(columnCount - 1, y,
                        new Link("?" + PARAMETER_DATABASE + "=" + database + "&" + PARAMETER_TABLE + "=" + tableName + "&" + PARAMETER_EDIT + "="
                                + cursor.getString(0), "Edit"));
                table.add(columnCount, y,
                        new Link("?" + PARAMETER_DATABASE + "=" + database + "&" + PARAMETER_TABLE + "=" + tableName + "&" + PARAMETER_DELETE + "="
                                + cursor.getString(0), "Delete"));
                y++;
            } while (cursor.moveToNext());
        }
        cursor.close();
        Page page = new Page();
        page.addNavigationLink("?", "Databases list");
        page.addNavigationLink("?" + PARAMETER_DATABASE + "=" + database, "Tables list");
        page.addNavigationLink("?" + PARAMETER_DATABASE + "=" + database + "&" + PARAMETER_TABLE + "=" + tableName + "&" + PARAMETER_EDIT + "=new", "Insert row");
        page.setSingleContentPart(table);
        return page;
    } catch (Exception e) {
        e.printStackTrace();
        return new ErrorPage("Can't read items: " + e.getMessage(), true);
    }
}
 
Example 18
Project: Taxi-Datalogger   File: CloudPublisherService.java   Source Code and License Vote up 4 votes
@WorkerThread
void processCollectedSensorData() throws JSONException {
    if (mPublisher == null || !mPublisher.isReady()) {
        return;
    }

    // Query the data we wish to push to the cloud
    long lastSyndId = DatalogDbHelper.getLastSyncId(this);
    Cursor cursor = mDatabase.query(DatalogDbHelper.TABLE_NAME,
            null,
            DatalogDbHelper.DatalogEntry._ID + " > " + lastSyndId,
            null,
            null,
            null,
            BaseColumns._ID + " ASC");
    Log.i(TAG, "publishing " + cursor.getCount() + " log entries");

    final int columnCount = cursor.getColumnCount();
    for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
        JSONObject entryObject = new JSONObject();
        // Add the device ID to the JSON record.
        //
        // FIXME: There should be a way to get Google Cloud IOT to do this on its
        // end, so I don't need to trust the IDs.
        entryObject.put("deviceId", mDeviceId);
        long id = 0;
        for (int i = 0; i < columnCount; i++) {
            String columnName = cursor.getColumnName(i);
            if (columnName != null) {
                // Note the most recent ID we've transmitted, but don't include
                // the ID column in the JSON message
                if (columnName.equals(BaseColumns._ID)) {
                    id = cursor.getLong(i);
                    continue;
                }
                if (cursor.getType(i) == Cursor.FIELD_TYPE_FLOAT) {
                    entryObject.put(columnName, cursor.getDouble(i));
                } else {
                    entryObject.put(columnName, cursor.getString(i));
                }
            }
        }
        // Push message to the cloud
        mPublisher.publish(entryObject.toString());
        Log.d(TAG, "Sent entry: " + (cursor.getPosition()+1) + "/" +
                cursor.getCount());
        if (id > lastSyndId)
            DatalogDbHelper.setLastSyncId(this, id);
    }
    cursor.close();
}
 
Example 19
Project: mobile-store   File: Repo.java   Source Code and License Vote up 4 votes
public Repo(Cursor cursor) {

        checkCursorPosition(cursor);

        for (int i = 0; i < cursor.getColumnCount(); i++) {
            switch (cursor.getColumnName(i)) {
                case Cols._ID:
                    id = cursor.getInt(i);
                    break;
                case Cols.LAST_ETAG:
                    lastetag = cursor.getString(i);
                    break;
                case Cols.ADDRESS:
                    address = cursor.getString(i);
                    break;
                case Cols.DESCRIPTION:
                    description = cursor.getString(i);
                    break;
                case Cols.FINGERPRINT:
                    fingerprint = cursor.getString(i);
                    break;
                case Cols.IN_USE:
                    inuse = cursor.getInt(i) == 1;
                    break;
                case Cols.LAST_UPDATED:
                    lastUpdated = Utils.parseTime(cursor.getString(i), null);
                    break;
                case Cols.MAX_AGE:
                    maxage = cursor.getInt(i);
                    break;
                case Cols.VERSION:
                    version = cursor.getInt(i);
                    break;
                case Cols.NAME:
                    name = cursor.getString(i);
                    break;
                case Cols.SIGNING_CERT:
                    signingCertificate = cursor.getString(i);
                    break;
                case Cols.PRIORITY:
                    priority = cursor.getInt(i);
                    break;
                case Cols.IS_SWAP:
                    isSwap = cursor.getInt(i) == 1;
                    break;
                case Cols.USERNAME:
                    username = cursor.getString(i);
                    break;
                case Cols.PASSWORD:
                    password = cursor.getString(i);
                    break;
                case Cols.TIMESTAMP:
                    timestamp = cursor.getLong(i);
                    break;
                case Cols.ICON:
                    icon = cursor.getString(i);
                    break;
                case Cols.MIRRORS:
                    mirrors = Utils.parseCommaSeparatedString(cursor.getString(i));
                    break;
                case Cols.PUSH_REQUESTS:
                    pushRequests = cursor.getInt(i);
                    break;
            }
        }
    }
 
Example 20
Project: Bee-Analyzer   File: MapsActivity.java   Source Code and License Vote up 4 votes
public void onLocationChanged(Location location)
{
    double latitude = location.getLatitude();
    double longitude = location.getLongitude();
    LatLng newLocation = new LatLng(latitude, longitude);

    String out = "0";

    String selectQuery = "SELECT imei,latitude,longitude,datetime(timestamp,'localtime') as currentTime, out FROM position ORDER BY currentTime LIMIT 1";
    Cursor cursor = localdb.rawQuery(selectQuery, null);

    if (cursor.moveToFirst()) //If there is any location info before
    {
        HashMap<String, String> lastLocation = new HashMap<String, String>();
        for(int i=0; i<cursor.getColumnCount();i++)
            lastLocation.put(cursor.getColumnName(i), cursor.getString(i));

        //If Last location is out of activation area
        if(lastLocation.get("out") == "1")
        {
            //if (true)
            if (PolyUtil.containsLocation(newLocation,ituArea.getPoints(),true))
                Insertion(newLocation, out);
        }
        //If distance greater or equal to 20 meter between last location and new location
        //else if(true)
        else if(getDistance(newLocation, new LatLng(Double.parseDouble(lastLocation.get("latitude")),Double.parseDouble(lastLocation.get("longitude")))) >= 20)
        {
            //if(false)
            if (!PolyUtil.containsLocation(newLocation,ituArea.getPoints(),true))
                out = "1";
            Insertion(newLocation,out);
        }
    }
    else // First location info
    {
        //if (true)
        if (PolyUtil.containsLocation(newLocation,ituArea.getPoints(),true))
            Insertion(newLocation,out);
    }
}