List of usage examples for android.database Cursor getType
int getType(int columnIndex);
From source file:com.android.contacts.common.model.ContactLoader.java
private void cursorColumnToContentValues(Cursor cursor, ContentValues values, int index) { switch (cursor.getType(index)) { case Cursor.FIELD_TYPE_NULL: // don't put anything in the content values break;/*from w w w. j a v a2 s . com*/ case Cursor.FIELD_TYPE_INTEGER: values.put(ContactQuery.COLUMNS[index], cursor.getLong(index)); break; case Cursor.FIELD_TYPE_STRING: values.put(ContactQuery.COLUMNS[index], cursor.getString(index)); break; case Cursor.FIELD_TYPE_BLOB: values.put(ContactQuery.COLUMNS[index], cursor.getBlob(index)); break; default: throw new IllegalStateException("Invalid or unhandled data type"); } }
From source file:com.digicorp.plugin.sqlitePlugin.SQLitePlugin.java
/** * Convert results cursor to JSON string. * * @param cur//from ww w . j a v a2 s . com * Cursor into query results * * @return results in string form * */ @SuppressLint("NewApi") private String results2string(Cursor cur) { String result = "[]"; // If query result has rows if (cur.moveToFirst()) { JSONArray fullresult = new JSONArray(); String key = ""; int colCount = cur.getColumnCount(); // Build up JSON result object for each row do { JSONObject row = new JSONObject(); try { for (int i = 0; i < colCount; ++i) { key = cur.getColumnName(i); // for old Android SDK remove lines from HERE: if (android.os.Build.VERSION.SDK_INT >= 11) { switch (cur.getType(i)) { case Cursor.FIELD_TYPE_NULL: row.put(key, null); break; case Cursor.FIELD_TYPE_INTEGER: row.put(key, cur.getInt(i)); break; case Cursor.FIELD_TYPE_FLOAT: row.put(key, cur.getFloat(i)); break; case Cursor.FIELD_TYPE_STRING: row.put(key, cur.getString(i)); break; case Cursor.FIELD_TYPE_BLOB: row.put(key, new String(Base64.encode(cur.getBlob(i), Base64.DEFAULT))); break; } } else // to HERE. { row.put(key, cur.getString(i)); } } fullresult.put(row); } catch (JSONException e) { e.printStackTrace(); } } while (cur.moveToNext()); result = fullresult.toString(); } return result; }
From source file:com.zetaDevelopment.phonegap.plugin.sqlitePlugin.SQLitePlugin.java
/** * Convert results cursor to JSON string. * * @param cur//from w w w . ja va2 s. c o m * Cursor into query results * * @return results in string form * */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) private String results2string(Cursor cur) { String result = "[]"; // If query result has rows if (cur.moveToFirst()) { JSONArray fullresult = new JSONArray(); String key = ""; int colCount = cur.getColumnCount(); // Build up JSON result object for each row do { JSONObject row = new JSONObject(); try { for (int i = 0; i < colCount; ++i) { key = cur.getColumnName(i); // for old Android SDK remove lines from HERE: if (android.os.Build.VERSION.SDK_INT >= 11) { switch (cur.getType(i)) { case Cursor.FIELD_TYPE_NULL: row.put(key, null); break; case Cursor.FIELD_TYPE_INTEGER: row.put(key, cur.getInt(i)); break; case Cursor.FIELD_TYPE_FLOAT: row.put(key, cur.getFloat(i)); break; case Cursor.FIELD_TYPE_STRING: row.put(key, cur.getString(i)); break; case Cursor.FIELD_TYPE_BLOB: //row.put(key, cur.getBlob(i)); row.put(key, new String(Base64.encode(cur.getBlob(i), Base64.DEFAULT))); break; } } else // to HERE. { row.put(key, cur.getString(i)); } } fullresult.put(row); } catch (JSONException e) { e.printStackTrace(); } } while (cur.moveToNext()); result = fullresult.toString(); } return result; }
From source file:com.triarc.sync.SyncAdapter.java
@SuppressLint("NewApi") private JSONObject getVersions(SyncType type, SyncTypeCollection collection, MutableBoolean hasUpdates) { JSONObject changeSet = new JSONObject(); JSONArray entityVersions = new JSONArray(); SQLiteDatabase openDatabase = null;/*from w ww. j a va 2 s . co m*/ Cursor query = null; try { changeSet.put("entityVersions", entityVersions); openDatabase = openDatabase(collection); query = openDatabase.query(type.getName(), new String[] { "_id", "_timestamp", "__internalTimestamp", "__state" }, null, null, null, null, "__internalTimestamp ASC"); while (query.moveToNext()) { syncResult.stats.numEntries++; JSONObject jsonObject = new JSONObject(); int fieldType = query.getType(0); String id = query.getString(0); String queryId = this.getQueryId(fieldType, id); jsonObject.put("id", id); jsonObject.put("timestamp", query.getLong(1)); jsonObject.put("clientTimestamp", query.getLong(2)); int state = query.getInt(3); if (state != UNCHANGED) { hasUpdates.setValue(true); } if (state == ADDED || state == UPDATED) { appendEntity(type, openDatabase, jsonObject, queryId); } jsonObject.put("state", state); entityVersions.put(jsonObject); } } catch (Exception e) { syncResult.stats.numIoExceptions++; syncResult.stats.numSkippedEntries++; syncResult.databaseError = true; e.printStackTrace(); sendLogs(); } finally { if (query != null) query.close(); if (openDatabase != null && openDatabase.isOpen()) closeDb(collection.getName()); } return changeSet; }
From source file:android.support.content.InMemoryCursor.java
/** * @param cursor source of data to copy. Ownership is reserved to the called, meaning * we won't ever close it. *///from w w w.j av a 2 s. c o m InMemoryCursor(Cursor cursor, int offset, int length, int disposition) { checkArgument(offset < cursor.getCount()); // NOTE: The cursor could simply be saved to a field, but we choose to wrap // in a dedicated relay class to avoid hanging directly onto a reference // to the cursor...so future authors are not enticed to think there's // a live link between the delegate cursor and this cursor. mObserverRelay = new ObserverRelay(cursor); mColumnNames = cursor.getColumnNames(); mRowCount = Math.min(length, cursor.getCount() - offset); int numColumns = cursor.getColumnCount(); mExtras = ContentPager.buildExtras(cursor.getExtras(), cursor.getCount(), disposition); mColumnType = new int[numColumns]; mTypedColumnIndex = new int[NUM_TYPES][numColumns]; mColumnTypeCount = new int[NUM_TYPES]; if (!cursor.moveToFirst()) { throw new RuntimeException("Can't position cursor to first row."); } for (int col = 0; col < numColumns; col++) { int type = cursor.getType(col); mColumnType[col] = type; mTypedColumnIndex[type][col] = mColumnTypeCount[type]++; } mLongs = new long[mRowCount * mColumnTypeCount[FIELD_TYPE_INTEGER]]; mDoubles = new double[mRowCount * mColumnTypeCount[FIELD_TYPE_FLOAT]]; mBlobs = new byte[mRowCount * mColumnTypeCount[FIELD_TYPE_BLOB]][]; mStrings = new String[mRowCount * mColumnTypeCount[FIELD_TYPE_STRING]]; for (int row = 0; row < mRowCount; row++) { if (!cursor.moveToPosition(offset + row)) { throw new RuntimeException("Unable to position cursor."); } // Now copy data from the row into primitive arrays. for (int col = 0; col < mColumnType.length; col++) { int type = mColumnType[col]; int position = getCellPosition(row, col, type); switch (type) { case FIELD_TYPE_NULL: throw new UnsupportedOperationException("Not implemented."); case FIELD_TYPE_INTEGER: mLongs[position] = cursor.getLong(col); break; case FIELD_TYPE_FLOAT: mDoubles[position] = cursor.getDouble(col); break; case FIELD_TYPE_BLOB: mBlobs[position] = cursor.getBlob(col); break; case FIELD_TYPE_STRING: mStrings[position] = cursor.getString(col); break; } } } }
From source file:com.odoo.orm.OModel.java
/** * Creates the record row.//from w w w .ja v a 2 s . c o m * * @param column * the column * @param cr * the cr * @return the object */ public Object createRecordRow(OColumn column, Cursor cr) { Object value = false; if (column.getDefaultValue() != null) { value = column.getDefaultValue(); } int index = cr.getColumnIndex(column.getName()); switch (cr.getType(index)) { case Cursor.FIELD_TYPE_NULL: value = false; break; case Cursor.FIELD_TYPE_STRING: value = cr.getString(index); break; case Cursor.FIELD_TYPE_INTEGER: value = cr.getInt(index); break; case Cursor.FIELD_TYPE_FLOAT: value = cr.getFloat(index); break; case Cursor.FIELD_TYPE_BLOB: value = cr.getBlob(index); break; } return value; }
From source file:com.clough.android.androiddbviewer.ADBVApplication.java
@Override public void onCreate() { super.onCreate(); // Getting user configured(custom) SQLiteOpenHelper instance. sqliteOpenHelper = getDataBase();//w w w . j av a 2 s . co m // getDataBase() could return a null if (sqliteOpenHelper != null) { // Background operation of creating the server socket. new Thread(new Runnable() { @Override public void run() { try { // Server socket re create when device is being disconnected or // when AndroidDBViewer desktop application is being closed. // Creating server socket will exit when // android application runs in low memory or when // android application being terminated due some reasons. l1: while (flag) { serverSocket = new ServerSocket(1993); socket = serverSocket.accept(); br = new BufferedReader(new InputStreamReader(socket.getInputStream())); pw = new PrintWriter(socket.getOutputStream(), true); // Keeps a continuous communication between android application and // AndroidDBViewer desktop application through IO streams of the accepted socket connection. // There will be continuous data parsing between desktop application and android application. // Identification of device being disconnected or desktop application being closed will be determined // only when there is a NULL data being received. l2: while (flag) { // Format of the parsing data string is JSON, a content of a 'Data' instance String requestJSONString = br.readLine(); if (requestJSONString == null) { // Received a null response from desktop application, due to disconnecting the // device or closing the AndroidDBViewer desktop application. // Therefore, closing all current connections and streams to re create the server // socket so that desktop application can connect in it's next run. // Device disconnection doesn't produce an IOException. // Also, even after calling // socket.close(), socket.shutdownInput() and socket.shutdownOutput() // within a shutdown hook in desktop application, the socket connection // in this async task always gives // socket.isConnected() as 'true' , // socket.isClosed() as 'false' , // socket.isInputShutdown() as 'false' and // socket.isOutputShutdown() as 'false' . // But, bufferedReader.readLine() starts returning 'null' continuously. // So, inorder to desktop application to connect with the device again, // there should be a ServerSocket waiting to accept a socket connection, in device. closeConnection(); continue l1; } else { // Received a valid response from the desktop application. Data data; try { // Converting received request to a 'Data' instance. data = new Data(new JSONObject(requestJSONString)); int status = data.getStatus(); if (status == Data.CONNECTION_REQUEST) { // Very first request from desktop application to // establish the connection and setting the response as // connection being accepted. data.setStatus(Data.CONNECTION_ACCEPTED); } else if (status == Data.LIVE_CONNECTION) { // When there is no user interaction in desktop application, // data being passed from desktop application to android // application with the status of LIVE_CONNECTION, and the // same data send again to the desktop application from android application, // to notify that connection is still alive. // This exchange won't change until there is a request from // desktop application with a different status. } else if (status == Data.QUERY) { // Requesting to perform a query execution. String result = "No result"; try { // Performing select, insert, delete and update queries. Cursor cursor = sqliteOpenHelper.getWritableDatabase() .rawQuery(data.getQuery(), null); // Flag to identify the firs move of the cursor boolean firstTime = true; int columnCount = 0; // JSONArray to hold the all JSONObjects, created per every row // of the result returned, executing the given query. JSONArray jsonArray = new JSONArray(); // Moving the cursor to the next row of retrieved result // after executing the requested query. while (cursor.moveToNext()) { if (firstTime) { // Column count of the result returned, executing the given query. columnCount = cursor.getColumnCount(); firstTime = false; } // JOSNObject to hold the values of a single row JSONObject jsonObject = new JSONObject(); for (int i = 0; i < columnCount; i++) { int columnType = cursor.getType(i); String columnName = cursor.getColumnName(i); if (columnType == Cursor.FIELD_TYPE_STRING) { jsonObject.put(columnName, cursor.getString(i)); } else if (columnType == Cursor.FIELD_TYPE_BLOB) { jsonObject.put(columnName, cursor.getBlob(i).toString()); } else if (columnType == Cursor.FIELD_TYPE_FLOAT) { jsonObject.put(columnName, String.valueOf(cursor.getFloat(i))); } else if (columnType == Cursor.FIELD_TYPE_INTEGER) { jsonObject.put(columnName, String.valueOf(cursor.getInt(i))); } else if (columnType == Cursor.FIELD_TYPE_NULL) { jsonObject.put(columnName, "NULL"); } else { jsonObject.put(columnName, "invalid type"); } } jsonArray.put(jsonObject); } result = jsonArray.toString(); cursor.close(); } catch (Exception e) { // If SQL error is occurred when executing the requested query, // error content will be the response to the desktop application. StringWriter sw = new StringWriter(); PrintWriter epw = new PrintWriter(sw); e.printStackTrace(epw); result = sw.toString(); epw.close(); sw.close(); } finally { data.setResult(result); } } else if (status == Data.DEVICE_NAME) { // Requesting device information data.setResult(Build.BRAND + " " + Build.MODEL); } else if (status == Data.APPLICATION_ID) { // Requesting application id (package name) data.setResult(getPackageName()); } else if (status == Data.DATABASE_NAME) { // Requesting application database name. // Will provide the database name according // to the SQLiteOpenHelper user provided data.setResult(sqliteOpenHelper.getDatabaseName()); } else { // Unidentified request state. closeConnection(); continue l1; } String responseJSONString = data.toJSON().toString(); pw.println(responseJSONString); } catch (JSONException e) { // Response couldn't convert to a 'Data' instance. // Desktop application will be notified to close the application. closeConnection(); continue l1; } } } } } catch (IOException e) { // Cannot create a server socket. Letting background process to end. } } }).start(); } }
From source file:com.ruesga.timelinechart.TimelineChartView.java
private boolean isNumericColumnType(int columnIndex, Cursor c) { int type = c.getType(columnIndex); return type == Cursor.FIELD_TYPE_INTEGER || type == Cursor.FIELD_TYPE_FLOAT; }
From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java
/** * Return the data stored in the cursor at the given index and given position * (ie the given row which the cursor is currently on) as null OR a String. * <p>/*from w ww . j a v a 2s. co m*/ * NB: Currently only checks for Strings, long, int, and double. * * @param c * @param i * @return */ @SuppressLint("NewApi") public String getIndexAsString(Cursor c, int i) { // If you add additional return types here be sure to modify the javadoc. if (i == -1) return null; if (c.isNull(i)) { return null; } switch (c.getType(i)) { case Cursor.FIELD_TYPE_STRING: return c.getString(i); case Cursor.FIELD_TYPE_FLOAT: return Double.toString(c.getDouble(i)); case Cursor.FIELD_TYPE_INTEGER: return Long.toString(c.getLong(i)); case Cursor.FIELD_TYPE_NULL: return c.getString(i); default: case Cursor.FIELD_TYPE_BLOB: throw new IllegalStateException("Unexpected data type in SQLite table"); } }
From source file:osu.appclub.corvallisbus.MainActivity.java
@Override public void searchComplete(Cursor cursor) { Log.d("osu.appclub", "Found " + cursor.getCount() + " results"); if (cursor.getCount() == 0) { MatrixCursor placeholder = new MatrixCursor(new String[] { "_id" }); placeholder.addRow(new Object[] { 0 }); searchView.setSuggestionsAdapter(new CursorAdapter(this, placeholder, false) { @Override//from w w w . j a v a 2 s . c o m public View newView(Context context, Cursor cursor, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(android.R.layout.simple_list_item_1, parent, false); return view; } @Override public void bindView(View view, Context context, Cursor cursor) { TextView text = (TextView) view.findViewById(android.R.id.text1); text.setText(R.string.search_no_results); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // no-op } }); } }); } else { searchView.setSuggestionsAdapter(new CursorAdapter(this, cursor, false) { @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(android.R.layout.simple_list_item_2, parent, false); return view; } @SuppressLint("DefaultLocale") @Override public void bindView(View view, Context context, Cursor cursor) { final int stopID = cursor.getInt(0); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { searchView.clearFocus(); enqueueBusStop(stopID); } }); TextView textStopName = (TextView) view.findViewById(android.R.id.text1); textStopName.setText(cursor.getString(1)); TextView textDistance = (TextView) view.findViewById(android.R.id.text2); if (cursor.getType(2) == Cursor.FIELD_TYPE_NULL) { textDistance.setText(""); } else { textDistance.setText(String.format("%.1f miles", cursor.getDouble(2))); } } }); } }