private JSONArray constructResponse(Cursor c, String parameters) throws JSONException {
   JSONObject params = new JSONObject(parameters);
   c.moveToFirst();
   String[] columnNames = c.getColumnNames();
   JSONArray json = new JSONArray();
   String addressFieldName = null;
   if (params.has("addressFieldName") && null != params.getString("addressFieldName")) {
     addressFieldName =
         CaseFormat.LOWER_UNDERSCORE.to(
             CaseFormat.LOWER_CAMEL, params.getString("addressFieldName"));
   }
   while ((!c.isAfterLast())) {
     JSONObject obj = new JSONObject();
     for (int i = 0; i < columnNames.length; i++) {
       if (columnNames[i].equals("birthdate")) {
         obj.put(
             "age", Years.yearsBetween(DateTime.parse(c.getString(i)), new DateTime()).getYears());
       } else if (params.has("addressFieldName") && columnNames[i].equals(addressFieldName)) {
         JSONObject address = new JSONObject();
         address.put(params.getString("addressFieldName"), c.getString(i));
         obj.put("addressFieldValue", address);
       } else if (params.has("extraIdentifiers") && columnNames[i].equals("extraIdentifiers")) {
         JSONObject extraIdentifiers = new JSONObject();
         extraIdentifiers.put("extraIdentifiers", c.getString(i));
         obj.put("extraIdentifiers", extraIdentifiers);
       } else {
         obj.put(columnNames[i], c.getString(i));
       }
     }
     json.put(obj);
     c.moveToNext();
   }
   c.close();
   return json;
 }
  // Visible for testing
  /* package */ static Cursor removeDuplicateDestinations(Cursor original) {
    final MatrixCursor result = new MatrixCursor(original.getColumnNames(), original.getCount());
    final HashSet<String> destinationsSeen = new HashSet<String>();

    original.moveToPosition(-1);
    while (original.moveToNext()) {
      final String destination = original.getString(Query.DESTINATION);
      if (destinationsSeen.contains(destination)) {
        continue;
      }
      destinationsSeen.add(destination);

      result.addRow(
          new Object[] {
            original.getString(Query.NAME),
            original.getString(Query.DESTINATION),
            original.getInt(Query.DESTINATION_TYPE),
            original.getString(Query.DESTINATION_LABEL),
            original.getLong(Query.CONTACT_ID),
            original.getLong(Query.DATA_ID),
            original.getString(Query.PHOTO_THUMBNAIL_URI),
            original.getInt(Query.DISPLAY_NAME_SOURCE)
          });
    }

    return result;
  }
Example #3
0
  /**
   * 从短信中获取信息,转换为meta列表
   *
   * @param context
   * @return
   */
  public List<Record> analysis(Context context) {
    init();
    Uri uriSMSURI = Uri.parse("content://sms/inbox");
    Cursor cur = context.getContentResolver().query(uriSMSURI, null, null, null, null);
    String[] test = cur.getColumnNames();
    for (int i = 0; i < test.length; i++) {
      Log.i(TAG, i + "," + test[i]);
    }
    Date date = new Date();
    List<Record> metaList = new ArrayList<Record>();
    while (cur.moveToNext()) {
      date.setTime(cur.getLong(4));
      String phoneNum = cur.getString(2);
      String content = cur.getString(12);

      Meta meta = generateMeta(date, phoneNum, content);
      if (meta != null) {
        if ("1065905710008396523".equals(phoneNum) || "1065905710008296523".equals(phoneNum)) {
          Log.i(TAG, content);
        }

        metaList.add(changeToRecord(meta));
      }
    }
    return metaList;
  }
 // 获取所有视频未读消息
 public List<HashMap<String, String>> getAllNotifyNoRead() {
   Cursor cursor = null;
   try {
     String sql =
         "select distinct "
             + TablesColumns.TABLENOTICE_ID
             + ","
             + TablesColumns.TABLENOTICE_SUBJECT
             + ","
             + TablesColumns.TABLENOTICE_SIGNAL
             + ","
             + TablesColumns.TABLENOTICE_CONTEXT
             + ","
             + TablesColumns.TABLENOTICE_USER
             + ","
             + TablesColumns.TABLENOTICE_ALERT
             + ","
             + TablesColumns.TABLENOTICE_OPERATOR
             + ","
             + TablesColumns.TABLENOTICE_CREATEDAT
             + ","
             + TablesColumns.TABLENOTICE_READAT
             + " from "
             + TablesColumns.TABLENOTICE
             + " where "
             + TablesColumns.TABLENOTICE_READAT
             + " = 'null' and "
             + TablesColumns.TABLENOTICE_SIGNAL
             + " in ('like','comment') ORDER BY "
             + TablesColumns.TABLENOTICE_CREATEDAT
             + " DESC";
     cursor = dataBase.rawQuery(sql, null);
     List<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
     HashMap<String, String> map;
     String[] names = cursor.getColumnNames();
     while (cursor.moveToNext()) {
       map = new HashMap<String, String>();
       for (String name : names) {
         map.put(name, cursor.getString(cursor.getColumnIndex(name)));
       }
       boolean isAlreadContain = false;
       for (HashMap<String, String> alMap : data) {
         if (alMap.containsValue(map.get(TablesColumns.TABLENOTICE_ID).toString())) {
           isAlreadContain = true;
           break;
         }
       }
       if (isAlreadContain) {
         continue;
       }
       data.add(map);
     }
     cursor.close();
     return data;
   } catch (Exception e) {
     return null;
   } finally {
     if (cursor != null) cursor.close();
   }
 }
