/** {@inheritDoc} */
  public void onQueryComplete(int token, Object cookie, Cursor cursor) {
    if (getActivity() == null || cursor == null) {
      return;
    }

    mCursor = cursor;
    getActivity().startManagingCursor(mCursor);

    // If there was a last-opened track, load it. Otherwise load the first track.
    cursor.moveToFirst();
    String lastTrackID = UIUtils.getLastUsedTrackID(getActivity());
    if (lastTrackID != null) {
      while (!cursor.isAfterLast()) {
        if (lastTrackID.equals(cursor.getString(TracksAdapter.TracksQuery.TRACK_ID))) {
          break;
        }
        cursor.moveToNext();
      }

      if (cursor.isAfterLast()) {
        loadTrack(null, mAutoloadTarget);
      } else {
        loadTrack(cursor, mAutoloadTarget);
      }
    } else {
      loadTrack(null, mAutoloadTarget);
    }

    mAdapter.setHasAllItem(true);
    mAdapter.setIsSessions(TracksFragment.NEXT_TYPE_SESSIONS.equals(mNextType));
    mAdapter.changeCursor(mCursor);
  }
예제 #2
0
  private static void updateNotification(
      Context context, MasterSecret masterSecret, boolean signal, int reminderCount) {
    Cursor telcoCursor = null;
    Cursor pushCursor = null;

    try {
      telcoCursor = DatabaseFactory.getMmsSmsDatabase(context).getUnread();

      if ((telcoCursor == null || telcoCursor.isAfterLast())
          && (pushCursor == null || pushCursor.isAfterLast())) {
        ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE))
            .cancel(NOTIFICATION_ID);
        clearReminder(context);
        return;
      }

      NotificationState notificationState =
          constructNotificationState(context, masterSecret, telcoCursor);

      if (notificationState.hasMultipleThreads()) {
        sendMultipleThreadNotification(context, notificationState, signal);
      } else {
        sendSingleThreadNotification(context, masterSecret, notificationState, signal);
      }

      if (signal) {
        scheduleReminder(context, reminderCount);
      }
    } finally {
      if (telcoCursor != null) telcoCursor.close();
      if (pushCursor != null) pushCursor.close();
    }
  }
  private void combineBlockAgendas() {
    final String filename = "agendas.org";
    long agendaFileNodeID = db.getFileId(filename);
    Cursor cursor = db.getNodeChildren(agendaFileNodeID);

    cursor.moveToFirst();

    String previousBlockTitle = "";
    long previousBlockNode = -1;

    while (cursor.isAfterLast() == false) {
      String name = cursor.getString(cursor.getColumnIndex("name"));

      if (name.indexOf(">") == -1) continue;

      String blockTitle = name.substring(0, name.indexOf(">"));

      if (TextUtils.isEmpty(blockTitle) == false) { // Is a block agenda

        if (blockTitle.equals(previousBlockTitle)
            == false) { // Create new node to contain block agenda
          previousBlockNode =
              db.addNode(agendaFileNodeID, blockTitle, "", "", "", db.getFilenameId(filename));
        }

        String blockEntryName = name.substring(name.indexOf(">") + 1);

        long nodeId = cursor.getLong(cursor.getColumnIndex("_id"));

        Cursor children = db.getNodeChildren(nodeId);
        children.moveToFirst();

        if (blockEntryName.startsWith("Day-agenda") && children.getCount() == 1) {
          blockEntryName = children.getString(children.getColumnIndex("name"));
          children = db.getNodeChildren(children.getLong(children.getColumnIndex("_id")));
          children.moveToFirst();
          cloneChildren(children, previousBlockNode, agendaFileNodeID, blockEntryName, filename);
        } else if (blockEntryName.startsWith("Week-agenda")) {
          while (children.isAfterLast() == false) {
            blockEntryName = children.getString(children.getColumnIndex("name"));
            Cursor children2 = db.getNodeChildren(children.getLong(children.getColumnIndex("_id")));
            children2.moveToFirst();
            cloneChildren(children2, previousBlockNode, agendaFileNodeID, blockEntryName, filename);
            children2.close();
            children.moveToNext();
          }
        } else
          cloneChildren(children, previousBlockNode, agendaFileNodeID, blockEntryName, filename);

        previousBlockTitle = blockTitle;
        db.deleteNode(cursor.getLong(cursor.getColumnIndex("_id")));
        children.close();
      }

      cursor.moveToNext();
    }

    cursor.close();
  }
