Java Code Examples for android.database.Cursor#getColumnNames()

The following examples show how to use android.database.Cursor#getColumnNames() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RootCursorWrapper.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
public RootCursorWrapper(String authority, String rootId, Cursor cursor, int maxCount) {
    mAuthority = authority;
    mRootId = rootId;
    mCursor = cursor;

    final int count = cursor.getCount();
    if (maxCount > 0 && count > maxCount) {
        mCount = maxCount;
    } else {
        mCount = count;
    }

    if (cursor.getColumnIndex(COLUMN_AUTHORITY) != -1
            || cursor.getColumnIndex(COLUMN_ROOT_ID) != -1) {
        throw new IllegalArgumentException("Cursor contains internal columns!");
    }
    final String[] before = cursor.getColumnNames();
    mColumnNames = new String[before.length + 2];
    System.arraycopy(before, 0, mColumnNames, 0, before.length);
    mAuthorityIndex = before.length;
    mRootIdIndex = before.length + 1;
    mColumnNames[mAuthorityIndex] = COLUMN_AUTHORITY;
    mColumnNames[mRootIdIndex] = COLUMN_ROOT_ID;
}
 
Example 2
Source File: CursorMatchers.java    From android-test with Apache License 2.0 6 votes vote down vote up
private static int findColumnIndex(Matcher<String> nameMatcher, Cursor cursor) {
  int result = COLUMN_NOT_FOUND;
  String[] columnNames = cursor.getColumnNames();
  for (int i = 0; i < columnNames.length; i++) {
    String column = columnNames[i];
    if (nameMatcher.matches(column)) {
      if (result == COLUMN_NOT_FOUND) {
        result = i;
      } else {
        result = MULTIPLE_COLUMNS_FOUND;
        break;
      }
    }
  }
  return result;
}
 
Example 3
Source File: TableViewActivity.java    From SQLite-sync.com with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void loadGridView() {
    SQLiteDatabase db = null;
    Cursor cursor = null;
    String[] columns = new String[0];
    List<String[]> rows = new ArrayList<>();

    try{
        db = openOrCreateDatabase("/data/data/" + getPackageName() + "/sqlitesync.db", 1, null);
        cursor = db.rawQuery(String.format("Select * FROM %s;", _tableName), null);

        columns = cursor.getColumnNames();

        while (cursor.moveToNext()){
            List<String> row = new ArrayList<>();
            for(int i = 0; i < cursor.getColumnCount(); i++){
                row.add(cursor.getString(i));
            }
            rows.add(row.toArray(new String[row.size()]));
        }
    }
    finally {
        if(cursor != null && !cursor.isClosed()){
            cursor.close();
        }
        if(db != null && db.isOpen()){
            db.close();
        }
    }

    ((GridView) findViewById(R.id.gridView)).setAdapter(new GridViewAdapter(this, columns, rows.toArray(new String[rows.size()][]), this));
    ((GridView) findViewById(R.id.gridView)).setNumColumns(columns.length + 1);
}
 
Example 4
Source File: ContactsManager.java    From Linphone4Android with GNU General Public License v3.0 5 votes vote down vote up
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 5
Source File: CursorHelper.java    From libcommon with Apache License 2.0 5 votes vote down vote up
@SuppressLint("NewApi")
public static void dumpCursor(@Nullable final Cursor cursor) {
	if ((cursor != null) && !cursor.isClosed() && cursor.moveToFirst()) {
		final StringBuilder sb = new StringBuilder();
		final int n = cursor.getColumnCount();
		final String[] columnNames = cursor.getColumnNames();
		int row = 0;
		do {
			sb.setLength(0);
			sb.append("row=").append(row).append(", ");
			for (int i = 0; i < n; i++) {
				switch (cursor.getType(i)) {
				case Cursor.FIELD_TYPE_FLOAT:
					sb.append(columnNames[i]).append("=").append(cursor.getDouble(i));
					break;
				case Cursor.FIELD_TYPE_INTEGER:
					sb.append(columnNames[i]).append("=").append(cursor.getLong(i));
					break;
				case Cursor.FIELD_TYPE_STRING:
					sb.append(columnNames[i]).append("=").append(cursor.getString(i));
					break;
				case Cursor.FIELD_TYPE_BLOB:
					sb.append(columnNames[i]).append("=").append("BLOB");
					break;
				case Cursor.FIELD_TYPE_NULL:
					sb.append(columnNames[i]).append("=").append("NULL");
					break;
				default:
					sb.append(columnNames[i]).append("=").append("UNKNOWN");
					break;
				}
				sb.append(", ");
			}
			Log.v(TAG, "dumpCursor:" + sb.toString());
			row++;
		} while (cursor.moveToNext());
	}
}
 
