Exemplo n.º 1
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";
  }
Exemplo n.º 2
0
  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));
    }
  }
Exemplo n.º 3
0
  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();
  }
Exemplo n.º 4
0
  /**
   * 查找包含会议材料的列表
   *
   * @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;
  }
  /*
   * loadAdminClasses (String table)
   * dbHelperAdminClasses is a helper class which mimics the SQL format of quizzes that is used
   * on our remote database.
   * Parameters: String username - 'username' should be the username of the currently logged user
   * Returns: Pair<ArrayList<String>, HashMap<String,List<String>>> - Returns
   *              1. An ArrayList representing the headers of each quiz topic
   *              2. A HashMap that that pairs header keys with a List of that header's children
   *          The header and child information is used in SubjectNavActivity to create
   *          an expandable list where the unexpanded tab is a quiz topic, and the expanded tabs
   *          are specific quizzes belonging to that topic.
   *
   */
  public Pair<ArrayList<String>, HashMap<String, List<String>>> loadAdminClasses(String username) {

    this.table = "`" + username + "Classes`";

    String selectionQuery = "SELECT * FROM " + this.table + " ORDER BY indexer";
    try {
      Cursor dataCurs = this.getWritableDatabase().rawQuery(selectionQuery, null);
      dataCurs.moveToFirst();
      HashMap<String, List<String>> headerChildPairs = new HashMap<>();
      ArrayList<String> headers = new ArrayList<>();
      do {
        List<String> children = new ArrayList<>();
        String header = dataCurs.getString(CLASS_INDEX); // Get Header
        headers.add(header);

        // Iterate starts after header and ends before indexer.
        for (int i = CLASS_INDEX + 1; i < dataCurs.getColumnCount() - 1; i++) {
          if (dataCurs.getString(i) != null) // If child isn't null, or "" add to list of child
          if (!dataCurs.getString(i).equals("")) children.add(dataCurs.getString(i));
        }
        headerChildPairs.put(header, children);
      } while (dataCurs.moveToNext());
      dataCurs.close();

      return new Pair<>(headers, headerChildPairs);
    } catch (SQLiteException e) {
      e.printStackTrace();
    }

    return null;
  }
Exemplo n.º 6
0
 /**
  * Flatten all columns and all rows of a cursor to a single array. The array cannot be interpreted
  * meaningfully without the number of columns.
  *
  * @param cursor
  * @param limit Maximum number of rows to process.
  * @return List of Java primitives matching the value type of each column.
  */
 private List<Object> flattenRows(Cursor cursor, int limit) {
   Util.throwIfNot(limit >= 0);
   List<Object> flatList = new ArrayList<Object>();
   final int numColumns = cursor.getColumnCount();
   for (int row = 0; row < limit && cursor.moveToNext(); row++) {
     for (int column = 0; column < numColumns; column++) {
       switch (cursor.getType(column)) {
         case Cursor.FIELD_TYPE_NULL:
           flatList.add(null);
           break;
         case Cursor.FIELD_TYPE_INTEGER:
           flatList.add(cursor.getLong(column));
           break;
         case Cursor.FIELD_TYPE_FLOAT:
           flatList.add(cursor.getDouble(column));
           break;
         case Cursor.FIELD_TYPE_BLOB:
           flatList.add(cursor.getBlob(column));
           break;
         case Cursor.FIELD_TYPE_STRING:
         default:
           flatList.add(cursor.getString(column));
           break;
       }
     }
   }
   if (!cursor.isAfterLast()) {
     for (int column = 0; column < numColumns; column++) {
       flatList.add("{truncated}");
     }
   }
   return flatList;
 }