예제 #4
0
  public List<Seance> cursorToSeance(Cursor res) {
    List<Seance> listSeances = new ArrayList<Seance>();
    res.moveToFirst();

    while (res.isAfterLast() == false) {

      Seance seance =
          new Seance(
              res.getInt(res.getColumnIndex(SEANCE_COLUMN_ID)),
              res.getString(res.getColumnIndex(SEANCE_COLUMN_ACTUAL_DATE)),
              res.getString(res.getColumnIndex(SEANCE_COLUMN_SHOW_TIME)),
              res.getInt(res.getColumnIndex(SEANCE_COLUMN_IS_TROISD)) == 1,
              res.getInt(res.getColumnIndex(SEANCE_COLUMN_IS_MALENTENDANT)) == 1,
              res.getInt(res.getColumnIndex(SEANCE_COLUMN_IS_HANDICAPE)) == 1,
              res.getString(res.getColumnIndex(SEANCE_COLUMN_NATIONALITY)),
              res.getInt(res.getColumnIndex(SEANCE_COLUMN_CINEMAID)),
              res.getInt(res.getColumnIndex(SEANCE_COLUMN_FILMID)),
              res.getString(res.getColumnIndex(SEANCE_COLUMN_TITRE)),
              res.getInt(res.getColumnIndex(SEANCE_COLUMN_CATEGORIEID)),
              res.getInt(res.getColumnIndex(SEANCE_COLUMN_PERFORMANCEID)),
              res.getString(res.getColumnIndex(SEANCE_COLUMN_CINEMA_SALLE)));
      res.moveToNext();
      listSeances.add(seance);
    }
    return listSeances;
  }
예제 #5
0
  public List<Event> cursorToEvent(Cursor res) {
    List<Event> listEvents = new ArrayList<Event>();
    res.moveToFirst();

    while (res.isAfterLast() == false) {

      List<Film> listFilms = stringToFilms(res.getString(res.getColumnIndex(EVENT_COLUMN_FILMS)));

      Event event =
          new Event(
              res.getString(res.getColumnIndex(EVENT_COLUMN_ID)),
              res.getString(res.getColumnIndex(EVENT_COLUMN_TITRE)),
              res.getString(res.getColumnIndex(EVENT_COLUMN_SOUSTITRE)),
              res.getString(res.getColumnIndex(EVENT_COLUMN_AFFICHE)),
              res.getString(res.getColumnIndex(EVENT_COLUMN_DESCRIPTION)),
              res.getString(res.getColumnIndex(EVENT_COLUMN_VAD_CONDITION)),
              res.getString(res.getColumnIndex(EVENT_COLUMN_PARTENAIRE)),
              res.getString(res.getColumnIndex(EVENT_COLUMN_DATE_DEB)),
              res.getString(res.getColumnIndex(EVENT_COLUMN_DATE_FIN)),
              res.getString(res.getColumnIndex(EVENT_COLUMN_HEURE)),
              res.getString(res.getColumnIndex(EVENT_COLUMN_CONTACT)),
              res.getString(res.getColumnIndex(EVENT_COLUMN_WEB_LABEL)),
              res.getString(res.getColumnIndex(EVENT_COLUMN_EVENEMENTTYPEID)),
              listFilms);
      event.setTitre_wrapped(res.getString(res.getColumnIndex(EVENT_COLUMN_TITRE_WRAPPED)));
      event.setType_wrapped(res.getString(res.getColumnIndex(EVENT_COLUMN_TYPE_WRAPPED)));

      listEvents.add(event);
      res.moveToNext();
    }
    return listEvents;
  }