Example 6
Source File: SMSReceive.java    From cordova-plugin-sms-receive with MIT License 5 votes vote down vote up
private JSONObject getJsonFromCursor(Cursor cur) {
	JSONObject json = new JSONObject();
	int nCol = cur.getColumnCount();
	String keys[] = cur.getColumnNames();
	try {
		for (int j=0; j<nCol; j++) {
			switch(cur.getType(j)) {
				case Cursor.FIELD_TYPE_NULL:
					json.put(keys[j], JSONObject.NULL);
				break;
				case Cursor.FIELD_TYPE_INTEGER:
					json.put(keys[j], cur.getLong(j));
				break;
				case Cursor.FIELD_TYPE_FLOAT:
					json.put(keys[j], cur.getFloat(j));
				break;
				case Cursor.FIELD_TYPE_STRING:
					json.put(keys[j], cur.getString(j));
				break;
				case Cursor.FIELD_TYPE_BLOB:
					json.put(keys[j], cur.getBlob(j));
				break;
			}
		}
	}
	catch (Exception e) {
		return null;
	}
	return json;
}
 
Example 7
Source File: GenreLoader.java    From flutter_audio_query with MIT License 5 votes vote down vote up
@Override
        protected List<Map<String, Object>> loadData(String selection, String[] selectionArgs,
                                                     String sortOrder) {

            List<Map<String, Object>> dataList= new ArrayList<>();
            Cursor genreCursor = m_resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                    new String[] {"Distinct " + GENRE_PROJECTION[0] }, selection,
                    selectionArgs, sortOrder);

//            Cursor genreCursor = m_resolver.query(MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI,
//                    GENRE_PROJECTION, selection, selectionArgs, sortOrder);

            if (genreCursor != null){
                while ( genreCursor.moveToNext() ){
                    try {
                        Map<String, Object> data = new HashMap<>();
                        for (String column : genreCursor.getColumnNames()) {
                            String genreName = genreCursor.getString(
                                    genreCursor.getColumnIndex(column));
                            data.put(MediaStore.Audio.GenresColumns.NAME, genreName);
                        }
                        dataList.add(data);
                    }

                    catch(Exception ex){
                        Log.e(TAG_ERROR, "GenreLoader::loadData method exception");
                        Log.e(TAG_ERROR, ex.getMessage() );
                    }
                }
                genreCursor.close();
            }

            return dataList;
        }
 
Example 8
Source File: AndroidDatabase.java    From pos with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public List<Object> select(String queryString) {
	try {
		SQLiteDatabase database = this.getWritableDatabase();
		List<Object> list = new ArrayList<Object>();
		Cursor cursor = database.rawQuery(queryString, null);

		if (cursor != null) {
			if (cursor.moveToFirst()) {
				do {
					ContentValues content = new ContentValues();
					String[] columnNames = cursor.getColumnNames();
					for (String columnName : columnNames) {
						content.put(columnName, cursor.getString(cursor
								.getColumnIndex(columnName)));
					}
					list.add(content);
				} while (cursor.moveToNext());
			}
		}
		cursor.close();
		database.close();
		return list;

	} catch (Exception e) {
		e.printStackTrace();
		return null;
	}
}
 