Exemplo n.º 7
0
  /**
   * 取得数据库的表信息
   *
   * @return
   */
  public ArrayList<DBMasterEntity> getTables() {
    ArrayList<DBMasterEntity> tadbMasterArrayList = new ArrayList<DBMasterEntity>();
    String sql = "select * from sqlite_master where type='table' order by name";
    CHLogger.i(SQLiteDB.this, sql);
    if (testSQLiteDatabase()) {
      if (sql != null && !sql.equalsIgnoreCase("")) {
        this.queryStr = sql;
        free();
        queryCursor =
            mSQLiteDatabase.rawQuery(
                "select * from sqlite_master where type='table' order by name", null);

        if (queryCursor != null) {
          while (queryCursor.moveToNext()) {
            if (queryCursor != null && queryCursor.getColumnCount() > 0) {
              DBMasterEntity tadbMasterEntity = new DBMasterEntity();
              tadbMasterEntity.setType(queryCursor.getString(0));
              tadbMasterEntity.setName(queryCursor.getString(1));
              tadbMasterEntity.setTbl_name(queryCursor.getString(2));
              tadbMasterEntity.setRootpage(queryCursor.getInt(3));
              tadbMasterEntity.setSql(queryCursor.getString(4));
              tadbMasterArrayList.add(tadbMasterEntity);
            }
          }
        } else {
          CHLogger.e(SQLiteDB.this, "数据库未打开!");
        }
      }
    } else {
      CHLogger.e(SQLiteDB.this, "数据库未打开!");
    }
    return tadbMasterArrayList;
  }
Exemplo n.º 8
0
  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();
  }
Exemplo n.º 9
0
 /**
  * Fills the specified cursor window by iterating over the contents of the cursor. The window is
  * filled until the cursor is exhausted or the window runs out of space.
  *
  * <p>The original position of the cursor is left unchanged by this operation.
  *
  * @param cursor The cursor that contains the data to put in the window.
  * @param position The start position for filling the window.
  * @param window The window to fill.
  * @hide
  */
 public static void cursorFillWindow(
     final Cursor cursor, int position, final CursorWindow window) {
   if (position < 0 || position >= cursor.getCount()) {
     return;
   }
   final int oldPos = cursor.getPosition();
   final int numColumns = cursor.getColumnCount();
   window.clear();
   window.setStartPosition(position);
   window.setNumColumns(numColumns);
   if (cursor.moveToPosition(position)) {
     do {
       if (!window.allocRow()) {
         break;
       }
       for (int i = 0; i < numColumns; i++) {
         final boolean success;
         final String value = cursor.getString(i);
         success =
             value != null ? window.putString(value, position, i) : window.putNull(position, i);
         if (!success) {
           window.freeLastRow();
           break;
         }
       }
       position += 1;
     } while (cursor.moveToNext());
   }
   cursor.moveToPosition(oldPos);
 }
Exemplo n.º 10
0
 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;
 }