예제 #6
0
  /**
   * *
   *
   * @param db SQLiteDatabase - The database resource to query
   * @return ArrayList<Price>
   */
  public static ArrayList<Price> findAll(SQLiteDatabase db) {

    String sql = "SELECT * FROM price ORDER BY created_at DESC";
    Cursor cursor = db.rawQuery(sql, null);

    ArrayList<Price> prices = new ArrayList<>();
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
      int id = (cursor.getInt(cursor.getColumnIndex(PriceTable.COLUMN_NAME_ID)));
      int stationId = (cursor.getInt(cursor.getColumnIndex(PriceTable.COLUMN_NAME_STATION_ID)));
      int productClass =
          (cursor.getInt(cursor.getColumnIndex(PriceTable.COLUMN_NAME_PRODUCT_CLASS)));
      Double priceValue = (cursor.getDouble(cursor.getColumnIndex(PriceTable.COLUMN_NAME_PRICE)));
      int verified = (cursor.getInt(cursor.getColumnIndex(PriceTable.COLUMN_NAME_VERIFIED)));
      int createdAt = (cursor.getInt(cursor.getColumnIndex(PriceTable.COLUMN_NAME_CREATED_AT)));
      String productName =
          (cursor.getString(cursor.getColumnIndex(PriceTable.COLUMN_NAME_PRODUCT_NAME)));
      Price price =
          new Price(createdAt, id, priceValue, productClass, productName, stationId, verified);
      prices.add(price);
      cursor.moveToNext();
    }
    cursor.close();
    return prices;
  }
  /**
   * @param url the cached URL
   * @return the cached result for the URL or null
   */
  public CachedUrlResult getUrlResult(String url) {
    Cursor cursor =
        database.rawQuery(
            "select "
                + DatabaseHelper.COLUMN_BODY
                + ", "
                + DatabaseHelper.COLUMN_DATETIME
                + " FROM "
                + DatabaseHelper.TABLE_URLS
                + " where "
                + DatabaseHelper.COLUMN_URL
                + " = ?",
            new String[] {url});

    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
      String body = cursor.getString(0);
      long dateTime = cursor.getInt(1);
      return new UrlResultImpl(url, body, dateTime);
    }
    cursor.close();

    // Didn't find the url
    return null;
  }
  protected static List<Action> getAlarmActions(
      SleepAsAndroidConstants.SLEEP_AS_ANDROID_ALARM_EVENT event) throws Exception {
    ArrayList<Action> actions = new ArrayList<>();

    String[] columns = {
      SleepAsAndroidActionTable.COLUMN_ALARM_TYPE_ID, SleepAsAndroidActionTable.COLUMN_ACTION_ID
    };
    Cursor cursor =
        DatabaseHandler.database.query(
            SleepAsAndroidActionTable.TABLE_NAME,
            columns,
            SleepAsAndroidActionTable.COLUMN_ALARM_TYPE_ID + "==" + event.getId(),
            null,
            null,
            null,
            null);
    cursor.moveToFirst();

    while (!cursor.isAfterLast()) {
      Long actionId = cursor.getLong(1);
      actions.add(ActionHandler.get(actionId));
      cursor.moveToNext();
    }

    cursor.close();
    return actions;
  }