Example 9
Source File: TestSunshineDatabase.java    From android-dev-challenge with Apache License 2.0 4 votes vote down vote up
/**
>>>>>>> a6840f1... S07.03-Exercise-ConflictResolutionPolicy
     * Tests the columns with null values cannot be inserted into the database.
     */
    @Test
    public void testNullColumnConstraints() {
        /* Use a WeatherDbHelper to get access to a writable database */

        /* We need a cursor from a weather table query to access the column names */
        Cursor weatherTableCursor = database.query(
                REFLECTED_TABLE_NAME,
                /* We don't care about specifications, we just want the column names */
                null, null, null, null, null, null);

        /* Store the column names and close the cursor */
        String[] weatherTableColumnNames = weatherTableCursor.getColumnNames();
        weatherTableCursor.close();

        /* Obtain weather values from TestUtilities and make a copy to avoid altering singleton */
        ContentValues testValues = TestUtilities.createTestWeatherContentValues();
        /* Create a copy of the testValues to save as a reference point to restore values */
        ContentValues testValuesReferenceCopy = new ContentValues(testValues);

        for (String columnName : weatherTableColumnNames) {

            /* We don't need to verify the _ID column value is not null, the system does */
            if (columnName.equals(WeatherContract.WeatherEntry._ID)) continue;

            /* Set the value to null */
            testValues.putNull(columnName);

            /* Insert ContentValues into database and get a row ID back */
            long shouldFailRowId = database.insert(
                    REFLECTED_TABLE_NAME,
                    null,
                    testValues);

            String variableName = getConstantNameByStringValue(
                    WeatherContract.WeatherEntry.class,
                    columnName);

            /* If the insert fails, which it should in this case, database.insert returns -1 */
            String nullRowInsertShouldFail =
                    "Insert should have failed due to a null value for column: '" + columnName + "'"
                            + ", but didn't."
                            + "\n Check that you've added NOT NULL to " + variableName
                            + " in your create table statement in the WeatherEntry class."
                            + "\n Row ID: ";
            assertEquals(nullRowInsertShouldFail,
                    -1,
                    shouldFailRowId);

            /* "Restore" the original value in testValues */
            testValues.put(columnName, testValuesReferenceCopy.getAsDouble(columnName));
        }

        /* Close database */
        dbHelper.close();
    }
 
Example 10
Source File: DetailsActivity.java    From tracker-control-android with GNU General Public License v3.0 4 votes vote down vote up
protected Boolean doInBackground(final String... args) {
    if (exportDir == null) return false;

    File file = new File(exportDir, appPackageName + ".csv");
    try {
        file.createNewFile();
        CSVWriter csv = new CSVWriter(new FileWriter(file),
                CSVWriter.DEFAULT_SEPARATOR,
                CSVWriter.DEFAULT_QUOTE_CHARACTER,
                CSVWriter.DEFAULT_ESCAPE_CHARACTER,
                CSVWriter.RFC4180_LINE_END);

        Cursor data = trackerList.getAppInfo(appUid);
        if (data == null) return false;

        List<String> columnNames = new ArrayList<>();
        Collections.addAll(columnNames, data.getColumnNames());
        columnNames.add("Tracker Name");
        columnNames.add("Tracker Category");

        csv.writeNext(columnNames.toArray(new String[0]));
        while (data.moveToNext()) {
            String[] row = new String[data.getColumnNames().length + 2];
            for (int i = 0; i < data.getColumnNames().length; i++) {
                row[i] = data.getString(i);
            }

            String hostname = data.getString(data.getColumnIndex("daddr"));
            Tracker tracker = TrackerList.findTracker(hostname);
            if (tracker != null) {
                row[data.getColumnNames().length] = tracker.name;
                row[data.getColumnNames().length + 1] = tracker.category;
            } else {
                row[data.getColumnNames().length] = "";
                row[data.getColumnNames().length + 1] = "";
            }

            csv.writeNext(row);
        }
        csv.close();
        data.close();
    } catch (IOException e) {
        return false;
    }

    return true;
}
 