Example #5
0
  public synchronized List<String[]> queryWithArgs(String sql, String[] vArgs) throws Throwable {
    Cursor cursor = null;
    SQLiteDatabase database = null;
    List<String[]> ret = new ArrayList<String[]>();
    try {
      database = mSqliteHelper.getWritableDatabase();
      cursor = database.rawQuery(sql, vArgs);
      String[] names = cursor.getColumnNames();
      ret.add(names);
      while (cursor.moveToNext()) {
        String[] record = new String[names.length];
        for (int x = 0; x < names.length; x++) {
          record[x] = cursor.getString(x);
        }
        ret.add(record);
      }

    } finally {
      try {
        if (null != cursor) {
          cursor.close();
        }
      } finally {
        database.close();
      }
    }
    return ret;
  }
 public List<String> getAllNoReadNoticeIds() {
   Cursor cursor = null;
   try {
     String sql =
         "select distinct id from "
             + TablesColumns.TABLENOTICE
             + " where "
             + TablesColumns.TABLENOTICE_READAT
             + " = 'null' and "
             + TablesColumns.TABLENOTICE_SIGNAL
             + " not in ('like','comment')";
     cursor = dataBase.rawQuery(sql, null);
     List<String> data = new ArrayList<String>();
     String[] names = cursor.getColumnNames();
     while (cursor.moveToNext()) {
       for (String name : names) {
         data.add(cursor.getString(cursor.getColumnIndex(name)));
       }
     }
     cursor.close();
     return data;
   } catch (Exception e) {
     return null;
   } finally {
     if (cursor != null) cursor.close();
   }
 }
Example #7
0
  private String showCursor(Cursor cursor) {
    // show SCHEMA (column names & types)
    cursor.moveToPosition(-1); // reset cursor's top
    String cursorData = "\nCursor: [";

    try {
      // get column names
      String[] colName = cursor.getColumnNames();
      for (int i = 0; i < colName.length; i++) {
        String dataType = getColumnType(cursor, i);
        cursorData += colName[i] + dataType;

        if (i < colName.length - 1) {
          cursorData += ", ";
        }
      }
    } catch (Exception e) {
      Log.e("<<SCHEMA>>", e.getMessage());
    }
    cursorData += "]";

    // now get the rows
    cursor.moveToPosition(-1); // reset cursor's top
    while (cursor.moveToNext()) {
      String cursorRow = "\n[";
      for (int i = 0; i < cursor.getColumnCount(); i++) {
        cursorRow += cursor.getString(i);
        if (i < cursor.getColumnCount() - 1) cursorRow += ", ";
      }
      cursorData += cursorRow + "]";
    }
    return cursorData + "\n";
  }