예제 #9
0
  /**
   * Return a Cursor over the list of all todo in the database
   *
   * @return Cursor over all notes
   */
  public List<BookInfo> fetchAllBooks() {

    // createBook(new BookInfo("Agile Estimating and Planning", "Mike Cohn", "Paperback", "Book
    // Description", 324, "2005-08-21", "Prentice Hall", "123455432"));

    List<BookInfo> bookList = new ArrayList<BookInfo>();

    Cursor results = database.query(DATABASE_TABLE, null, null, null, null, null, null);

    results.moveToFirst();
    while (!results.isAfterLast()) {
      BookInfo thisBook = new BookInfo();

      thisBook.setId(results.getInt(0));
      thisBook.setTitle(results.getString(1));
      thisBook.setAuthor(results.getString(2));
      thisBook.setEdition(results.getString(3));
      thisBook.setDescription(results.getString(4));
      thisBook.setPages(new Integer(results.getString(5)));
      thisBook.setReleaseDate(results.getString(6));
      thisBook.setPublisher(results.getString(7));
      thisBook.setIsbn(results.getString(8));

      bookList.add(thisBook);

      results.moveToNext();
    }

    results.close();

    return bookList;
  }
예제 #10
0
  public ArrayList<Ingredient> getRecipeIngredients(String recipeName) {
    Log.d(TAG, "getRecipeIngredients recipeName: " + recipeName);
    SQLiteDatabase db = getReadableDatabase();
    ArrayList<Ingredient> list = new ArrayList<>();

    String statment =
        "SELECT * FROM "
            + TABLE_INGREDIENTS
            + " WHERE "
            + ING_COL_RECIPE_NAME
            + "='"
            + recipeName
            + "';";

    Cursor cursor = db.rawQuery(statment, null);

    if (cursor.isAfterLast()) {
      return null;
    }

    while (cursor.moveToNext()) {
      Ingredient ingredient =
          new Ingredient(
              cursor.getDouble(2), Unit.returnUnitByInt(cursor.getInt(3)), cursor.getString(1));
      list.add(ingredient);
    }
    return list;
  }
예제 #11
0
 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;
 }
예제 #12
0
  public ArrayList<String> getBoughtProducts() {
    database = getReadableDatabase();

    ArrayList<String> productNames = new ArrayList<String>();

    Cursor cursor =
        database.rawQuery(
            "SELECT "
                + PRODUCT_NAME
                + " FROM  "
                + TABLE_PRODUCT
                + " AS P JOIN "
                + TABLE_BOUGHTPRODUCTS
                + " AS BP ON P."
                + PRODUCT_ID
                + "=BP."
                + BOUGHTPRODUCTS_PRODUCT
                + " ORDER BY BP."
                + BOUGHTPRODUCTS_TIMESTAMP
                + " DESC",
            null);

    cursor.moveToFirst();

    while (!cursor.isAfterLast()) {
      String name = cursor.getString(0);
      productNames.add(name);
      cursor.moveToNext();
    }

    cursor.close();
    database.close();

    return productNames;
  }
  public ArrayList<AuctionItem> getAllAuctions() {
    ArrayList<AuctionItem> allAuctions = new ArrayList<AuctionItem>();
    SQLiteDatabase db = dbHelper.getReadableDatabase();

    Cursor cursor = db.rawQuery("SELECT * FROM " + AUCTIONS_TABLE + ";", null);

    if (cursor != null) {
      if (cursor.moveToFirst()) {
        while (cursor.isAfterLast() == false) {
          AuctionItem auction = new AuctionItem();

          auction.id = cursor.getInt(cursor.getColumnIndex("ID"));
          auction.name = cursor.getString(cursor.getColumnIndex(AUCTIONS_NAME));
          auction.starting_price =
              Double.parseDouble(cursor.getString(cursor.getColumnIndex(AUCTIONS_STARTING_PRICE)));
          auction.created_by = cursor.getString(cursor.getColumnIndex(AUCTIONS_CREATED_BY));
          auction.highest_bid =
              Double.parseDouble(cursor.getString(cursor.getColumnIndex(AUCTIONS_HIGHEST_BID)));
          auction.highest_bidder = cursor.getString(cursor.getColumnIndex(AUCTIONS_HIGHEST_BIDDER));
          auction.hours_active =
              Integer.parseInt(cursor.getString(cursor.getColumnIndex(AUCTIONS_HOURS_ACTIVE)));

          allAuctions.add(auction);
          cursor.moveToNext();
        }
      }
      cursor.close();
    }

    return allAuctions;
  }