Example 11
Source File: TestSunshineDatabase.java    From android-dev-challenge with Apache License 2.0 4 votes vote down vote up
/**
>>>>>>> a6840f1... S07.03-Exercise-ConflictResolutionPolicy
     * Tests the columns with null values cannot be inserted into the database.
     */
    @Test
    public void testNullColumnConstraints() {
        /* Use a WeatherDbHelper to get access to a writable database */

        /* We need a cursor from a weather table query to access the column names */
        Cursor weatherTableCursor = database.query(
                REFLECTED_TABLE_NAME,
                /* We don't care about specifications, we just want the column names */
                null, null, null, null, null, null);

        /* Store the column names and close the cursor */
        String[] weatherTableColumnNames = weatherTableCursor.getColumnNames();
        weatherTableCursor.close();

        /* Obtain weather values from TestUtilities and make a copy to avoid altering singleton */
        ContentValues testValues = TestUtilities.createTestWeatherContentValues();
        /* Create a copy of the testValues to save as a reference point to restore values */
        ContentValues testValuesReferenceCopy = new ContentValues(testValues);

        for (String columnName : weatherTableColumnNames) {

            /* We don't need to verify the _ID column value is not null, the system does */
            if (columnName.equals(WeatherContract.WeatherEntry._ID)) continue;

            /* Set the value to null */
            testValues.putNull(columnName);

            /* Insert ContentValues into database and get a row ID back */
            long shouldFailRowId = database.insert(
                    REFLECTED_TABLE_NAME,
                    null,
                    testValues);

            String variableName = getConstantNameByStringValue(
                    WeatherContract.WeatherEntry.class,
                    columnName);

            /* If the insert fails, which it should in this case, database.insert returns -1 */
            String nullRowInsertShouldFail =
                    "Insert should have failed due to a null value for column: '" + columnName + "'"
                            + ", but didn't."
                            + "\n Check that you've added NOT NULL to " + variableName
                            + " in your create table statement in the WeatherEntry class."
                            + "\n Row ID: ";
            assertEquals(nullRowInsertShouldFail,
                    -1,
                    shouldFailRowId);

            /* "Restore" the original value in testValues */
            testValues.put(columnName, testValuesReferenceCopy.getAsDouble(columnName));
        }

        /* Close database */
        dbHelper.close();
    }
 
Example 12
Source File: SqliteManagerPresenter.java    From SqliteManager with Apache License 2.0 4 votes vote down vote up
private
@NonNull
SqliteResponseData getSqliteResponseDataFromQuery(String query, String[] selectionArgs) {
    SqliteResponse sqliteResponse = mSqliteResponseRetriever.getData(query, selectionArgs);
    if (sqliteResponse.isQuerySuccess()) {
        try {
            Cursor cursor = sqliteResponse.getCursor();
            String[] selectedTableColumnNames = cursor.getColumnNames();
            int[] selectedTableColumnTypes = new int[selectedTableColumnNames.length];
            int columnCount = cursor.getColumnCount();
            List<SparseArray<Object>> valuesArray = new ArrayList<>(cursor.getCount());

            if (cursor.moveToFirst()) {
                do {
                    SparseArray<Object> columnValuePair = new SparseArray<>(columnCount);
                    for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) {
                        int fieldType = cursor.getType(columnIndex);
                        selectedTableColumnTypes[columnIndex] = fieldType;
                        if (fieldType == Cursor.FIELD_TYPE_NULL) {
                            columnValuePair.put(columnIndex, cursor.getString(columnIndex));
                        } else if (fieldType == Cursor.FIELD_TYPE_INTEGER) {
                            columnValuePair.put(columnIndex, cursor.getInt(columnIndex));
                        } else if (fieldType == Cursor.FIELD_TYPE_FLOAT) {
                            columnValuePair.put(columnIndex, cursor.getFloat(columnIndex));
                        } else if (fieldType == Cursor.FIELD_TYPE_STRING) {
                            columnValuePair.put(columnIndex, cursor.getString(columnIndex));
                        } else if (fieldType == Cursor.FIELD_TYPE_BLOB) {
                            columnValuePair.put(columnIndex, cursor.getBlob(columnIndex));
                        } else {
                            // never in this case
                            columnValuePair.put(columnIndex, cursor.getString(columnIndex));
                        }
                    }
                    valuesArray.add(columnValuePair);
                } while (cursor.moveToNext());
            }
            return new SqliteResponseData(columnCount, selectedTableColumnNames, selectedTableColumnTypes, valuesArray);
        } catch (Exception exception) {
            // sometimes cursor will not be null. when there are any constraints
            return new SqliteResponseData(exception);
        } finally {
            mSqliteDataRetriever.freeResources();
        }
    } else {
        mSqliteDataRetriever.freeResources();
        return new SqliteResponseData(sqliteResponse.getThrowable());
    }
}
 