Example #8
0
 /**
  * Parse a content uri to a file. Some file manager return Uri like "file:///sdcard/test.mp4", In
  * this case Uri.getPath() get the file path in file system, so can create a file object with this
  * path, if this file is exists, means parse file success. Some file manager such as Gallery,
  * return Uri like "content://video/8323", In this case Uri.getPath() can't get file path in file
  * system, but can user ContentResolver to get file path from media database.
  *
  * @param uri
  * @return
  */
 public static File parseUriToFile(Context context, Uri uri) {
   if (uri == null) {
     return null;
   }
   File file = null;
   String path = uri.getPath();
   file = new File(path); // If this file is exists, means parse file success.
   if (!file.exists()) {
     // Use ContentResolver to get file path from media database.
     ContentResolver cr = context.getContentResolver();
     String[] pro =
         new String[] {
           MediaStore.MediaColumns.DATA,
         };
     Cursor cursor = cr.query(uri, pro, null, null, null);
     if (cursor != null) {
       String[] cs = cursor.getColumnNames();
       for (String string : cs) {
         System.out.println(string);
       }
       if (cursor.moveToFirst()) {
         int index = cursor.getColumnIndex(MediaStore.MediaColumns.DATA);
         path = cursor.getString(index);
         if (null != path && !"".equals(path)) {
           file = new File(path);
           if (!file.exists()) {
             file = null;
           }
         }
       }
       cursor.close();
     }
   }
   return file;
 }
  // TODO: mmsQuery
  Cursor mmsQuery(Uri uri, String query) {
    Cursor mmsCursor = mContext.getContentResolver().query(uri, null, null, null, null);
    String[] columnNames = mmsCursor.getColumnNames();

    for (String str : columnNames) {}
    mmsCursor.moveToFirst();
    do {} while (mmsCursor.moveToNext());
    return mmsCursor;
  }
 public static void debugContentResolvers(Context ctx, Uri uri) {
   try {
     Cursor cur = ctx.getContentResolver().query(uri, null, null, null, null);
     Log.d(TAG, "columns for uri: " + uri + ": " + Arrays.asList(cur.getColumnNames()).toString());
     cur.close();
   } catch (Exception exc) {
     Log.e(TAG, "Error finding columns for uri: " + uri); // , exc);
   }
 }
  /**
   * Query all the model tables and generate the fully fleshed out Form objects. <br>
   * This call will return ALL forms in the system.
   *
   * @return
   */
  public static Form[] getAllForms() {
    Uri getFormsUri = RapidSmsDBConstants.Form.CONTENT_URI;

    Cursor allformsCursor =
        mContext.getContentResolver().query(getFormsUri, null, null, null, null); // real
    // way
    // Cursor allformsCursor =
    // provider.query(getFormsUri,null,null,null,null); //hack way

    if (formColumnNamesToIndex == null) {
      formColumnNamesToIndex = new HashMap<String, Integer>();
      String[] colnames = allformsCursor.getColumnNames();
      int colcount = colnames.length;
      for (int i = 0; i < colcount; i++) {
        formColumnNamesToIndex.put(
            colnames[i], new Integer(allformsCursor.getColumnIndex(colnames[i])));
      }
    }
    int formcount = allformsCursor.getCount();

    Form[] ret = new Form[formcount];
    allformsCursor.moveToFirst();
    for (int i = 0; i < formcount; i++) {

      int id = allformsCursor.getInt(formColumnNamesToIndex.get(BaseColumns._ID).intValue());
      Integer idInt = Integer.valueOf(id);

      if (formIdCache.containsKey(idInt)) {
        ret[i] = formIdCache.get(idInt);
      }

      String name =
          allformsCursor.getString(
              formColumnNamesToIndex.get(RapidSmsDBConstants.Form.FORMNAME).intValue());
      String prefix =
          allformsCursor.getString(
              formColumnNamesToIndex.get(RapidSmsDBConstants.Form.PREFIX).intValue());
      String description =
          allformsCursor.getString(
              formColumnNamesToIndex.get(RapidSmsDBConstants.Form.DESCRIPTION).intValue());
      String parsemethod =
          allformsCursor.getString(
              formColumnNamesToIndex.get(RapidSmsDBConstants.Form.PARSEMETHOD).intValue());

      // Field[] fields = getFieldsForForm(provider, id); // hack way
      Field[] fields = getFieldsForForm(id); // real way

      Form theForm = new Form(id, name, prefix, description, fields, ParserType.SIMPLEREGEX);

      formIdCache.put(idInt, theForm);
      ret[i] = theForm;
      allformsCursor.moveToNext();
    }
    allformsCursor.close();
    return ret;
  }