Exemplo n.º 11
0
  /**
   * 将游标结果集转成指定类名的列表
   *
   * @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;
  }
Exemplo n.º 12
0
  public String mensaje(String organo) {

    String cad = "";
    int numAleatorio;
    if (organo.equalsIgnoreCase("General")) {
      numAleatorio = aleatorio(6);
    } else {
      numAleatorio = aleatorio(2);
    }

    try {
      aBD = new Ayudante(this, "mensajes", null, 1);
      db = aBD.getReadableDatabase();
      if (db != null) {
        Cursor cursor =
            db.rawQuery(
                "SELECT * FROM mensajes where tematica='" + organo + "' and  num=" + numAleatorio,
                null); // +i+" and num="+g,null);//+num+" and num="+numAleatorio+"",null);
        int numcol = cursor.getColumnCount();
        int numren = cursor.getCount();
        while (cursor.moveToNext()) {
          cad = cursor.getString(2);
        } // while
        // Toast.makeText(getApplicationContext(),"es "+numAleatorio,Toast.LENGTH_SHORT).show();

        cursor.close();
        db.close();
      } // if
      else cad = "db fue null";
    } // try
    catch (Exception e) {
      String cad2 = "ERROR " + e.getMessage();
    } // catch
    return cad;
  }
Exemplo n.º 13
0
 /**
  * 把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;
 }
  public String[] getCorrectAnswer(String Question) {

    String selectQuery =
        "SELECT * FROM questions q INNER JOIN answer_option a ON q._id = a.question_id where q.question =? AND a.correct = 1";

    OpenHelper openHelper = new OpenHelper(this);
    SQLiteDatabase db = openHelper.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, new String[] {Question});

    cursor.moveToFirst();

    String[] arrayData = null;

    if (cursor != null) {

      arrayData = new String[cursor.getColumnCount()];

      arrayData[0] = cursor.getString(cursor.getColumnIndex("question"));
      arrayData[1] = cursor.getString(cursor.getColumnIndex("answer"));

      arrayData[2] = cursor.getString(cursor.getColumnIndex("correct"));
    }

    cursor.close();
    return arrayData;
  }
Exemplo n.º 15
0
 public Cursor getCompleteDetails(int searchIndex) {
   // TODO Auto-generated method stub
   String completeDetails = "Select * From " + TABLE_NAME + " Where  ISBN = " + searchIndex;
   Cursor cur = myDatabase.rawQuery(completeDetails, null);
   Log.e(
       "No of rows returned is ", " :: " + cur.getCount() + "no of coulms" + cur.getColumnCount());
   return cur;
 }
  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;
  }
Exemplo n.º 17
0
    private int copyFromCursor(SQLiteDatabase db, Cursor c) {
      final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
      final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
      final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
      final int iconTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
      final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
      final int iconPackageIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
      final int iconResourceIndex =
          c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
      final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
      final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
      final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
      final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
      final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
      final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
      final int displayModeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);

      ContentValues[] rows = new ContentValues[c.getCount()];
      int i = 0;
      while (c.moveToNext()) {
        ContentValues values = new ContentValues(c.getColumnCount());
        values.put(LauncherSettings.Favorites._ID, c.getLong(idIndex));
        values.put(LauncherSettings.Favorites.INTENT, c.getString(intentIndex));
        values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
        values.put(LauncherSettings.Favorites.ICON_TYPE, c.getInt(iconTypeIndex));
        values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
        values.put(LauncherSettings.Favorites.ICON_PACKAGE, c.getString(iconPackageIndex));
        values.put(LauncherSettings.Favorites.ICON_RESOURCE, c.getString(iconResourceIndex));
        values.put(LauncherSettings.Favorites.CONTAINER, c.getInt(containerIndex));
        values.put(LauncherSettings.Favorites.ITEM_TYPE, c.getInt(itemTypeIndex));
        values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
        values.put(LauncherSettings.Favorites.SCREEN, c.getInt(screenIndex));
        values.put(LauncherSettings.Favorites.CELLX, c.getInt(cellXIndex));
        values.put(LauncherSettings.Favorites.CELLY, c.getInt(cellYIndex));
        values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
        values.put(LauncherSettings.Favorites.DISPLAY_MODE, c.getInt(displayModeIndex));
        rows[i++] = values;
      }

      db.beginTransaction();
      int total = 0;
      try {
        int numValues = rows.length;
        for (i = 0; i < numValues; i++) {
          if (db.insert(TABLE_FAVORITES, null, rows[i]) < 0) {
            return 0;
          } else {
            total++;
          }
        }
        db.setTransactionSuccessful();
      } finally {
        db.endTransaction();
      }

      return total;
    }
Exemplo n.º 18
0
 /**
  * No Distinc de la columna especificada.
  *
  * @param tabla Nombre de la tabla a consultar.
  * @param columna Nombre de la columna que se desea obtener.
  * @param where Condicion where para la consulta sin la palabra 'where' (null en caso de no
  *     existir condicion).
  * @return Lista con los datos de la columna especificada.
  */
 public List<String[]> getTabla(String tabla, String[] columna, String where) {
   List<String[]> filas = new ArrayList(); // Lista
   String[] fila;
   SQLiteDatabase db = this.myDataBase;
   if (db != null) {
     Cursor c =
         this.getReadableDatabase()
             .query(false, tabla, columna, where, null, null, null, null, null);
     if (c.moveToFirst()) {
       do {
         fila = new String[c.getColumnCount()];
         for (int i = 0; i < c.getColumnCount(); i++) fila[i] = c.getString(i);
         filas.add(fila);
       } while (c.moveToNext());
       return filas;
     } else return new ArrayList();
   } else return new ArrayList();
 }