예제 #14
0
  public List<String> getProductNames() {
    database = this.getReadableDatabase();
    ArrayList<String> names = new ArrayList<String>();
    String[] columns = {SQLiteHelper.PRODUCT_NAME};
    Cursor cursor =
        database.query(
            SQLiteHelper.TABLE_PRODUCT,
            columns,
            null,
            null,
            null,
            null,
            SQLiteHelper.PRODUCT_NAME + " ASC");

    cursor.moveToFirst();

    while (!cursor.isAfterLast()) {
      String name = cursor.getString(cursor.getColumnIndex(PRODUCT_NAME));
      names.add(name);
      cursor.moveToNext();
    }

    cursor.close();
    database.close();

    return names;
  }
예제 #15
0
  @Override
  public ShoppingList getShoppingListFromDatabase() {
    database = this.getReadableDatabase();
    ShoppingList list = new ShoppingList();
    Cursor cursor =
        database.query(
            SQLiteHelper.TABLE_SHOPPINGLIST,
            null,
            null,
            null,
            null,
            null,
            SQLiteHelper.SHOPPINGLIST_PRODUCT + " DESC");

    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
      int id = cursor.getInt(cursor.getColumnIndex(SHOPPINGLIST_PRODUCT));
      Product p = getProductById(id);

      if (p != null) {
        list.addToList(p);
      }
      cursor.moveToNext();
    }
    cursor.close();
    database.close();

    return list;
  }
예제 #16
0
  public int countSamples() {
    try {
      synchronized (dbLock) {
        if (db == null || !db.isOpen()) {
          try {
            db = helper.getWritableDatabase();
          } catch (android.database.sqlite.SQLiteException ex) {
            Log.e(TAG, "Could not open database", ex);
            return -1;
          }
        }

        Cursor cursor = db.rawQuery("select count(timestamp) FROM " + SAMPLES_VIRTUAL_TABLE, null);

        if (cursor == null) {
          // There are no results
          return -1;
        } else {
          int ret = -1;
          cursor.moveToFirst();
          while (!cursor.isAfterLast()) {
            ret = cursor.getInt(0);
            cursor.moveToNext();
          }
          cursor.close();
          return ret;
        }
      }
    } catch (Throwable th) {
      Log.e(TAG, "Failed to query oldest samples!", th);
    }
    return -1;
  }
예제 #17
0
  public List<Sms> getAllSms() {
    List<Sms> smsList = new ArrayList<Sms>();

    Cursor cursor =
        database.query(
            MySQLiteHelper.TABLE_SMS,
            allColumns,
            null,
            null,
            null,
            null,
            MySQLiteHelper.COLUMN_SMS_ID + " DESC");

    cursor.moveToFirst();

    while (!cursor.isAfterLast()) {
      Sms sms = cursorToSms(cursor);
      smsList.add(sms);

      cursor.moveToNext();
    }

    // make sure to close the cursor
    cursor.close();
    return smsList;
  }
예제 #18
0
  public Recipe getRecipe(String name) {
    Log.d(TAG, "getRecipe Name: " + name);

    SQLiteDatabase db = getReadableDatabase();

    String statment =
        "SELECT * FROM " + TABLE_RECIPES + " WHERE " + RECIPE_COL_NAME + "='" + name + "';";

    Cursor cursor = db.rawQuery(statment, null);

    if (cursor.isAfterLast()) {
      return null;
    }
    cursor.moveToFirst();
    Recipe recipe =
        new Recipe(
            name,
            null,
            cursor.getString(1),
            cursor.getString(2),
            BitmapUtils.StringToBitMap(cursor.getString(3)));
    cursor.close();
    ArrayList<Ingredient> list = getRecipeIngredients(name);
    recipe.setIngredientList(list);

    return recipe;
  }