Example #12
0
 @SuppressWarnings("unused")
 private void printSMSFieldNames(Cursor sms_sent_cursor) {
   // Get Column names.
   String[] colNames = sms_sent_cursor.getColumnNames();
   if (colNames != null) {
     for (int k = 0; k < colNames.length; k++) {
       Log.i("Info", "colNames[" + k + "] : " + colNames[k]);
     }
   }
 }
  public void testInsert() throws DataAccessException {
    Person p = insertPerson();
    DrinkingSpot ds = new DrinkingSpot();
    ds.setCreator(p);
    ds.setStartTime(new Date());
    ds.setGps("asd");
    ds = spotDAOLocal.insert(ds);
    Assert.assertTrue(ds.getId() != -1);
    Assert.assertTrue(ds.getId() != 0);
    Log.i("BeerBuddy", ds.toString());
    // select it
    SQLiteDatabase writableDatabase = db.getWritableDatabase();

    Cursor dbCursor = writableDatabase.rawQuery("Select * from person", null);
    while (dbCursor.moveToNext()) {
      for (String colname : dbCursor.getColumnNames()) {
        Log.i("BeerBuddy", colname + ": " + dbCursor.getString(dbCursor.getColumnIndex(colname)));
        ;
      }
    }
    dbCursor.close();
    assertTrue(dbCursor.getCount() > 0);

    dbCursor =
        writableDatabase.rawQuery(
            "Select * from drinkingspot where id = ?", new String[] {ds.getId() + ""});
    while (dbCursor.moveToNext()) {
      for (String colname : dbCursor.getColumnNames()) {
        Log.i("BeerBuddy", colname + ": " + dbCursor.getString(dbCursor.getColumnIndex(colname)));
        ;
      }

      assertEquals(ds.getId(), dbCursor.getLong(dbCursor.getColumnIndex("id")));
    }
    assertTrue(dbCursor.getCount() > 0);
    dbCursor.close();

    DrinkingSpot byId = spotDAOLocal.getById(ds.getId());
    assertNotNull(byId);

    byId = spotDAOLocal.getActiveByPersonId(p.getId());
    assertNotNull(byId);
  }
 /**
  * 获取所有非视频信息
  *
  * @return
  */
 public List<HashMap<String, String>> getAllNotice() {
   Cursor cursor = null;
   try {
     String sql =
         "select distinct "
             + TablesColumns.TABLENOTICE_ID
             + ","
             + TablesColumns.TABLENOTICE_SUBJECT
             + ","
             + TablesColumns.TABLENOTICE_SIGNAL
             + ","
             + TablesColumns.TABLENOTICE_CONTEXT
             + ","
             + TablesColumns.TABLENOTICE_USER
             + ","
             + TablesColumns.TABLENOTICE_ALERT
             + ","
             + TablesColumns.TABLENOTICE_OPERATOR
             + ","
             + TablesColumns.TABLENOTICE_CREATEDAT
             + ","
             + TablesColumns.TABLENOTICE_READAT
             + " from "
             + TablesColumns.TABLENOTICE
             + " where "
             + TablesColumns.TABLENOTICE_SIGNAL
             + " not in ('like','comment') ORDER BY "
             + TablesColumns.TABLENOTICE_CREATEDAT
             + " DESC";
     cursor = dataBase.rawQuery(sql, null);
     List<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
     HashMap<String, String> map;
     String[] names = cursor.getColumnNames();
     while (cursor.moveToNext()) {
       map = new HashMap<String, String>();
       for (String name : names) {
         map.put(name, cursor.getString(cursor.getColumnIndex(name)));
       }
       if (data.size() > 0
           && data.get(data.size() - 1)
               .get("id")
               .contains(map.get(TablesColumns.TABLENOTICE_ID).toString())) {
         continue;
       }
       data.add(map);
     }
     cursor.close();
     return data;
   } catch (Exception e) {
     return null;
   } finally {
     if (cursor != null) cursor.close();
   }
 }
 @Rpc(description = "Returns a List of all possible attributes for contacts.")
 public List<String> contactsGetAttributes() {
   List<String> result = new ArrayList<String>();
   Cursor cursor = mContentResolver.query(CONTACTS_URI, null, null, null, null);
   if (cursor != null) {
     String[] columns = cursor.getColumnNames();
     for (int i = 0; i < columns.length; i++) {
       result.add(columns[i]);
     }
     cursor.close();
   }
   return result;
 }
  public static void exportToCSV() {

    ArrayList<String> keyList = new ArrayList<>();
    keyList.add(DBAdapter.KEY_ROWID);
    keyList.add(DBAdapter.KEY_EVALUATOR);
    keyList.add(DBAdapter.KEY_HOSPITALID);
    keyList.add(DBAdapter.KEY_DATE);
    keyList.add(DBAdapter.KEY_LANGUAGE);
    for (ItemSection section : DataSource.sections) {
      for (ItemQuestion question : section.questions) {
        if (question.dbKey != null) {
          Collections.addAll(keyList, question.dbKey);
        }
      }
    }

    String[] keys = keyList.toArray(new String[keyList.size()]);

    Cursor cursor = HomeActivity.myDb.getColumns(keys);
    cursor.moveToFirst();

    File path = Environment.getExternalStorageDirectory();
    File filename =
        new File(
            path,
            "/FrailtyAnswers-"
                + cursor.getString(cursor.getColumnIndex(DBAdapter.KEY_HOSPITALID))
                + ".csv");

    try {
      CSVWriter writer = new CSVWriter(new FileWriter(filename), '\t');
      writer.writeNext(new String[] {"sep=\t"});

      writer.writeNext(cursor.getColumnNames());

      if (cursor.moveToFirst()) {
        ArrayList<String> values = new ArrayList<>();
        for (int i = 0; i < cursor.getColumnCount(); i++) {
          values.add(cursor.getString(i));
        }
        String[] stringValues = values.toArray(new String[values.size()]);
        writer.writeNext(stringValues);
      }

      writer.close();
      cursor.close();

    } catch (IOException e) {
      System.err.println("Caught IOException: " + e.getMessage());
    }
  }
  public void testNext() {
    String[] columnNames = new String[] {"number"};
    Cursor cursor1 = getCursor(TABLE_NAME_1, null, columnNames);
    Cursor cursor2 = getCursor(TABLE_NAME_2, null, columnNames);

    // For cursor1 , values are '01'~'07' and 'EQUAL_START'~'MAX_VALUE'
    assertEquals(TEST_ITEM_COUNT, cursor1.getCount());
    // For cursor2 , values are '11'~'17' and 'EQUAL_START'~'MAX_VALUE'
    assertEquals(TEST_ITEM_COUNT, cursor2.getCount());
    CursorJoiner cursorJoiner =
        new CursorJoiner(cursor1, cursor1.getColumnNames(), cursor2, cursor2.getColumnNames());
    for (int i = 0; i < UNIQUE_COUNT; i++) {
      // For cursor1, value 1~7 result value as LEFT to cursor2 value '11'
      assertTrue(cursorJoiner.hasNext());
      assertEquals(Result.LEFT, cursorJoiner.next());
      assertEquals(
          getOrderNumberString(DEFAULT_TABLE1_VALUE_BEGINS + i, MAX_VALUE), cursor1.getString(0));
      assertEquals(
          getOrderNumberString(DEFAULT_TABLE2_VALUE_BEGINS, MAX_VALUE), cursor2.getString(0));
    }
    for (int i = 0; i < UNIQUE_COUNT; i++) {
      // For cursor2, value 11~17 result a value as LEFT to cursor1 value '18'
      assertTrue(cursorJoiner.hasNext());
      assertEquals(Result.RIGHT, cursorJoiner.next());
      assertEquals(getOrderNumberString(EQUAL_START, MAX_VALUE), cursor1.getString(0));
      assertEquals(
          getOrderNumberString(DEFAULT_TABLE2_VALUE_BEGINS + i, MAX_VALUE), cursor2.getString(0));
    }
    for (int i = 0; i < EQUAL_VALUE_COUNT; i++) {
      // For cursor1 and cursor2, value 18~20 result a value as BOTH
      assertTrue(cursorJoiner.hasNext());
      assertEquals(Result.BOTH, cursorJoiner.next());
      assertEquals(getOrderNumberString(EQUAL_START + i, MAX_VALUE), cursor1.getString(0));
      assertEquals(getOrderNumberString(EQUAL_START + i, MAX_VALUE), cursor2.getString(0));
    }
    closeCursor(cursor1);
    closeCursor(cursor2);
  }