Exemplo n.º 19
0
 public synchronized Story getStory(int position) {
   if (stories == null
       || stories.getColumnCount() == 0
       || position >= stories.getCount()
       || position < 0) {
     return null;
   } else {
     stories.moveToPosition(position);
     return Story.fromCursor(stories);
   }
 }
Exemplo n.º 20
0
 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;
 }
Exemplo n.º 21
0
 /*
  * Use the getContacts() function
  * to get a cursor and print all
  * the contact names followed by look up keys
  * uses the printLookyupKeus() function
  */
 public void listContacts() {
   Cursor c = null;
   try {
     c = getContacts();
     int i = c.getColumnCount();
     this.mReportTo.reportBack(tag, "Number of columns:" + i);
     this.printLookupKeys(c);
   } finally {
     if (c != null) c.close();
   }
 }
 public static Mi ck(Context context) {
   Mi mi = new Mi();
   String key1 = "";
   try {
     key1 = org.dayup.decription.Utils.getDigest();
   } catch (NoSuchAlgorithmException e) {
     Log.e(TAG, e.getMessage());
   }
   Cursor cursor = null;
   try {
     cursor =
         context
             .getContentResolver()
             .query(Uri.parse(CONTENT_KEY), null, null, new String[] {key1}, null);
     if (cursor != null && cursor.moveToFirst()) {
       int cols = cursor.getColumnCount();
       if (cols == 1) { // key.version = 1
         mi.setV(1);
         mi.setLc(System.currentTimeMillis());
         mi.setIrk(key1.equals(cursor.getString(0)));
       } else {
         mi.setLc(cursor.getLong(3));
         mi.setV(cursor.getInt(2));
         mi.setK2(cursor.getString(1));
         mi.setK1(cursor.getString(0));
         try {
           mi.setIrk(
               key1.equals(mi.getK1())
                   && org.dayup.decription.Utils.getDigest2("" + mi.getLc()).equals(mi.getK2())
                   && mi.getLc() % 2 == 0);
         } catch (NoSuchAlgorithmException e) {
           mi.setIrk(false);
           Log.e(TAG, e.getMessage());
         }
       }
     } else {
       return null;
     }
   } catch (SecurityException se) {
     mi.setIrk(false);
     Toast.makeText(
             context,
             "Invalid app apk, please install/update it from Android Market.",
             Toast.LENGTH_LONG)
         .show();
     Log.e(TAG, se.getMessage());
   } finally {
     if (cursor != null) {
       cursor.close();
     }
   }
   return mi;
 }
Exemplo n.º 23
0
 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());
   }
 }