예제 #19
0
  private String getNotes(String sortOrder) {
    Uri uri = NoteTable.CONTENT_URI;
    ContentResolver cr = getContentResolver();
    String[] projection =
        new String[] {
          NoteTable._ID,
          NoteTable.TITLE,
          NoteTable.DESCRIPTION,
          NoteTable.MODIFIED_DATE,
          NoteTable.TYPE
        };
    Cursor c = cr.query(uri, projection, null, null, sortOrder);

    int iId = c.getColumnIndex(NoteTable._ID);
    int iTitle = c.getColumnIndex(NoteTable.TITLE);
    int iDescription = c.getColumnIndex(NoteTable.DESCRIPTION);
    int iType = c.getColumnIndex(NoteTable.TYPE);

    JSONArray res = new JSONArray();
    try {
      for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(NoteTable._ID, c.getString(iId));
        jsonObject.put(NoteTable.TITLE, c.getString(iTitle));
        jsonObject.put(NoteTable.DESCRIPTION, c.getString(iDescription));
        jsonObject.put(NoteTable.TYPE, c.getInt(iType));
        res.put(jsonObject);
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }

    return res.toString();
  }
예제 #20
0
  @Override
  public List<Device> getAllDevices() {
    List<Device> devices = null;
    try {
      open();

      devices = new ArrayList<Device>();

      Cursor cursor = db.query(TABLE.ASSET.toString(), null, null, null, null, null, null);

      cursor.moveToFirst();
      while (!cursor.isAfterLast()) {
        Device device = cursorToDevice(cursor);
        devices.add(device);
        cursor.moveToNext();
      }
      cursor.close();
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      close();
    }

    return devices;
  }
예제 #21
0
 private boolean isCursorValid(Cursor cursor) {
   // Check whether the cursor is valid or not.
   if (cursor == null || cursor.isClosed() || cursor.isBeforeFirst() || cursor.isAfterLast()) {
     return false;
   }
   return true;
 }
  private String getParentName(String parentGUID)
      throws ParentNotFoundException, NullCursorException {
    if (parentGUID == null) {
      return "";
    }
    if (SPECIAL_GUIDS_MAP.containsKey(parentGUID)) {
      return SPECIAL_GUIDS_MAP.get(parentGUID);
    }

    // Get parent name from database.
    String parentName = "";
    Cursor name = dataAccessor.fetch(new String[] {parentGUID});
    try {
      name.moveToFirst();
      if (!name.isAfterLast()) {
        parentName = RepoUtils.getStringFromCursor(name, BrowserContract.Bookmarks.TITLE);
      } else {
        Logger.error(
            LOG_TAG,
            "Couldn't find record with guid '" + parentGUID + "' when looking for parent name.");
        throw new ParentNotFoundException(null);
      }
    } finally {
      name.close();
    }
    return parentName;
  }
예제 #23
0
  public ArrayList<String> getNewsPaperNames() {
    Cursor result;
    ArrayList<String> newsPaperNames = new ArrayList<String>();

    try {
      db = appCtx.openOrCreateDatabase(databaseName, Context.MODE_PRIVATE, null);
      result =
          db.query(
              true, tableName, new String[] {"NewsPaperName"}, null, null, null, null, null, null);

      result.moveToFirst();

      int newsPaperNameIndex = result.getColumnIndex("NewsPaperName");
      while (!result.isAfterLast()) {
        newsPaperNames.add(result.getString(newsPaperNameIndex));
        result.moveToNext();
      }

      result.close();
      db.close();
    } catch (SQLiteException exception) {
      Log.e("NewsPaperTableHandler::getNewsPaperNames", "Failed to get newspaper names");
    } catch (Exception exception) {
      Log.e("NewsPaperTableHandler::getNewsPaperNames", exception.getMessage());
    }

    return newsPaperNames;
  }
  private void sendResults(Long attemptId) {
    dbHelper = new DbHelper(this);
    Cursor cur = dbHelper.getUnsubmitted(attemptId.intValue());
    cur.moveToFirst();
    String content = "";
    while (cur.isAfterLast() == false) {
      content = dbHelper.createSubmitResponseObject(cur);
      cur.moveToNext();
    }
    cur.close();
    dbHelper.close();

    APIRequest[] resultsToSend = new APIRequest[1];
    APIRequest r = new APIRequest();
    r.fullurl =
        prefs.getString("prefServer", getString(R.string.prefServerDefault))
            + "api/?method=submit&format=json";
    r.rowId = attemptId.intValue();
    r.username = prefs.getString("prefUsername", "");
    r.password = prefs.getString("prefPassword", "");
    r.timeoutConnection = Integer.parseInt(prefs.getString("prefServerTimeoutConnection", "10000"));
    r.timeoutSocket = Integer.parseInt(prefs.getString("prefServerTimeoutResponse", "10000"));
    r.content = content;
    resultsToSend[0] = r;

    Toast.makeText(this, "Sending results", Toast.LENGTH_SHORT).show();

    // send results to server
    SubmitResultsTask task = new SubmitResultsTask(QuizActivityEnd.this);
    task.setDownloaderListener(this);
    task.execute(resultsToSend);
  }