Example 13
Source File: CursorUtils.java    From Android-ORM with Apache License 2.0 4 votes vote down vote up
public static List<Object[]> getFromCursor(Cursor c,
        Class<?>[] objClassArray, String[] aliasArray) {
        
    ArrayList<Object[]> list = new ArrayList<Object[]>();
    if (c == null) {
        return list;
    }
    String[] colNames = c.getColumnNames();
    int[] indices = new int[colNames.length];
    Field[] objField = new Field[colNames.length];
    // field type class, used in getter invoked.
    // Class<?>[] fieldClass = new Class<?>[colNames.length];
    int[] types = new int[colNames.length];
    int[] objIds = new int[colNames.length];
    try {
        for (int i = 0; i < colNames.length; i++) {
            indices[i] = c.getColumnIndex(colNames[i]);
            for (int j = 0; j < objClassArray.length; j++) {
                Field f = getObjField(colNames[i], objClassArray[j],
                        aliasArray[j]);
                // fieldClass[i] = f.getType();
                types[i] = getColumnType(f.getType());
                // if (f != null) 
                {
                    objField[i] = f;
                    objIds[i] = j;
                    break;
                }
            }
        }
        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
            Object[] objArray = new Object[objClassArray.length];
            for (int i = 0; i < indices.length; i++) {
                Object obj = objArray[objIds[i]];
                if (obj == null) {
                    obj = objClassArray[objIds[i]].newInstance();
                    objArray[objIds[i]] = obj;
                }
                if (objField[i] != null) {
                    objField[i].setAccessible(true);
                    objField[i].set(obj,
                            getColumnValue(c, indices[i], types[i]));
                }
            }
            list.add(objArray);
        }
        c.close();
    } catch (Exception e) {
        throw new ORMException(e);
    }
    return list;
}
 
Example 14
Source File: ContactablesLoaderCallbacks.java    From android-BasicContactables with Apache License 2.0 4 votes vote down vote up
@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
    TextView tv  = (TextView) ((Activity)mContext).findViewById(R.id.sample_output);
    if(tv == null) {
        Log.e(TAG, "TextView is null?!");
    } else if (mContext == null) {
        Log.e(TAG, "Context is null?");
    } else {
        Log.e(TAG, "Nothing is null?!");
    }

    // Reset text in case of a previous query
    tv.setText(mContext.getText(R.string.intro_message) + "\n\n");

    if (cursor.getCount() == 0) {
        return;
    }

    // Pulling the relevant value from the cursor requires knowing the column index to pull
    // it from.
    // BEGIN_INCLUDE(get_columns)
    int phoneColumnIndex = cursor.getColumnIndex(CommonDataKinds.Phone.NUMBER);
    int emailColumnIndex = cursor.getColumnIndex(CommonDataKinds.Email.ADDRESS);
    int nameColumnIndex = cursor.getColumnIndex(CommonDataKinds.Contactables.DISPLAY_NAME);
    int lookupColumnIndex = cursor.getColumnIndex(CommonDataKinds.Contactables.LOOKUP_KEY);
    int typeColumnIndex = cursor.getColumnIndex(CommonDataKinds.Contactables.MIMETYPE);
    // END_INCLUDE(get_columns)

    cursor.moveToFirst();
    // Lookup key is the easiest way to verify a row of data is for the same
    // contact as the previous row.
    String lookupKey = "";
    do {
        // BEGIN_INCLUDE(lookup_key)
        String currentLookupKey = cursor.getString(lookupColumnIndex);
        if (!lookupKey.equals(currentLookupKey)) {
            String displayName = cursor.getString(nameColumnIndex);
            tv.append(displayName + "\n");
            lookupKey = currentLookupKey;
        }
        // END_INCLUDE(lookup_key)

        // BEGIN_INCLUDE(retrieve_data)
        // The data type can be determined using the mime type column.
        String mimeType = cursor.getString(typeColumnIndex);
        if (mimeType.equals(CommonDataKinds.Phone.CONTENT_ITEM_TYPE)) {
            tv.append("\tPhone Number: " + cursor.getString(phoneColumnIndex) + "\n");
        } else if (mimeType.equals(CommonDataKinds.Email.CONTENT_ITEM_TYPE)) {
            tv.append("\tEmail Address: " + cursor.getString(emailColumnIndex) + "\n");
        }
        // END_INCLUDE(retrieve_data)

        // Look at DDMS to see all the columns returned by a query to Contactables.
        // Behold, the firehose!
        for(String column : cursor.getColumnNames()) {
            Log.d(TAG, column + column + ": " +
                    cursor.getString(cursor.getColumnIndex(column)) + "\n");
        }
    } while (cursor.moveToNext());
}
 
