public JSONArray getJSON() { SQLiteDatabase database = databaseHelper.getReadableDatabase(); Cursor cursor = database.query(getTableName(), null, null, null, null, null, null); if (cursor == null) return null; JSONArray resultSet = new JSONArray(); try { cursor.moveToFirst(); while (cursor.isAfterLast() == false) { int totalColumn = cursor.getColumnCount(); JSONObject rowObject = new JSONObject(); for (int i = 0; i < totalColumn; i++) { if (cursor.getColumnName(i) != null) { try { if (cursor.getString(i) != null) rowObject.put(cursor.getColumnName(i), cursor.getString(i)); else rowObject.put(cursor.getColumnName(i), ""); } catch (Exception e) { } } } resultSet.put(rowObject); cursor.moveToNext(); } cursor.close(); } finally { cursor.close(); } return resultSet; }
public void delete(final RecyclerView.ViewHolder viewHolder) { final Context context = viewHolder.itemView.getContext(); final int pos = viewHolder.getAdapterPosition(); mCursor.moveToPosition(pos); final long remId = mCursor.getLong(PredictionsProvider.Util.INDEX_ID); final String question = mCursor.getString(PredictionsProvider.Util.INDEX_QUESTION); final ContentValues predValues = new ContentValues(); for (int i = 0; i < mCursor.getColumnCount(); i++) { switch (mCursor.getType(i)) { case Cursor.FIELD_TYPE_INTEGER: predValues.put(mCursor.getColumnName(i), mCursor.getLong(i)); break; case Cursor.FIELD_TYPE_FLOAT: predValues.put(mCursor.getColumnName(i), mCursor.getDouble(i)); break; case Cursor.FIELD_TYPE_STRING: predValues.put(mCursor.getColumnName(i), mCursor.getString(i)); break; case Cursor.FIELD_TYPE_BLOB: predValues.put(mCursor.getColumnName(i), mCursor.getBlob(i)); break; default: // null } } new AsyncTask<Void, Void, Boolean>() { @Override protected Boolean doInBackground(Void... params) { return PredictionsProvider.Util.removePrediction(context, remId); } @Override protected void onPostExecute(Boolean removed) { if (!removed) return; expanded.remove(remId); notifyItemRemoved(pos); String msg = context.getString(R.string.prediction_dismiss_snackbar_delete, question); Snackbar.make(viewHolder.itemView, msg, Snackbar.LENGTH_LONG) .setAction( R.string.prediction_dismiss_snackbar_undo, new View.OnClickListener() { @Override public void onClick(View v) { new AsyncTask<Void, Void, Uri>() { @Override protected Uri doInBackground(Void... params) { return context .getContentResolver() .insert(PredictionsContract.PredictionEntry.CONTENT_URI, predValues); } }.execute(); } }) .show(); } }.execute(); }
public static ArrayList<MediaBean> getVersions(Context ctx, String PlayId, String htmlId) { ArrayList<MediaBean> list = new ArrayList<MediaBean>(); Cursor cursor = ctx.getContentResolver() .query( Uri.withAppendedPath( MoverContentProvider.CONTENT_URI, MoverContentProvider.MEDIA_PATH), null, null, null, null); /// .query(MoverContentProvider.CONTENT_URI+"/"+MoverContentProvider.PLAY_PATH, null, null, // null, null); if (cursor != null && cursor.getCount() > 0) { setColumns(cursor); for (int i = 0; i < cursor.getCount(); i++) { cursor.moveToPosition(i); MediaBean media = new MediaBean(); media.setMediaID(cursor.getColumnName(COLUMN_INDEX_MEDIA_ID)); media.setMediaName(cursor.getColumnName(COLUMN_INDEX_MEDIA_NAME)); list.add(media); } } cursor.close(); return list; }
@Override public void bindView(View view, Context context, Cursor cursor) { // here we are setting our data // that means, take the data from the cursor and put it in views TextView textViewPersonName = (TextView) view.findViewById(R.id.tv_activity_name); textViewPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1)))); TextView textViewPersonPIN = (TextView) view.findViewById(R.id.tv_activity_group); textViewPersonPIN.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(2)))); }
public ChapterItem getChapter(String idChapter) throws SQLException { ChapterItem chapterItem = new ChapterItem(idChapter); Cursor cursor = mDatabase.query( true, DATABASE_CHAPTERS_TABLE, CHAPTER_FIELDS, KEY_ID_CHAPTER + " = '" + idChapter + "'", null, null, null, null, null); if (cursor.moveToFirst()) { chapterItem.setYtChapterId(cursor.getString(1)); chapterItem.setYtPlaylistId(cursor.getString(2)); chapterItem.setTitle(cursor.getString(3)); chapterItem.setDescription(cursor.getColumnName(4)); chapterItem.setThumbnailUrl(cursor.getString(5)); chapterItem.setDuration(cursor.getInt(6)); chapterItem.setCurrentTimepoint(cursor.getInt(7)); chapterItem.setPercentageSeen(cursor.getInt(8)); cursor.close(); } return chapterItem; }
Schema createSchema(FeatureEntry entry) { log(format("SELECT * FROM %s LIMIT 1", entry.getTableName())); Cursor c = db.query(entry.getTableName(), null, null, null, null, null, null, "1"); c.moveToNext(); SchemaBuilder sb = Schema.build(entry.getTableName()); for (int i = 0; i < c.getColumnCount(); i++) { String col = c.getColumnName(i); if (col.equals(entry.getGeometryColumn())) { CoordinateReferenceSystem crs = entry.getSrid() != null ? Proj.crs(entry.getSrid()) : null; sb.field(col, entry.getGeometryType().getType(), crs); } else { Class type = null; switch (c.getType(i)) { case Cursor.FIELD_TYPE_INTEGER: type = Integer.class; break; case Cursor.FIELD_TYPE_FLOAT: type = Double.class; break; case Cursor.FIELD_TYPE_BLOB: type = byte[].class; break; default: type = String.class; } sb.field(col, type); } } return sb.schema(); }
/** * 查找包含会议材料的列表 * * @param context * @param pageSize * @param pageIndex * @return */ public static HashMap<String, Object> selectDateList( Context context, int pageSize, int pageIndex) { HashMap<String, Object> hm = new HashMap<String, Object>(); SQLiteDatabase db = new DatabaseHelper(context, SaveData.getInstance().getUserCode()).getWritableDatabase(); // 查找总条数 int RecordCount = db.rawQuery("select * from NoticeList where DataSum <> '0'", null).getCount(); hm.put("RecordCount", RecordCount); int from = pageSize * (pageIndex - 1); // System.out.println("from = " + from + "->to:" + pageSize); Cursor mCursor = db.rawQuery( "select * from NoticeList where DataSum <> '0' LIMIT " + from + "," + pageSize, null); ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(); int count = mCursor.getColumnCount(); while (mCursor.moveToNext()) { HashMap<String, String> map = new HashMap<String, String>(); for (int i = 0; i < count; i++) { map.put(mCursor.getColumnName(i), mCursor.getString(i)); } list.add(map); } hm.put("List", list); return hm; }
/** * 将游标结果集转成指定类名的列表 * * @param cursor 游标 * @param className 类名(完全路径:包名+类名) * @return */ @SuppressWarnings("unchecked") protected <E> List<E> cursorToList(Cursor cursor, Class<E> cls) { List<E> rs = new ArrayList<E>(); if (!BaseUtil.isEmpty(cursor)) { int count = cursor.getCount(); // 游标移动到第一条记录 cursor.moveToFirst(); int columnCount = cursor.getColumnCount(); for (int i = 0; i < count; i++) { if (cls == null) { BaseDaoBean bean = new BaseDaoBean(); for (int j = 0; j < columnCount; j++) { bean.put(cursor.getColumnName(j), cursor.getString(j)); } rs.add((E) bean); } else { try { E obj = cls.newInstance(); for (int j = 0; j < columnCount; j++) { setAttributeValue(obj, j, cursor); } rs.add(obj); } catch (Exception e) { Log.e(TAG, "数据转换失败"); break; } } cursor.moveToNext(); } } return rs; }
/** * 把Cursor中的所有元素转换成String * * @param mCursor * @return */ public static String toString(Cursor mCursor) { String str = ""; if (mCursor == null) { str = "cursor is null pointer"; } else { final String _n = "\n", _t = "\t"; int coloumnCount = mCursor.getColumnCount(); int rowCount = mCursor.getCount(); str = coloumnCount + "列" + rowCount + "行\n序号"; for (int i = 0; i < coloumnCount; i++) { str += _t + mCursor.getColumnName(i); } // String coloumnNames[]=mCursor.getColumnNames(); // for(String name:coloumnNames){ // str+="\t "+name; // } if (mCursor.moveToFirst()) { int currentRow = 0; do { str += _n + currentRow; for (int j = 0; j < coloumnCount; j++) { str += _t + mCursor.getString(j); } currentRow++; } while (mCursor.moveToNext()); } } return str; }
private Map<String, Integer> getColMap(Cursor c) { Map<String, Integer> m = new HashMap<String, Integer>(); for (int i = 0; i < c.getColumnCount(); i++) { m.put(c.getColumnName(i).toUpperCase(), i); } return m; }
public CallObserver(Context context, Cursor cursor, Handler handler) { super(handler); this.cursor = cursor; this.context = context; Log.i(TAG, "num of rows" + cursor.getCount()); Log.i(TAG, "number of column" + cursor.getColumnCount()); for (int i = 0; i < cursor.getColumnCount(); i++) { Log.i(TAG, "column name " + i + ' ' + cursor.getColumnName(i)); } }
public static DbModel getDbModel(final Cursor cursor) { DbModel result = null; if (cursor != null) { result = new DbModel(); int columnCount = cursor.getColumnCount(); for (int i = 0; i < columnCount; i++) { result.add(cursor.getColumnName(i), cursor.getString(i)); } } return result; }
@Override public void bindView(View view, Context context, Cursor cursor) { // here we are setting our data // that means, take the data from the cursor and put it in views TextView code = (TextView) view.findViewById(R.id.txtCodel); TextView title = (TextView) view.findViewById(R.id.txtTitle); TextView lessontime = (TextView) view.findViewById(R.id.txtTimes); TextView teacher = (TextView) view.findViewById(R.id.txtTeacher); TextView location = (TextView) view.findViewById(R.id.txtLocation); TextView txtPm = (TextView) view.findViewById(R.id.textView1); TextView color = (TextView) view.findViewById(R.id.txtcolor); code.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(3)))); title.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(4)))); teacher.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(8)))); location.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(9)))); color.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(7)))); Typeface font = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Light.ttf"); Typeface font_a = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Medium.ttf"); Typeface font_b = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Regular.ttf"); Typeface font_c = Typeface.createFromAsset(context.getAssets(), "fonts/DistProTh.otf"); Typeface font_d = Typeface.createFromAsset(context.getAssets(), "fonts/DroidSans.ttf"); code.setTypeface(font_b); lessontime.setTypeface(font_c); title.setTypeface(font_a); teacher.setTypeface(font_b); location.setTypeface(font_b); txtPm.setTypeface(font_b); String startTime = cursor.getString(cursor.getColumnIndex(cursor.getColumnName(5))); String endTime = cursor.getString(cursor.getColumnIndex(cursor.getColumnName(6))); String pn = "am"; double a = Float.parseFloat(startTime) / 100; double c = Float.parseFloat(endTime) / 100; if (a > 12) { // pn="am"; txtPm.setText(pn); a = a - 12; if (a < 1) a = a + 1; } if (c > 12) { pn = "pm"; txtPm.setText(pn); c = c - 12; if (c < 0.59) c = c + 1; } else { pn = "am"; txtPm.setText(pn); } String m = df.format(a) + "-" + df.format(c); m = m.replaceAll("[.]", ":"); lessontime.setText(m); }
private void cursorLog(Cursor cursor) { while (cursor.moveToNext()) { StringBuilder stb = new StringBuilder(); for (int i = 0; i < cursor.getColumnCount(); i++) { stb.append(cursor.getColumnName(i).toString()); stb.append(":"); stb.append(cursor.getString(i)); cursor.getString(i); } Log.e("log", stb.toString()); } }
/** * 解析数据 * * @param <T> 对象 * @param cursor 游标 * @param cls 类对象 * @param columns 查询参数 * @param data 数据 */ private <T> void parserData(Cursor cursor, Class<T> cls, List<T> data) { while (cursor.moveToNext()) { T t = null; try { t = cls.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } if (t != null) { for (int i = 0; i < cursor.getColumnNames().length; i++) { try { Field field = cls.getField(trim(cursor.getColumnNames()[i])); Object obj = field.get(t); if (obj instanceof String) { field.set( t, cursor.getString(cursor.getColumnIndexOrThrow(cursor.getColumnNames()[i]))); } else if (obj instanceof Integer) { field.set(t, cursor.getInt(cursor.getColumnIndexOrThrow(cursor.getColumnNames()[i]))); } else if (obj instanceof Double) { field.set( t, cursor.getDouble(cursor.getColumnIndexOrThrow(cursor.getColumnNames()[i]))); } else if (obj instanceof Long) { field.set(t, cursor.getLong(cursor.getColumnIndexOrThrow(cursor.getColumnName(i)))); } else if (obj instanceof Boolean) { field.set( t, cursor.getInt(cursor.getColumnIndexOrThrow(cursor.getColumnNames()[i])) == 0 ? false : true); } else { field.set( t, cursor.getString(cursor.getColumnIndexOrThrow(cursor.getColumnNames()[i]))); } } catch (NoSuchFieldException e) { e.printStackTrace(); continue; } catch (IllegalArgumentException e) { e.printStackTrace(); continue; } catch (IllegalAccessException e) { e.printStackTrace(); continue; } } data.add(t); } } }
public List<ModelInterface> getAllPictures(ContentResolver contentResolver) { List<ModelInterface> returnList = new ArrayList<ModelInterface>(); Cursor cursor = contentResolver.query( Pictures.CONTENT_URI, null, Pictures.PICTURE_ID + " IS NOT null", null, null); if (cursor.moveToFirst()) { do { long id = 0; byte[] picture = null; for (int i = 0; i < cursor.getColumnCount(); i++) { if (cursor.getColumnName(i).equalsIgnoreCase(Pictures.PICTURE_ID)) { id = cursor.getInt(i); } else if (cursor.getColumnName(i).equalsIgnoreCase(Pictures.PICTURE)) { picture = cursor.getBlob(i); } } PictureModel pic = new PictureModel(id, picture); returnList.add(pic); } while (cursor.moveToNext()); } cursor.close(); return returnList; }
public void delete(ContentResolver contentResolver, PictureModel pic) { Cursor cursor = contentResolver.query( Pictures.CONTENT_URI, null, Pictures.PICTURE_ID + " IS NOT null", null, null); cursor.moveToFirst(); int id = 0; for (int i = 0; i < cursor.getColumnCount(); i++) { if (cursor.getColumnName(i).equalsIgnoreCase(Pictures.PICTURE_ID)) { id = cursor.getInt(i); } } contentResolver.delete( Pictures.CONTENT_URI, Pictures.PICTURE_ID + " = " + Long.toString(id), null); }
public static void displayCursor(Cursor cursor, boolean close, String title) { cursor.moveToFirst(); while (!cursor.isAfterLast()) { int columnCount = cursor.getColumnCount(); String row = ""; for (int i = 0; i < columnCount; i++) { if (!row.equals("")) row += ", "; row += cursor.getColumnName(i) + ": " + cursor.getString(i); } Log.d("DisplayCursor(" + title + ")", row); cursor.moveToNext(); } if (close) cursor.close(); }
public BinList query(String sql, String[] selectionArgs) { this.connection(); BinList list = new BinList(); Cursor cursor = this.db.rawQuery(sql, selectionArgs); int j = 0; while (cursor.moveToNext()) { for (int i = 0; i < cursor.getColumnCount(); i++) { list.put(j, cursor.getColumnName(i).toString(), cursor.getString(i)); } j++; } cursor.close(); this.close(); return list; }
/** * Show all rows of a particular {@link Uri}. * * @param context {@link Context} * @param u {@link Uri} */ static void showRows(final Context context, final Uri u) { Log.d(TAG, "-----GET HEADERS-----"); Log.d(TAG, "-- " + u.toString() + " --"); Cursor c = context.getContentResolver().query(u, null, null, null, null); if (c != null) { int l = c.getColumnCount(); StringBuilder buf = new StringBuilder(); for (int i = 0; i < l; i++) { buf.append(i + ":"); buf.append(c.getColumnName(i)); buf.append(" | "); } Log.d(TAG, buf.toString()); } }
/** * 查询所有需要提醒开会的通知 * * @param context */ public static ArrayList<HashMap<String, String>> selectIsWarn(Context context) { SQLiteDatabase db = new DatabaseHelper(context, SaveData.getInstance().getUserCode()).getWritableDatabase(); Cursor mCursor = db.rawQuery("select * from NoticeList where IsWarn = 'true'", null); ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(); int count = mCursor.getColumnCount(); while (mCursor.moveToNext()) { HashMap<String, String> map = new HashMap<String, String>(); for (int i = 0; i < count; i++) { map.put(mCursor.getColumnName(i), mCursor.getString(i)); } list.add(map); } return list; }
public List<Map<String, String>> cursor2List(Cursor cursor) { List<Map<String, String>> list = new ArrayList<Map<String, String>>(); int cols_len = cursor.getColumnCount(); while (cursor.moveToNext()) { Map<String, String> map = new HashMap<String, String>(); for (int i = 0; i < cols_len; i++) { String cols_name = cursor.getColumnName(i); String cols_values = cursor.getString(i); if (cols_values == null) { cols_values = ""; } map.put(cols_name, cols_values); } list.add(map); } return list; }
@Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { if (view instanceof TextView && Weaves.Columns.LAST_MODIFIED.equals(cursor.getColumnName(columnIndex))) { TextView tview = (TextView) view; long theDateLong = cursor.getLong(columnIndex); Date theDate = new Date(theDateLong * 1000); // GregorianCalendar sm_gregorianCalendar = new GregorianCalendar(); // sm_gregorianCalendar.setTimeInMillis(theDateLong); String dateStr = m_dateFormat.format(theDate); // String dateStr = "" + theDate.toString(); // String dateStr = "" + theDateLong; tview.setText(dateStr); return true; } return false; }
public static void dumpCursor(String title, Cursor cursor) { if (cursor == null) { Log.w(title + ": No Results returned"); return; } Log.w(title + ": " + cursor.getCount() + " row returned"); if (cursor.moveToFirst()) { do { Log.w("\n"); for (int ndx = 0; ndx < cursor.getColumnCount(); ndx++) { Log.w(" " + cursor.getColumnName(ndx) + " = " + cursor.getString(ndx)); } } while (cursor.moveToNext()); } }
private static String getDebugText(Cursor cursor) { final StringBuilder sb = new StringBuilder(); sb.append("APN ["); for (int i = 0; i < cursor.getColumnCount(); i++) { final String name = cursor.getColumnName(i); final String value = cursor.getString(i); if (TextUtils.isEmpty(value)) { continue; } if (i > 0) { sb.append(' '); } sb.append(name).append('=').append(value); } sb.append("]"); return sb.toString(); }
public static <T> T inflate(Cursor cursor, TableDetails tableDetails) { T dataModelObject; try { dataModelObject = (T) tableDetails.createNewModelInstance(); } catch (Exception ex) { throw new QuantumFluxException( "Could not create a new instance of data model object: " + tableDetails.getTableName()); } for (int i = 0; i < cursor.getColumnCount(); i++) { String columnName = cursor.getColumnName(i); TableDetails.ColumnDetails columnDetails = tableDetails.findColumn(columnName); inflateColumn(cursor, dataModelObject, columnDetails, i); } return dataModelObject; }
public boolean CursorMatches(Cursor c, ContentValues cv) { for (int i = 0; i < c.getColumnCount(); i++) { String column = c.getColumnName(i); if (cv.containsKey(column)) { mAsserter.info("Comparing", "Column values for: " + column); Object value = cv.get(column); if (value == null) { if (!c.isNull(i)) { return false; } } else { if (c.isNull(i) || !value.toString().equals(c.getString(i))) { return false; } } } } return true; }
@SuppressWarnings("unchecked") public static <T> T getEntity( final DbUtils db, final Cursor cursor, Class<T> entityType, long findCacheSequence) { if (db == null || cursor == null) return null; EntityTempCache.setSeq(findCacheSequence); try { Table table = Table.get(db, entityType); Id id = table.id; String idColumnName = id.getColumnName(); int idIndex = id.getIndex(); if (idIndex < 0) { idIndex = cursor.getColumnIndex(idColumnName); } Object idValue = id.getColumnConverter().getFieldValue(cursor, idIndex); T entity = EntityTempCache.get(entityType, idValue); if (entity == null) { entity = entityType.newInstance(); id.setValue2Entity(entity, cursor, idIndex); EntityTempCache.put(entityType, idValue, entity); } else { return entity; } int columnCount = cursor.getColumnCount(); for (int i = 0; i < columnCount; i++) { String columnName = cursor.getColumnName(i); Column column = table.columnMap.get(columnName); if (column != null) { column.setValue2Entity(entity, cursor, i); } } // init finder for (Finder finder : table.finderMap.values()) { finder.setValue2Entity(entity, null, 0); } return entity; } catch (Throwable e) { LogUtils.e(e.getMessage(), e); } return null; }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // открываем подключение к БД db = new DB(this); db.open(); // получаем курсор cursor = db.getAllData(); if (cursor.getCount() == 0) { fillData(); cursor = db.getAllData(); } startManagingCursor(cursor); lvData = (ListView) findViewById(R.id.listView1); cursor.moveToFirst(); itemArray = new ArrayList<String>(); Bitmap bitmap = null; for (int i = 0; i < cursor.getColumnCount(); i++) { if (!cursor.getColumnName(i).equals(DB.COLUMN_FOTO)) { itemArray.add(cursor.getString(i)); } else { bitmap = byteToImage(cursor.getBlob(i)); } } itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, itemArray); db.close(); ImageView ivFoto = new ImageView(this); if (bitmap != null) { ivFoto.setImageBitmap(bitmap); } lvData.addFooterView(ivFoto); lvData.setAdapter(itemAdapter); }
@Override public List<Map<String, String>> listCache(String selection, String[] selectionArgs) { // TODO Auto-generated method stub List<Map<String, String>> list = new ArrayList<Map<String, String>>(); SQLiteDatabase database = null; Cursor cursor = null; try { database = helper.getReadableDatabase(); cursor = database.query( false, SQLHelper.TABLE_CHANNEL, null, selection, selectionArgs, null, null, null, null); int cols_len = cursor.getColumnCount(); while (cursor.moveToNext()) { Map<String, String> map = new HashMap<String, String>(); for (int i = 0; i < cols_len; i++) { String cols_name = cursor.getColumnName(i); String cols_values = cursor.getString(cursor.getColumnIndex(cols_name)); if (cols_values == null) { cols_values = ""; } map.put(cols_name, cols_values); } list.add(map); } } catch (Exception e) { // TODO: handle exception } finally { if (database != null) { database.close(); } } return list; }