예제 #25
0
  /**
   * Method loads data from the bridges table
   *
   * @param db data base to read the data frim
   */
  static void load(SQLiteDatabase db, Context context) {
    assert (db != null);
    assert (context != null);
    Cursor cursor = db.rawQuery("select * from " + BridgeEntry.TABLE_NAME, null);

    if (cursor.moveToFirst()) {
      Bridge bridge;

      while (!cursor.isAfterLast()) {
        int id = cursor.getInt(cursor.getColumnIndex(BridgeEntry.COLUMN_NAME_BRIDGE_ID));
        String userDefName =
            cursor.getString(cursor.getColumnIndex(BridgeEntry.COLUMN_NAME_USER_DEF_NAME));
        if (userDefName == null)
          userDefName = context.getResources().getString(R.string.default_bridge);
        bridge =
            new Bridge(
                id,
                userDefName,
                cursor.getString(cursor.getColumnIndex(BridgeEntry.COLUMN_NAME_FACTORY_NAME)));

        DataManager.getInstance().addBridge(bridge);
        if (cursor.getInt(cursor.getColumnIndex(BridgeEntry.COLUMN_NAME_ACTIVE)) == 1)
          DataManager.getInstance().setActiveBridgeId(id);

        cursor.moveToNext();
      }

      cursor.close();
    }
  }