Example 15
Source File: TestSunshineDatabase.java    From android-dev-challenge with Apache License 2.0 4 votes vote down vote up
/**
>>>>>>> a6840f1... S07.03-Exercise-ConflictResolutionPolicy
     * Tests the columns with null values cannot be inserted into the database.
     */
    @Test
    public void testNullColumnConstraints() {
        /* Use a WeatherDbHelper to get access to a writable database */

        /* We need a cursor from a weather table query to access the column names */
        Cursor weatherTableCursor = database.query(
                REFLECTED_TABLE_NAME,
                /* We don't care about specifications, we just want the column names */
                null, null, null, null, null, null);

        /* Store the column names and close the cursor */
        String[] weatherTableColumnNames = weatherTableCursor.getColumnNames();
        weatherTableCursor.close();

        /* Obtain weather values from TestUtilities and make a copy to avoid altering singleton */
        ContentValues testValues = TestUtilities.createTestWeatherContentValues();
        /* Create a copy of the testValues to save as a reference point to restore values */
        ContentValues testValuesReferenceCopy = new ContentValues(testValues);

        for (String columnName : weatherTableColumnNames) {

            /* We don't need to verify the _ID column value is not null, the system does */
            if (columnName.equals(WeatherContract.WeatherEntry._ID)) continue;

            /* Set the value to null */
            testValues.putNull(columnName);

            /* Insert ContentValues into database and get a row ID back */
            long shouldFailRowId = database.insert(
                    REFLECTED_TABLE_NAME,
                    null,
                    testValues);

            String variableName = getConstantNameByStringValue(
                    WeatherContract.WeatherEntry.class,
                    columnName);

            /* If the insert fails, which it should in this case, database.insert returns -1 */
            String nullRowInsertShouldFail =
                    "Insert should have failed due to a null value for column: '" + columnName + "'"
                            + ", but didn't."
                            + "\n Check that you've added NOT NULL to " + variableName
                            + " in your create table statement in the WeatherEntry class."
                            + "\n Row ID: ";
            assertEquals(nullRowInsertShouldFail,
                    -1,
                    shouldFailRowId);

            /* "Restore" the original value in testValues */
            testValues.put(columnName, testValuesReferenceCopy.getAsDouble(columnName));
        }

        /* Close database */
        dbHelper.close();
    }
 
Example 16
Source File: TestSunshineDatabase.java    From android-dev-challenge with Apache License 2.0 4 votes vote down vote up
/**
>>>>>>> a6840f1... S07.03-Exercise-ConflictResolutionPolicy
     * Tests the columns with null values cannot be inserted into the database.
     */
    @Test
    public void testNullColumnConstraints() {
        /* Use a WeatherDbHelper to get access to a writable database */

        /* We need a cursor from a weather table query to access the column names */
        Cursor weatherTableCursor = database.query(
                REFLECTED_TABLE_NAME,
                /* We don't care about specifications, we just want the column names */
                null, null, null, null, null, null);

        /* Store the column names and close the cursor */
        String[] weatherTableColumnNames = weatherTableCursor.getColumnNames();
        weatherTableCursor.close();

        /* Obtain weather values from TestUtilities and make a copy to avoid altering singleton */
        ContentValues testValues = TestUtilities.createTestWeatherContentValues();
        /* Create a copy of the testValues to save as a reference point to restore values */
        ContentValues testValuesReferenceCopy = new ContentValues(testValues);

        for (String columnName : weatherTableColumnNames) {

            /* We don't need to verify the _ID column value is not null, the system does */
            if (columnName.equals(WeatherContract.WeatherEntry._ID)) continue;

            /* Set the value to null */
            testValues.putNull(columnName);

            /* Insert ContentValues into database and get a row ID back */
            long shouldFailRowId = database.insert(
                    REFLECTED_TABLE_NAME,
                    null,
                    testValues);

            String variableName = getConstantNameByStringValue(
                    WeatherContract.WeatherEntry.class,
                    columnName);

            /* If the insert fails, which it should in this case, database.insert returns -1 */
            String nullRowInsertShouldFail =
                    "Insert should have failed due to a null value for column: '" + columnName + "'"
                            + ", but didn't."
                            + "\n Check that you've added NOT NULL to " + variableName
                            + " in your create table statement in the WeatherEntry class."
                            + "\n Row ID: ";
            assertEquals(nullRowInsertShouldFail,
                    -1,
                    shouldFailRowId);

            /* "Restore" the original value in testValues */
            testValues.put(columnName, testValuesReferenceCopy.getAsDouble(columnName));
        }

        /* Close database */
        dbHelper.close();
    }
 