Exemplo n.º 24
0
 public JSONObject chunk() {
   JSONObject buf = new JSONObject();
   try {
     buf.put("done", false);
     int lim = 2500;
     List<Integer> colTypes = null;
     while (!mTablesLeft.isEmpty() && lim > 0) {
       String curTable = mTablesLeft.getFirst();
       if (mCursor == null) {
         mCursor = cursorForTable(curTable);
         colTypes = columnTypesForQuery(curTable);
       }
       JSONArray rows = new JSONArray();
       int count = mCursor.getColumnCount();
       while (mCursor.moveToNext() && mCursor.getPosition() <= lim) {
         JSONArray r = new JSONArray();
         for (int i = 0; i < count; i++) {
           switch (colTypes.get(i).intValue()) {
             case TYPE_STRING:
               r.put(mCursor.getString(i));
               break;
             case TYPE_FLOAT:
               r.put(mCursor.getDouble(i));
               break;
             case TYPE_INTEGER:
               r.put(mCursor.getLong(i));
               break;
           }
         }
         rows.put(r);
       }
       int fetched = rows.length();
       if (fetched != lim) {
         // table is empty
         mTablesLeft.removeFirst();
         mCursor.close();
         mCursor = null;
         // if we're the client, mark the objects as having been sent
         if (!mCol.getServer()) {
           mCol.getDb().execute("UPDATE " + curTable + " SET usn=" + mMaxUsn + " WHERE usn=-1");
         }
       }
       buf.put(curTable, rows);
       lim -= fetched;
     }
     if (mTablesLeft.isEmpty()) {
       buf.put("done", true);
     }
   } catch (JSONException e) {
     throw new RuntimeException(e);
   }
   return buf;
 }
Exemplo n.º 25
0
 /**
  * 转换Cursor当前的元素,且不作游标移动操作
  *
  * @param mCursor
  * @return
  */
 public static String toStringOnce(Cursor mCursor) {
   String str = "";
   if (mCursor == null) {
     str = "cursor is null pointer";
   } else {
     int coloumnCount = mCursor.getColumnCount();
     final String _t = "  \t";
     for (int j = 0; j < coloumnCount; j++) {
       str += _t + mCursor.getString(j);
     }
   }
   return str;
 }
Exemplo n.º 26
0
 public void printLookupUriColumns(String lookupuri) {
   Cursor c = null;
   try {
     c = getASingleContact(lookupuri);
     int i = c.getColumnCount();
     this.mReportTo.reportBack(tag, "Number of columns:" + i);
     int j = c.getCount();
     this.mReportTo.reportBack(tag, "Number of rows:" + j);
     this.printCursorColumnNames(c);
   } finally {
     if (c != null) c.close();
   }
 }
Exemplo n.º 27
0
 private Category cursorToUserCategory(Cursor cursor) {
   System.out.println(
       "*******************cursorToUserCategory************************KOLUMNEJA"
           + cursor.getColumnCount());
   // Log.d("cursorToCategory", "cursor.getLong(0) ID..>" +cursor.getLong(0) +" CATEGORYTEXT: " +
   // cursor.getString(1) + " cursor.getLong(2) RECEIPTID---> " +cursor.getLong(2));
   Category newCategory = new Category();
   newCategory.setCategoryId(cursor.getLong(0));
   newCategory.setCategoryText(cursor.getString(1));
   System.out.println("CATEGORY: " + newCategory.getCategoryText());
   System.out.println("newCategory in cursorToCategory---->" + newCategory);
   return newCategory;
 }
  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 onItemClick(AdapterView<?> parent, View view, int position, long id) {
      ListView listView = (ListView) parent;
      Cursor cursor = (Cursor) listView.getItemAtPosition(position);
      startManagingCursor(cursor);
      String[] data = new String[cursor.getColumnCount()];
      for (int index = 0; index < data.length; index++) {
        data[index] = cursor.getString(index);
      }

      Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
      intent.putExtra("data0", data);

      startActivity(intent);
    }
Exemplo n.º 30
0
 /**
  * 获取表的所有字段
  *
  * @param table 表名
  * @return
  */
 private List<String> getTableFields(String table) {
   List<String> list = new ArrayList<String>();
   String sql = "PRAGMA table_info(" + table + ")";
   db = dbFactory.getReadableDatabase();
   Cursor cursor = db.rawQuery(sql, null);
   while (cursor.moveToNext()) {
     for (int i = 0; i < cursor.getColumnCount(); i++) {
       list.add(cursor.getString(i));
     }
   }
   cursor.close();
   closeDB();
   return list;
 }