Example #18
0
  /**
   * 解析数据
   *
   * @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 static ITokenParser getFieldType(int type_id) {
    // //real way
    // public static SimpleFieldType getFieldType(ContentProvider provider,
    // int type_id) { // hack
    // way

    Integer typeInt = new Integer(type_id);
    if (fieldTypeHash.containsKey(typeInt)) {
      return fieldTypeHash.get(typeInt);
    }
    Uri typeUri = Uri.parse(RapidSmsDBConstants.FieldType.CONTENT_URI_STRING + type_id);
    Cursor typeCursor =
        mContext.getContentResolver().query(typeUri, null, null, null, null); // real
    // way
    // Cursor typeCursor = provider.query(typeUri, null, null, null, null);
    // // hack
    // way

    if (typeColumnNamesToIndex == null) {
      typeColumnNamesToIndex = new HashMap<String, Integer>();
      String[] colnames = typeCursor.getColumnNames();
      int colcount = colnames.length;
      for (int i = 0; i < colcount; i++) {
        typeColumnNamesToIndex.put(
            colnames[i], new Integer(typeCursor.getColumnIndex(colnames[i])));
      }
    }
    if (typeCursor.getCount() != 1) {
      throw new IllegalArgumentException(typeUri + " returned a bad result.");
    }

    typeCursor.moveToFirst();

    int id = typeCursor.getInt(typeColumnNamesToIndex.get(BaseColumns._ID).intValue());
    String dataType =
        typeCursor.getString(
            typeColumnNamesToIndex.get(RapidSmsDBConstants.FieldType.DATATYPE).intValue());
    String name =
        typeCursor.getString(
            typeColumnNamesToIndex.get(RapidSmsDBConstants.FieldType.NAME).intValue());
    String regex =
        typeCursor.getString(
            typeColumnNamesToIndex.get(RapidSmsDBConstants.FieldType.REGEX).intValue());

    // SimpleFieldType ftype) {
    SimpleFieldType newType = new SimpleFieldType(id, dataType, regex, name);
    fieldTypeHash.put(typeInt, newType);
    typeCursor.close();
    return newType;
  }
  @Override
  public Employee read(Long id) {
    Cursor cursor =
        database.query("Employees", null, "id=?", new String[] {id.toString()}, null, null, null);
    if (cursor != null || cursor.moveToFirst()) {
      for (String colName : cursor.getColumnNames()) {
        oneEmplprepareMap.put(colName, cursor.getString(cursor.getColumnIndex(colName)));
      }
      // employee = new
      // Employee(Integer.parseInt(oneEmplprepareMap.get("id")),oneEmplprepareMap.get("name"),Integer.parseInt(oneEmplprepareMap.get("postId")), )
    }

    return null;
  }
 // вывод в лог данных из курсора
 void logCursor(Cursor c) {
   if (c != null) {
     if (c.moveToFirst()) {
       String line;
       do {
         line = "";
         for (String column : c.getColumnNames()) {
           line = line.concat(column + " = " + c.getString(c.getColumnIndex(column)) + "; ");
         }
         Log.d(LOG_TAG, line);
       } while (c.moveToNext());
     }
   }
 }
  /**
   * Fill the client Data table from an Android Cursor Database
   *
   * @param pCursor
   */
  public void fillFromCursor(Cursor pCursor) {

    _mCursor = pCursor;
    _mCursorSize = pCursor.getCount();
    _mListOfRows.clear();
    _mListOfRows.ensureCapacity(_mCursorSize);

    String[] lCursorColumnsNames = pCursor.getColumnNames();
    int lNbrColumnsCDT = getColumnsCount();

    int lNbrColumnsCursor = lCursorColumnsNames.length;

    if (lNbrColumnsCDT == 0) {
      for (int i = 0; i < lNbrColumnsCursor; i++) {
        _mListOfColumns.add(new TColumn(lCursorColumnsNames[i], ValueType.TEXT));
      }
    }
    if (_mCursorSize > 0) {

      pCursor.moveToFirst();
      _mPosition = 0;
      while (!pCursor.isAfterLast()) {
        TRow lRow = new TRow();

        if (lNbrColumnsCDT > 0) {
          for (int i = 0; i < lNbrColumnsCDT; i++) {
            boolean lIsColumnFound = false;
            TColumn lColumn = _mListOfColumns.get(i);
            for (int j = 0; j < lNbrColumnsCursor; j++) {
              if (lColumn != null && lColumn.getName().equals(lCursorColumnsNames[j])) {
                lRow.addCell(_mContext, pCursor.getString(j), lColumn.getValueType(), _mCDTStatus);
                lIsColumnFound = true;
                break;
              }
            }
            if (!lIsColumnFound) lRow.addCell(_mContext, "", lColumn.getValueType(), _mCDTStatus);
          }
        } else {
          for (int i = 0; i < lNbrColumnsCursor; i++) {
            String lColumnName = lCursorColumnsNames[i];
            if (lColumnName != null && !lColumnName.equals(""))
              lRow.addCell(_mContext, pCursor.getString(i), ValueType.TEXT, _mCDTStatus);
          }
        }
        _mListOfRows.add(lRow);
        pCursor.moveToNext();
      }
    }
    Log.i("fillFromCursor", " Count :" + _mCursorSize);
  }
    public String[] getColumnNames() {
      String[] x = mDatabaseCursor.getColumnNames();
      String[] y = new String[x.length + mVirtualColumns.length];

      for (int i = 0; i < x.length; i++) {
        y[i] = x[i];
      }

      for (int i = 0; i < mVirtualColumns.length; i++) {
        y[x.length + i] = mVirtualColumns[i];
      }

      return y;
    }
  /**
   * Get a fully defined form object by the integer id (rapidandroid_form._id) as part of a URI
   * string
   *
   * @param id
   * @return
   */
  public static Form getFormFromUri(Uri formUri) {

    Integer formid = Integer.valueOf(formUri.getPathSegments().get(1));
    if (formIdCache.containsKey(formid)) {
      return formIdCache.get(formid);
    }

    Cursor formCursor =
        mContext.getContentResolver().query(formUri, null, null, null, null); // real
    // way
    if (formCursor.getCount() != 1) {
      throw new IllegalArgumentException(formUri + " returned a bad result.");
    }

    if (formColumnNamesToIndex == null) {
      formColumnNamesToIndex = new HashMap<String, Integer>();
      String[] colnames = formCursor.getColumnNames();
      int colcount = colnames.length;
      for (int i = 0; i < colcount; i++) {
        formColumnNamesToIndex.put(
            colnames[i], new Integer(formCursor.getColumnIndex(colnames[i])));
      }
    }

    formCursor.moveToFirst();
    int id = formCursor.getInt(formColumnNamesToIndex.get(BaseColumns._ID).intValue());
    String name =
        formCursor.getString(
            formColumnNamesToIndex.get(RapidSmsDBConstants.Form.FORMNAME).intValue());
    String prefix =
        formCursor.getString(
            formColumnNamesToIndex.get(RapidSmsDBConstants.Form.PREFIX).intValue());
    String description =
        formCursor.getString(
            formColumnNamesToIndex.get(RapidSmsDBConstants.Form.DESCRIPTION).intValue());
    String parsemethod =
        formCursor.getString(
            formColumnNamesToIndex.get(RapidSmsDBConstants.Form.PARSEMETHOD).intValue());

    // Field[] fields = getFieldsForForm(provider, id); // hack way
    Field[] fields = getFieldsForForm(id); // real way

    Form ret =
        new Form(formCursor.getInt(0), name, prefix, description, fields, ParserType.SIMPLEREGEX);
    formIdCache.put(Integer.valueOf(id), ret);
    formCursor.close();
    return ret;
  }