예제 #26
0
  /**
   * Gets a sequence of API calls from the queue for the given endpoint. Does not remove items from
   * queue.
   *
   * @param writeKey The writeKey to peek for queued calls for.
   * @param endPoint The type of api call to get a batch for (based on end point).
   */
  public Vector<QueuedApiCall> getBatch(String writeKey, String endPoint) {
    Cursor cursor =
        getWritableDatabase()
            .query(
                TABLE_QUEUE, /* All columns */
                null,
                "write_key = ?",
                new String[] {writeKey},
                null,
                null,
                /* ORDER BY */ "id ASC", /* LIMIT */
                "100");

    Vector<QueuedApiCall> batch = new Vector<QueuedApiCall>();
    if (cursor != null && cursor.moveToFirst()) {
      while (!cursor.isAfterLast()) {
        String callEndPoint = cursor.getString(cursor.getColumnIndex("endpoint"));
        if (!callEndPoint.equalsIgnoreCase(endPoint)) {
          break; // Different type, stop batch
        }
        batch.add(
            new QueuedApiCall(
                cursor.getLong(cursor.getColumnIndex("id")),
                cursor.getString(cursor.getColumnIndex("endpoint")),
                cursor.getString(cursor.getColumnIndex("payload")),
                cursor.getString(cursor.getColumnIndex("write_key"))));
        cursor.moveToNext();
      }
    }
    cursor.close();
    return batch;
  }
  /**
   * Fetches the full list of Posts stored in the local Database
   *
   * @param context
   * @return
   */
  public static List<Post> getPosts(Context context) {
    DatabaseWrapper databaseWrapper = new DatabaseWrapper(context);
    SQLiteDatabase database = databaseWrapper.getReadableDatabase();

    List<Post> postList = null;

    if (database != null) {
      Cursor cursor = database.rawQuery("SELECT * FROM " + PostORM.TABLE_NAME, null);

      Log.i(TAG, "Loaded " + cursor.getCount() + " Posts...");
      if (cursor.getCount() > 0) {
        postList = new ArrayList<Post>();
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
          Post post = cursorToPost(cursor);
          post.setTags(TagORM.getTagsForPost(context, post));

          postList.add(post);
          cursor.moveToNext();
        }
        Log.i(TAG, "Posts loaded successfully.");
      }

      database.close();
    }

    return postList;
  }
  public List<CachedUrlResult> getAll() {
    List<CachedUrlResult> urlResults = new ArrayList<CachedUrlResult>();
    Cursor cursor =
        database.rawQuery(
            "select "
                + DatabaseHelper.COLUMN_URL
                + ", "
                + DatabaseHelper.COLUMN_BODY
                + ", "
                + DatabaseHelper.COLUMN_DATETIME
                + " FROM "
                + DatabaseHelper.TABLE_URLS
                + " where 1",
            new String[] {});

    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
      String body = cursor.getString(0);
      String url = cursor.getString(1);
      long dateTime = cursor.getInt(2);
      urlResults.add(new UrlResultImpl(url, body, dateTime));
    }
    cursor.close();
    return urlResults;
  }
  @MediumTest
  public void testCursor2() throws Exception {
    populateDefaultTable();

    Cursor c = mDatabase.query("test", null, "_id > 1000", null, null, null, null);
    assertEquals(0, c.getCount());
    assertTrue(c.isBeforeFirst());

    try {
      c.getInt(0);
      fail("CursorIndexOutOfBoundsException expected");
    } catch (CursorIndexOutOfBoundsException ex) {
      // expected
    }

    int i;
    for (c.moveToFirst(), i = 0; !c.isAfterLast(); c.moveToNext(), i++) {
      c.getInt(0);
    }
    assertEquals(0, i);
    try {
      c.getInt(0);
      fail("CursorIndexOutOfBoundsException expected");
    } catch (CursorIndexOutOfBoundsException ex) {
      // expected
    }
    c.close();
  }
예제 #30
0
  public boolean checkMissingTomesIcons(Handler handler) {
    Tome tome;

    Log.d(Global.getLogTag(MyDbAdaptor.class), "checkMissingTomesIcons");
    Cursor cursor =
        database.rawQuery(MySQLiteOpenHelper.SELECT_ALL_MISSING_WITHOUT_ICON_RQST, null);
    if (cursor.moveToFirst()) {
      while (!cursor.isAfterLast()) {
        tome = new Tome();
        tome.isMissingTome = true;
        tome.setId(cursor.getInt(cursor.getColumnIndex(MySQLiteOpenHelper.COL_MISSING_ID)));
        tome.setNumber(cursor.getInt(cursor.getColumnIndex(MySQLiteOpenHelper.COL_MISSING_NUMBER)));
        tome.setSerieId(
            cursor.getInt(cursor.getColumnIndex(MySQLiteOpenHelper.COL_MISSING_SERIE_ID)));
        tome.setTomePageUrl(
            cursor.getString(cursor.getColumnIndex(MySQLiteOpenHelper.COL_MISSING_PAGEURL)));
        tome.setIconUrl(
            cursor.getString(cursor.getColumnIndex(MySQLiteOpenHelper.COL_MISSING_ICONURL)));
        tome.setIcon(cursor.getBlob(cursor.getColumnIndex(MySQLiteOpenHelper.COL_MISSING_ICON)));
        ServerConnector.getMissingTomeIcon(handler, tome);
        cursor.moveToNext();
      }
    }
    cursor.close();
    return true;
  }