Example 17
Source File: ChromeFileProvider.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
        String sortOrder) {
    Uri fileUri = getFileUriWhenReady(uri);
    if (fileUri == null) return null;

    // Workaround for a bad assumption that particular MediaStore columns exist by certain third
    // party applications.
    // http://crbug.com/467423.
    Cursor source = super.query(fileUri, projection, selection, selectionArgs, sortOrder);

    String[] columnNames = source.getColumnNames();
    String[] newColumnNames = columnNamesWithData(columnNames);
    if (columnNames == newColumnNames) return source;

    MatrixCursor cursor = new MatrixCursor(newColumnNames, source.getCount());

    source.moveToPosition(-1);
    while (source.moveToNext()) {
        MatrixCursor.RowBuilder row = cursor.newRow();
        for (int i = 0; i < columnNames.length; i++) {
            switch (source.getType(i)) {
                case Cursor.FIELD_TYPE_INTEGER:
                    row.add(source.getInt(i));
                    break;
                case Cursor.FIELD_TYPE_FLOAT:
                    row.add(source.getFloat(i));
                    break;
                case Cursor.FIELD_TYPE_STRING:
                    row.add(source.getString(i));
                    break;
                case Cursor.FIELD_TYPE_BLOB:
                    row.add(source.getBlob(i));
                    break;
                case Cursor.FIELD_TYPE_NULL:
                default:
                    row.add(null);
                    break;
            }
        }
    }

    source.close();
    return cursor;
}
 
Example 18
Source File: TestSunshineDatabase.java    From android-dev-challenge with Apache License 2.0 4 votes vote down vote up
/**
>>>>>>> a6840f1... S07.03-Exercise-ConflictResolutionPolicy
     * Tests the columns with null values cannot be inserted into the database.
     */
    @Test
    public void testNullColumnConstraints() {
        /* Use a WeatherDbHelper to get access to a writable database */

        /* We need a cursor from a weather table query to access the column names */
        Cursor weatherTableCursor = database.query(
                REFLECTED_TABLE_NAME,
                /* We don't care about specifications, we just want the column names */
                null, null, null, null, null, null);

        /* Store the column names and close the cursor */
        String[] weatherTableColumnNames = weatherTableCursor.getColumnNames();
        weatherTableCursor.close();

        /* Obtain weather values from TestUtilities and make a copy to avoid altering singleton */
        ContentValues testValues = TestUtilities.createTestWeatherContentValues();
        /* Create a copy of the testValues to save as a reference point to restore values */
        ContentValues testValuesReferenceCopy = new ContentValues(testValues);

        for (String columnName : weatherTableColumnNames) {

            /* We don't need to verify the _ID column value is not null, the system does */
            if (columnName.equals(WeatherContract.WeatherEntry._ID)) continue;

            /* Set the value to null */
            testValues.putNull(columnName);

            /* Insert ContentValues into database and get a row ID back */
            long shouldFailRowId = database.insert(
                    REFLECTED_TABLE_NAME,
                    null,
                    testValues);

            String variableName = getConstantNameByStringValue(
                    WeatherContract.WeatherEntry.class,
                    columnName);

            /* If the insert fails, which it should in this case, database.insert returns -1 */
            String nullRowInsertShouldFail =
                    "Insert should have failed due to a null value for column: '" + columnName + "'"
                            + ", but didn't."
                            + "\n Check that you've added NOT NULL to " + variableName
                            + " in your create table statement in the WeatherEntry class."
                            + "\n Row ID: ";
            assertEquals(nullRowInsertShouldFail,
                    -1,
                    shouldFailRowId);

            /* "Restore" the original value in testValues */
            testValues.put(columnName, testValuesReferenceCopy.getAsDouble(columnName));
        }

        /* Close database */
        dbHelper.close();
    }
 