Example #25
0
 void logCursor(Cursor cursor) {
   if (cursor != null) {
     if (cursor.moveToFirst()) {
       String str;
       do {
         str = "";
         for (String cn : cursor.getColumnNames()) {
           str = str.concat(cn + " = " + cursor.getString(cursor.getColumnIndex(cn)) + ";");
         }
         Log.d(LT, str);
       } while (cursor.moveToNext());
     } else {
       Log.d(LT, "Cursor is null");
     }
   }
 }
Example #26
0
 private static List<String> GetColumns(SQLiteDatabase db, String tableName) {
   List<String> ar = null;
   Cursor c = null;
   try {
     c = db.rawQuery("SELECT * FROM " + tableName + " LIMIT 1", null);
     if (c != null) {
       ar = new ArrayList<String>(Arrays.asList(c.getColumnNames()));
     }
   } catch (Exception e) {
     Log.v(tableName, e.getMessage(), e);
     e.printStackTrace();
   } finally {
     if (c != null) c.close();
   }
   return ar;
 }
Example #27
0
  public List<Map<String, String>> getAllCursorValues(Cursor cur) {

    List<Map<String, String>> allVals;

    allVals = new ArrayList<Map<String, String>>();

    while (cur.moveToNext()) {
      Map<String, String> curValues;

      curValues = new HashMap<String, String>();
      for (String columnName : cur.getColumnNames()) {
        curValues.put(columnName, cur.getString(cur.getColumnIndex(columnName)));
      }
    }

    return allVals;
  }