Example 19
Source File: CursorUtils.java    From Android-ORM with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> List<T> getFromCursor(Cursor c, Criteria criteria) {
    ArrayList<T> list = new ArrayList<>();
    if (c == null) {
        return list;
    }
    String[] colNames = c.getColumnNames();
    int[] indices = new int[colNames.length];
    Field[] objMethod = new Field[colNames.length];
    // field type class, used in getter invoked.
    // Class<?>[] fieldClass = new Class<?>[colNames.length];
    int[] types = new int[colNames.length];
    
    Class<?> objClass = criteria.getRoot().getClazz();
    String objAlias = criteria.getRoot().getAlias();
    Object obj = null;
    try {
        for (int i = 0; i < colNames.length; i++) {
            indices[i] = c.getColumnIndex(colNames[i]);
            Field m = getObjField(colNames[i], objClass, objAlias);
            if (m != null) {
                objMethod[i] = m;
                // fieldClass[i] = objMethod[i].getType();
                types[i] = getColumnType(objMethod[i].getType());
            }
        }
        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
            obj = objClass.newInstance();
            for (int i = 0; i < indices.length; i++) {
                if (objMethod[i] != null) {
                    if (objMethod[i].isAccessible()) {
                        objMethod[i].setAccessible(true);
                    }
                    objMethod[i].set(obj,
                            getColumnValue(c, indices[i], types[i]));
                }
            }
            list.add((T)obj);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    c.close();
    return list;
}
 
Example 20
Source File: TestSunshineDatabase.java    From android-dev-challenge with Apache License 2.0 4 votes vote down vote up
/**
>>>>>>> a6840f1... S07.03-Exercise-ConflictResolutionPolicy
     * Tests the columns with null values cannot be inserted into the database.
     */
    @Test
    public void testNullColumnConstraints() {
        /* Use a WeatherDbHelper to get access to a writable database */

        /* We need a cursor from a weather table query to access the column names */
        Cursor weatherTableCursor = database.query(
                REFLECTED_TABLE_NAME,
                /* We don't care about specifications, we just want the column names */
                null, null, null, null, null, null);

        /* Store the column names and close the cursor */
        String[] weatherTableColumnNames = weatherTableCursor.getColumnNames();
        weatherTableCursor.close();

        /* Obtain weather values from TestUtilities and make a copy to avoid altering singleton */
        ContentValues testValues = TestUtilities.createTestWeatherContentValues();
        /* Create a copy of the testValues to save as a reference point to restore values */
        ContentValues testValuesReferenceCopy = new ContentValues(testValues);

        for (String columnName : weatherTableColumnNames) {

            /* We don't need to verify the _ID column value is not null, the system does */
            if (columnName.equals(WeatherContract.WeatherEntry._ID)) continue;

            /* Set the value to null */
            testValues.putNull(columnName);

            /* Insert ContentValues into database and get a row ID back */
            long shouldFailRowId = database.insert(
                    REFLECTED_TABLE_NAME,
                    null,
                    testValues);

            String variableName = getConstantNameByStringValue(
                    WeatherContract.WeatherEntry.class,
                    columnName);

            /* If the insert fails, which it should in this case, database.insert returns -1 */
            String nullRowInsertShouldFail =
                    "Insert should have failed due to a null value for column: '" + columnName + "'"
                            + ", but didn't."
                            + "\n Check that you've added NOT NULL to " + variableName
                            + " in your create table statement in the WeatherEntry class."
                            + "\n Row ID: ";
            assertEquals(nullRowInsertShouldFail,
                    -1,
                    shouldFailRowId);

            /* "Restore" the original value in testValues */
            testValues.put(columnName, testValuesReferenceCopy.getAsDouble(columnName));
        }

        /* Close database */
        dbHelper.close();
    }