Example #28
0
  /**
   * Converts a Cursor into a unmodifiable Map of known metadata properties. Will throw away any
   * properties that aren't stored in the database. Will also not iterate through multiple rows in
   * the cursor.
   */
  private static Map<String, Object> fromCursor(Cursor c) {
    Map<String, Object> data = new HashMap<String, Object>();

    Set<String> model = getModel();
    String[] columns = c.getColumnNames();
    for (String column : columns) {
      if (model.contains(column)) {
        try {
          data.put(column, c.getString(c.getColumnIndexOrThrow(column)));
        } catch (Exception ex) {
          Log.i(LOGTAG, "Error getting data for " + column, ex);
        }
      }
    }

    return Collections.unmodifiableMap(data);
  }
 @Override
 public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
   if (cursor != null) {
     Log.e(
         TAG,
         String.format(
             "Report list Cursor size: %d. Cursor columns: %s. Cursor column count: %d",
             cursor.getCount(), Arrays.toString(cursor.getColumnNames()), cursor.getCount()));
     mAdapter.swapCursor(cursor);
     if (isResumed()) {
       setListShown(true);
     } else {
       setListShownNoAnimation(true);
     }
   }
   setListShown(true);
 }
 @Override
 public void bindView(View view, Context context, Cursor cursor) {
   final ODataRow row = new ODataRow();
   for (String col : cursor.getColumnNames()) {
     row.put(col, getValue(cursor, col));
   }
   if (mBeforeBindUpdateData != null) {
     row.addAll(mBeforeBindUpdateData.updateDataRow(cursor));
   }
   if (view instanceof OForm) {
     OForm form = (OForm) view;
     form.initForm(row);
   }
   if (mOnViewBindListener != null) {
     mOnViewBindListener.onViewBind(view, cursor, row);
   }
 }