Example #1
0
 static Version getPrevVersion(String code) {
   // query(String table, String[] columns, String selection, String[] selectionArgs, String
   // groupBy, String having, String orderBy)
   Cursor cursor =
       sqlite.query(
           res.getString(R.string.DATABASE_TABLE_VERSION),
           null,
           null,
           null,
           null,
           null,
           res.getString(R.string.KEY_ORDER) + " DESC");
   cursor.moveToFirst();
   Version r;
   boolean found = false;
   while (!found) {
     r = new Version(cursor, res);
     if (r.getCode().equals(code)) {
       found = true;
     }
     if (cursor.isLast()) {
       cursor
           .moveToFirst(); // if still not found, then this version must be the last one. So the
                           // target version is the first entry
       break;
     }
     cursor.moveToNext();
   }
   r = new Version(cursor, res);
   cursor.close();
   return r;
 }
Example #2
0
  public void testAddQueueItemSingleItemAlreadyInQueue()
      throws InterruptedException, ExecutionException, TimeoutException {
    final Context context = getInstrumentation().getTargetContext();
    Feed feed = new Feed("url", null, "title");
    feed.setItems(new ArrayList<>());
    FeedItem item = new FeedItem(0, "title", "id", "link", new Date(), FeedItem.PLAYED, feed);
    feed.getItems().add(item);

    PodDBAdapter adapter = PodDBAdapter.getInstance();
    adapter.open();
    adapter.setCompleteFeed(feed);
    adapter.close();

    assertTrue(item.getId() != 0);
    DBWriter.addQueueItem(context, item).get(TIMEOUT, TimeUnit.SECONDS);

    adapter = PodDBAdapter.getInstance();
    adapter.open();
    Cursor cursor = adapter.getQueueIDCursor();
    assertTrue(cursor.moveToFirst());
    assertTrue(cursor.getLong(0) == item.getId());
    cursor.close();
    adapter.close();

    DBWriter.addQueueItem(context, item).get(TIMEOUT, TimeUnit.SECONDS);
    adapter = PodDBAdapter.getInstance();
    adapter.open();
    cursor = adapter.getQueueIDCursor();
    assertTrue(cursor.moveToFirst());
    assertTrue(cursor.getLong(0) == item.getId());
    assertTrue(cursor.getCount() == 1);
    cursor.close();
    adapter.close();
  }
  @Override
  public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {

    if ((cursor.moveToFirst()) && (cursor.getCount() == 1)) {
      // Check to see if there is a no artists flag in the cursor indicating that
      // there are no artists for the given search term.
      String flag = cursor.getString(COL_ARTIST_SPOTIFY_ID);
      if (flag.equals(DataContract.ArtistEntry.FLAG_NO_ARTISTS_FOUND)) {
        Toast toast =
            Toast.makeText(
                getActivity(), getString(R.string.toast_no_artist_found), Toast.LENGTH_LONG);
        toast.show();
      } else {
        mArtistsAdapter.swapCursor(cursor);
      }
    } else if (cursor.moveToFirst()) {
      Log.i(
          TAG,
          "onLoadFinished called and cursor.moveToFirst() is true. mArtistAdapter swaps with cursor");
      mArtistsAdapter.swapCursor(cursor);
      if (mPosition != ListView.INVALID_POSITION) {
        mListView.smoothScrollToPosition(mPosition);
      }
    } else if (null
        != mSearchTerm) { // if the cursor is null, this means that the artists for mSearchTerm have
      // not been added to the db.
      Log.i(
          TAG,
          "onLoadFinished called, cursor is empty, and mSearchTerm is "
              + mSearchTerm
              + ". getArtists() called to start new FetchArtistsTask");
      getArtists();
    }
  }
  @Override
  public void onHandleIntent(Intent intent) {
    ComponentName me = new ComponentName(this, AppWidget.class);
    RemoteViews updateViews = new RemoteViews("apt.tutorial", R.layout.widget);
    RestaurantHelper helper = new RestaurantHelper(this);
    AppWidgetManager mgr = AppWidgetManager.getInstance(this);

    try {
      Cursor c = helper.getReadableDatabase().rawQuery(SQL_QUERY_COUNT, null);
      c.moveToFirst();
      int count = c.getInt(0);
      c.close();
      if (count > 0) {
        int offset = (int) (count * Math.random());
        String args[] = {String.valueOf(offset)};
        c = helper.getReadableDatabase().rawQuery(SQL_QUERY_SELECT, args);
        c.moveToFirst();
        updateViews.setTextViewText(R.id.name, c.getString(1));
        Intent i = new Intent(this, DetailForm.class);
        i.putExtra(LunchList.ID_EXTRA, c.getString(0));
        PendingIntent pi = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
        updateViews.setOnClickPendingIntent(R.id.name, pi);
        c.close();
      } else {
        updateViews.setTextViewText(R.id.title, this.getString(R.string.empty));
      }
    } finally {
      helper.close();
    }

    Intent i = new Intent(this, WidgetService.class);
    PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
    updateViews.setOnClickPendingIntent(R.id.next, pi);
    mgr.updateAppWidget(me, updateViews);
  }
  public float queryFoodTypeFraction(int type_index, String fromDate, String toDate) {
    String type = Integer.toString(type_index);
    String nextDay = DatePickerFragment.stringToNextDate(toDate);
    SQLiteDatabase db = this.getReadableDatabase();
    Log.d("FoodDBHelper", "queryFoodTypeFraction:" + fromDate + "_" + nextDay + " for " + type);

    // Log.d("queryLatest", GET_TRANSACTIONS_FOR_INTERVAL);
    Cursor denominator_cursor =
        db.rawQuery(GET_TRANSACTIONS_FOR_INTERVAL, new String[] {fromDate, nextDay});
    float fraction = 0.0f;
    if (denominator_cursor.getCount() > 0) {
      denominator_cursor.moveToFirst();
      float numerator = denominator_cursor.getFloat(denominator_cursor.getColumnIndex("all_count"));

      // Log.d("queryLatest", GET_TYPE_NUM_FOR_INTERVAL);
      Cursor numerator_cursor =
          db.rawQuery(
              GET_TYPE_NUM_FOR_INTERVAL, new String[] {type, type, type, fromDate, nextDay});
      if (numerator_cursor.getCount() > 0) {
        numerator_cursor.moveToFirst();
        fraction =
            numerator_cursor.getFloat(numerator_cursor.getColumnIndex("type_count")) / numerator;
      }
    }
    return fraction;
  }
 /**
  * 直接根据uri 获取图片
  *
  * @param context context
  * @param uri uri
  * @param cut 是否裁剪
  * @param callBack 回调
  */
 public static void getImagePathFromURI(
     Context context, Uri uri, boolean cut, PhotoCallBack callBack) {
   Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
   cursor.moveToFirst();
   String document_id = cursor.getString(0);
   document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
   cursor.close();
   cursor =
       context
           .getContentResolver()
           .query(
               MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
               null,
               MediaStore.Images.Media._ID + " = ? ",
               new String[] {document_id},
               null);
   cursor.moveToFirst();
   String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
   cursor.close();
   if (callBack != null) {
     callBack.Success(path);
   }
   if (cut) {
     doCropPhoto(context, uri, new File(path));
   }
 }
Example #7
0
  public LessonListElement getClosestLesson(int weekState, int day, int number) {
    LessonListElement result = null;
    try {
      Cursor c;
      c = getCursorClosestLessonByNumber(weekState, day, number);
      if (c.moveToFirst()) { // if has lesson today
        result = getLessonFromCursor(c);
      } else {
        c = getCursorClosestLessonByDay(weekState, day);
        if (c.moveToFirst()) { // if has lesson in other days on this week
          result = getLessonFromCursor(c);
        } else {
          c = getCursorClosestLessonFromOtherWeek(weekState);
          if (c.moveToFirst()) { // if has lesson on other week
            result = getLessonFromCursor(c);
          }
        }
      }
      c.close();
    } catch (Exception e) {
      e.printStackTrace();
    }

    return result;
  }
Example #8
0
  @Override
  public void onUpdate(Context ctxt, AppWidgetManager mgr, int[] appWidgetIds) {
    ComponentName me = new ComponentName(ctxt, AppWidget.class);
    RemoteViews updateViews = new RemoteViews("apt.tutorial", R.layout.widget);
    SQLiteDatabase db = (new RestaurantSQLiteHelper(ctxt)).getReadableDatabase();

    try {
      Cursor c = db.rawQuery("SELECT COUNT(*) FROM restaurants", null);

      c.moveToFirst();

      int count = c.getInt(0);

      c.close();

      if (count > 0) {
        int offset = (int) (count * Math.random());
        String args[] = {String.valueOf(offset)};

        c = db.rawQuery("SELECT name FROM restaurants LIMIT 1 OFFSET ?", args);
        c.moveToFirst();
        updateViews.setTextViewText(R.id.name, c.getString(0));
      } else {
        updateViews.setTextViewText(R.id.name, ctxt.getString(R.string.empty));
      }
    } finally {
      db.close();
    }

    mgr.updateAppWidget(me, updateViews);
  }
Example #9
0
  private static long getLastPlannedIntakeDate(Context context, long idMedicine) {
    String[] projection = {
      "MAX(" + DBContract.Intakes.COLUMN_NAME_DATE + ") AS " + DBContract.Intakes.COLUMN_NAME_DATE
    };
    String selection = DBContract.Intakes.COLUMN_NAME_ID_MEDICINE + " = ?";
    String[] selectionArgs = {Long.valueOf(idMedicine).toString()};
    long last;

    Cursor cursor =
        context
            .getContentResolver()
            .query(
                LembramoContentProvider.CONTENT_URI_INTAKES,
                projection,
                selection,
                selectionArgs,
                null);

    cursor.moveToFirst();
    if (cursor.moveToFirst())
      last = cursor.getLong(cursor.getColumnIndex(DBContract.Intakes.COLUMN_NAME_DATE));
    else last = 0;
    cursor.close();
    return last;
  }
Example #10
0
  public List<Note> getAllRemindersByTag(String tag) { // only returns notes, NOT reminders
    List<Note> mNotes = new ArrayList<Note>();
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cur =
        db.rawQuery(
            "select id, title, note_text,type from note_tags join notes on note_id = id where type = 1 and tag_name = "
                + tag,
            null);

    if (cur.moveToFirst()) {
      do {
        Note n = new Note();
        n.id = cur.getInt(0);
        n.text = cur.getString(2);
        n.title = cur.getString(1);
        n.type = cur.getInt(3);
        Cursor cur2 = db.rawQuery("select tag_name from note_tags where note_id = " + n.id, null);
        if (cur2.moveToFirst()) {
          do {
            n.tags.add(new String(cur2.getString(0)));
          } while (cur2.moveToNext());
        }
        mNotes.add(n);
      } while (cur.moveToNext());
    }

    return mNotes;
  }
Example #11
0
  public List<Note> getAllReminders() {
    List<Note> mNotes = new ArrayList<Note>();
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cur = db.rawQuery("select * from notes where type = 1", null);

    if (cur.moveToFirst()) {
      do {
        Note n = new Note();
        n.id = cur.getInt(cur.getColumnIndex("id"));
        n.text = cur.getString(cur.getColumnIndex("note_text"));
        n.title = cur.getString(cur.getColumnIndex("title"));
        n.type = cur.getInt(cur.getColumnIndex("type"));
        Cursor cur2 = db.rawQuery("select tag_name from note_tags where note_id = " + n.id, null);
        if (cur2.moveToFirst()) {
          do {
            n.tags.add(new String(cur2.getString(0)));
          } while (cur2.moveToNext());
        }
        mNotes.add(n);
      } while (cur.moveToNext());
    }

    return mNotes;
  }
Example #12
0
  @Override
  public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub
    db = new DBHelper(context);
    mContext = context;
    Calendar c = Calendar.getInstance();
    int yy = c.get(Calendar.YEAR);
    int mm = c.get(Calendar.MONTH) + 1;
    int dd = c.get(Calendar.DATE);
    int hh = c.get(Calendar.HOUR_OF_DAY);
    int mn = c.get(Calendar.MINUTE);
    int nw = (hh * 60) + mn;

    Cursor cur = db.getAllTaskByDate(yy, mm, dd);
    if (cur.moveToFirst()) {
      do {
        int tstime = cur.getInt(cur.getColumnIndex("stime"));
        int tstimem = cur.getInt(cur.getColumnIndex("stimem"));
        int tt = (tstime * 60) + tstimem;
        if ((tt - nw) <= 5 && (tt - nw) > 0) {
          String title = cur.getString(cur.getColumnIndex("tname"));
          showNotification(context, 1, title, "Starts at " + tstime + ":" + tstimem);
        }

      } while (cur.moveToNext());
    }
    cur.close();
    if (mm == 0) {
      Cursor lcur = db.getLogin();
      int id = 0;
      if (lcur.moveToFirst()) {
        id = lcur.getInt(lcur.getColumnIndex("uid"));
      }
      lcur.close();
      Cursor mcur = db.getTaskByPendingSync();

      if (mcur.moveToFirst()) {
        do {
          int tid = mcur.getInt(mcur.getColumnIndex("tid"));
          int rating = mcur.getInt(mcur.getColumnIndex("rating"));
          String feedback = mcur.getString(mcur.getColumnIndex("feedback"));
          if (isNetworkAvailable() && id != 0) {
            new RequestTask()
                .execute(
                    context.getResources().getString(R.string.server)
                        + "services/feedbackcollector.php?"
                        + "id="
                        + id
                        + "&tid="
                        + tid
                        + "&rating="
                        + rating
                        + "&feedback="
                        + feedback);
          }
        } while (mcur.moveToNext());
      }
      mcur.close();
    }
  }
  private String retrieveContactNumber() {
    String formattedContactNumber = null;
    Cursor cursorID =
        getContentResolver()
            .query(uriContact, new String[] {ContactsContract.Contacts._ID}, null, null, null);
    if (cursorID.moveToFirst())
      contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID));
    cursorID.close();

    Cursor cursorPhone =
        getContentResolver()
            .query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                new String[] {ContactsContract.CommonDataKinds.Phone.NUMBER},
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                    + " = ? AND "
                    + ContactsContract.CommonDataKinds.Phone.TYPE
                    + " = "
                    + ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
                new String[] {contactID},
                null);

    if (cursorPhone.moveToFirst()) {
      formattedContactNumber =
          cursorPhone.getString(
              cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
    }
    cursorPhone.close();
    String contactNumber = null;
    if (formattedContactNumber != null) {
      contactNumber = getNonFormattedNumber(formattedContactNumber);
    }

    return contactNumber;
  }
  public List<EdificioMOD> getEdificioListbyTipoSitio(String Nombre) {
    List<EdificioMOD> lista = new ArrayList<EdificioMOD>();
    EdificioMOD _edificioMOD;
    String Idcampus = "";

    String sql1 = "select idEdificio from sitio where tipo='" + Nombre + "'";
    Cursor ccc = database.rawQuery(sql1, null);
    if (ccc.moveToFirst()) {

      do {
        Idcampus = ccc.getString(0);

        String sql =
            "select nombreEdificio from edificio where idEdificio ='"
                + Idcampus
                + "' order by nombreEdificio asc";
        Cursor c = database.rawQuery(sql, null);

        if (c != null && c.moveToFirst()) {
          do {
            _edificioMOD = new EdificioMOD();
            _edificioMOD.setNombreEdificio(c.getString(c.getColumnIndex("nombreEdificio")));

            lista.add(_edificioMOD);
          } while (c.moveToNext());
        }

      } while (ccc.moveToNext());
    }

    return lista;
  }
  @SuppressWarnings("resource")
  public void testWipe() {
    ClientRecord record1 = new ClientRecord();
    ClientRecord record2 = new ClientRecord();
    String profileConst = Constants.DEFAULT_PROFILE;

    db.store(profileConst, record1);
    db.store(profileConst, record2);

    Cursor cur = null;
    try {
      // Test before wipe the records are there.
      cur = db.fetchClientsCursor(record2.guid, profileConst);
      assertTrue(cur.moveToFirst());
      assertEquals(1, cur.getCount());
      cur = db.fetchClientsCursor(record2.guid, profileConst);
      assertTrue(cur.moveToFirst());
      assertEquals(1, cur.getCount());

      // Test after wipe neither record exists.
      db.wipeClientsTable();
      cur = db.fetchClientsCursor(record2.guid, profileConst);
      assertFalse(cur.moveToFirst());
      assertEquals(0, cur.getCount());
      cur = db.fetchClientsCursor(record1.guid, profileConst);
      assertFalse(cur.moveToFirst());
      assertEquals(0, cur.getCount());
    } catch (NullCursorException e) {
      fail("Should not have NullCursorException");
    } finally {
      if (cur != null) {
        cur.close();
      }
    }
  }
Example #16
0
 private void logVerboseOpenFileInfo(Uri uri, String mode) {
   Log.v(
       Constants.TAG,
       "openFile uri: " + uri + ", mode: " + mode + ", uid: " + Binder.getCallingUid());
   Cursor cursor = query(Downloads.CONTENT_URI, new String[] {"_id"}, null, null, "_id");
   if (cursor == null) {
     Log.v(Constants.TAG, "null cursor in openFile");
   } else {
     if (!cursor.moveToFirst()) {
       Log.v(Constants.TAG, "empty cursor in openFile");
     } else {
       do {
         Log.v(Constants.TAG, "row " + cursor.getInt(0) + " available");
       } while (cursor.moveToNext());
     }
     cursor.close();
   }
   cursor = query(uri, new String[] {"_data"}, null, null, null);
   if (cursor == null) {
     Log.v(Constants.TAG, "null cursor in openFile");
   } else {
     if (!cursor.moveToFirst()) {
       Log.v(Constants.TAG, "empty cursor in openFile");
     } else {
       String filename = cursor.getString(0);
       Log.v(Constants.TAG, "filename in openFile: " + filename);
       if (new java.io.File(filename).isFile()) {
         Log.v(Constants.TAG, "file exists in openFile");
       }
     }
     cursor.close();
   }
 }
  public int getCurrentDataVersion() {
    int currentDataVersion = 0;

    // Query parameters
    String table = TABLE_NAME;
    String[] columns = allColumns;
    String selection = "name = 'data_version'";
    String[] selectionArgs = null;
    String groupBy = null;
    String having = null;
    String orderBy = null;
    String limit = null;

    // Execute query
    Cursor cursor =
        database.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
    cursor.moveToFirst();

    if (!(cursor.moveToFirst()) || cursor.getCount() == 0) {
      currentDataVersion = 0;
    } else {
      currentDataVersion = Integer.valueOf(cursor.getString(cursor.getColumnIndex("value")));
    }
    cursor.close();

    return currentDataVersion;
  }
  /**
   * This function gets the true path from an image uri saved on your device. Could not figure this
   * out for myself so the credit for this function goes to the Stack OverFlow user: bluebrain URL:
   * http://stackoverflow.com/a/20470572/2203488
   *
   * <p>All this function does is essentially goes through a query of my image information via my
   * URI and then gets the first row in the cursor to give me my Image Path Name. It has to do some
   * substringing first because of an issue with KitKat 4.4
   *
   * @param questImageURI
   * @return path
   */
  public String getRealPathFromURI(Uri questImageURI) {

    // Get the Quest Cursor from the URI and Substring the value to get the KitKat Image ID
    Cursor questCurs =
        getActivity().getContentResolver().query(questImageURI, null, null, null, null);
    questCurs.moveToFirst();
    String img_id = questCurs.getString(0);
    img_id = img_id.substring(img_id.lastIndexOf(":") + 1);
    questCurs.close();

    // Get the new Cursor from the new Image ID to work with KITKAT
    questCurs =
        getActivity()
            .getContentResolver()
            .query(
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                null,
                MediaStore.Images.Media._ID + " = ? ",
                new String[] {img_id},
                null);
    questCurs.moveToFirst();

    // Get Image Path from Cursor
    String path = questCurs.getString(questCurs.getColumnIndex(MediaStore.Images.Media.DATA));
    questCurs.close();

    return path;
  }
  @Override
  public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    adapter.swapCursor(cursor);
    if (isDualPane) {
      if (cursor.moveToFirst()) {
        /** If list is not empty, trying to restore previously displayed details. */
        restoreHandler.sendEmptyMessage(0);
      } else {
        /** If list became empty, removing previously displayed details */
        removeDetailsHandler.sendEmptyMessage(0);
      }
    }

    /** If there is no sync going and list is empty, refreshing list. */
    Account account = AccountService.getAccount();
    if (account != null) {
      boolean syncActive = ContentResolver.isSyncActive(account, Contract.CONTENT_AUTHORITY);
      boolean syncPending = ContentResolver.isSyncPending(account, Contract.CONTENT_AUTHORITY);
      if (!cursor.moveToFirst() && firstLoad && !(syncActive || syncPending)) {
        refreshList();
      }
    }
    firstLoad = false;
    setRefreshIndicationState(updateManager.isUpdating(UpdateManager.UpdateType.ALARMS));
  }
Example #20
0
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View myView = inflater.inflate(R.layout.contentp_fragment, container, false);

    // get the one view I need.
    output = (TextView) myView.findViewById(R.id.TextView01);

    appendthis("Query for 2 square");
    // example, select one of them, in this case 2
    Uri onerow = Uri.parse("content://edu.cs4730.provider/square/2");
    Cursor c = getActivity().getContentResolver().query(onerow, null, null, null, null);
    if (c != null) {
      c.moveToFirst();
      do {
        Log.i(TAG, "Value is" + c.getString(0));
        appendthis(c.getString(0) + " value is " + c.getString(1));
      } while (c.moveToNext());
    }

    appendthis("\nQuery all for cube:");
    // now select "all", which will return 1 to 10 cubed.
    Uri allrow = Uri.parse("content://edu.cs4730.provider/cube");
    c = getActivity().getContentResolver().query(allrow, null, null, null, null);
    if (c != null) {
      c.moveToFirst();
      do {
        Log.i(TAG, "Value is " + c.getString(0));
        appendthis(c.getString(0) + " value is " + c.getString(1));
      } while (c.moveToNext());
    }

    return myView;
  }
Example #21
0
  /**
   * Gets a list of the 4 latestDynamicSets for a specific exercise.
   *
   * @param workoutId workoutId for current workout
   * @param exerciseId exerciseId for current exercise
   * @param exerciseTypeId exerciseTypeId for current exercise
   * @return
   */
  public List<SetsData> getPreviouslyDynamicSets(int exerciseId, int exerciseTypeId) {
    List<SetsData> dynamicSetsList = new LinkedList<SetsData>();
    open();
    Cursor c =
        ourDatabase.rawQuery(
            "SELECT Sets.SetWeight, Sets.SetReps FROM Sets, "
                + "Exercises WHERE "
                + "Sets.ExerciseId = "
                + exerciseId
                + " AND Exercises.ExerciseId = "
                + "Sets.ExerciseId AND "
                + "Exercises.ExerciseTypeId = "
                + exerciseTypeId
                + " ORDER BY SetId "
                + "DESC LIMIT 4;",
            null);
    c.moveToFirst();
    int weight = c.getColumnIndex("SetWeight");
    int reps = c.getColumnIndex("SetReps");

    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
      dynamicSetsList.add(new SetsData(c.getInt(weight), c.getInt(reps)));
    }

    c.close();
    close();
    return dynamicSetsList;
  }
Example #22
0
  /**
   * Gets a list of the 4 latestStaticSets for a specific exercise.
   *
   * @param workoutId
   * @param exerciseId
   * @param exerciseTypeId
   * @return
   */
  public List<SetsData> getPreviouslyStaticSets(int exerciseId, int exerciseTypeId) {
    List<SetsData> staticSetsList = new LinkedList<SetsData>();
    open();
    Cursor c =
        ourDatabase.rawQuery(
            "SELECT Sets.SetDuration, Sets.SetWeight FROM Sets, "
                + "Exercises WHERE "
                + "Sets.ExerciseId = "
                + exerciseId
                + " AND Exercises.ExerciseId = "
                + "Sets.ExerciseId AND "
                + "Exercises.ExerciseTypeId = "
                + exerciseTypeId
                + " ORDER BY SetId DESC LIMIT 4;",
            null);
    c.moveToFirst();
    int duration = c.getColumnIndex("SetDuration");
    int weight = c.getColumnIndex("SetWeight");

    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
      String durationString =
          (((int) (c.getInt(duration) / NUMBER_SECONDS_IN_HOUR))
              + "h "
              + (((int) (c.getInt(duration) / NUMBER_SECONDS_IN_MIN)) % NUMBER_SECONDS_IN_MIN)
              + "m "
              + (c.getInt(duration) % NUMBER_SECONDS_IN_MIN)
              + "s ");
      staticSetsList.add(new SetsData(c.getInt(weight), durationString));
    }

    c.close();
    close();
    return staticSetsList;
  }
Example #23
0
  /**
   * Gets a list of the 4 latest CardioSets for a specific exercise
   *
   * @param workoutId workoutId for current workout
   * @param exerciseId exerciseId for current exercise
   * @param exerciseTypeId exerciseTypeId for current exercise
   * @return A List containing the four latest sets in SetData objects with SetDuration and
   *     SetDistance parameters.
   */
  public List<SetsData> getPreviouslyCardioSets(int exerciseId, int exerciseTypeId) {
    List<SetsData> cardioSetsList = new LinkedList<SetsData>();
    open();
    Cursor c =
        ourDatabase.rawQuery(
            "SELECT Sets.SetDuration, Sets.SetDistance FROM Sets, "
                + "Exercises WHERE "
                + "Sets.ExerciseId = "
                + exerciseId
                + " AND Exercises.ExerciseId = Sets.ExerciseId AND "
                + "Exercises.ExerciseTypeId = "
                + exerciseTypeId
                + " ORDER BY SetId DESC LIMIT 4;",
            null);
    c.moveToFirst();
    int duration = c.getColumnIndex("SetDuration");
    int distance = c.getColumnIndex("SetDistance");

    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {

      // Equation for formating number of seconds a set has taken into a String with
      // format hh:mm:ss
      String durationString =
          (((int) (c.getInt(duration) / NUMBER_SECONDS_IN_HOUR))
              + "h "
              + (((int) (c.getInt(duration) / NUMBER_SECONDS_IN_MIN)) % NUMBER_SECONDS_IN_MIN)
              + "m "
              + (c.getInt(duration) % NUMBER_SECONDS_IN_MIN)
              + "s ");
      cardioSetsList.add(new SetsData(durationString, c.getInt(distance)));
    }
    c.close();
    close();
    return cardioSetsList;
  }
  public ArrayList<SpeakerSeminarsWrapper> getFavRecord() {
    ArrayList<SpeakerSeminarsWrapper> array = new ArrayList<SpeakerSeminarsWrapper>();

    String query1 =
        "Select  distinct title from  speakerSeminar where ClientCode=? and EventCode=? and favourites=?";

    Cursor c =
        dbAdapter.selectRecordsFromDB(
            query1, new String[] {MyUIApplication.ClientCode, MyUIApplication.EventCode, "true"});
    if (c.moveToFirst()) {
      do {
        String title = c.getString(c.getColumnIndex("Title"));

        String query = "Select * from  speakerSeminar where title=? limit 1";

        Cursor cursor = dbAdapter.selectRecordsFromDB(query, new String[] {title});
        if (cursor.moveToFirst()) {
          SpeakerSeminarsWrapper _objSpeakerWrapper = new SpeakerSeminarsWrapper();

          _objSpeakerWrapper.id = cursor.getString(cursor.getColumnIndex("_id"));
          _objSpeakerWrapper.name = cursor.getString(cursor.getColumnIndex("name"));
          _objSpeakerWrapper.Title = cursor.getString(cursor.getColumnIndex("Title"));
          _objSpeakerWrapper.Day = cursor.getString(cursor.getColumnIndex("Day"));
          _objSpeakerWrapper.description = cursor.getString(cursor.getColumnIndex("description"));
          _objSpeakerWrapper.visited = cursor.getString(cursor.getColumnIndex("visited"));
          _objSpeakerWrapper.favourites = cursor.getString(cursor.getColumnIndex("favourites"));

          array.add(_objSpeakerWrapper);
        }
      } while (c.moveToNext());
    }
    return array;
  }
Example #25
0
  /**
   * Returns a miniature-sized icon associated with the category These icons are used for the map
   * overlays and dialog windows.
   *
   * @param category The top-level category
   * @return If no icon is found, return the default Android icon. otherwise, return the appropriate
   *     category icon.
   */
  public static Integer getIcon(String category, Context context) {
    SQLiteDatabase db = new FINDatabase(context).getReadableDatabase();

    Cursor cursor =
        db.query("categories", null, "full_name = '" + category + "'", null, null, null, null);
    cursor.moveToFirst();

    int parent = cursor.getInt(cursor.getColumnIndex("parent"));
    if (parent != 0) {
      cursor = db.query("categories", null, "cat_id = " + parent, null, null, null, null);
      cursor.moveToFirst();
      category = cursor.getString(cursor.getColumnIndex("full_name"));
    }

    cursor.close();
    db.close();

    if (!category.equals("")) {
      int icon =
          context
              .getResources()
              .getIdentifier(
                  "drawable/" + FINUtil.sendCategory(category, context),
                  null,
                  context.getPackageName());
      if (icon != 0) {
        return icon;
      }
    }

    return R.drawable.android;
  }
Example #26
0
 public ThemeInfo getCurrentThemeInfo() {
   ContentResolver contentResolver = getContext().getContentResolver();
   if (mCurrentThemeInfo == null) {
     String where = ThemeColumns.IS_APPLY + "=" + 1;
     Cursor cursor = contentResolver.query(ThemeColumns.CONTENT_URI, null, where, null, null);
     if (cursor != null) {
       if (cursor.moveToFirst()) {
         mCurrentThemeInfo = ThemeInfo.CreateFromDB(cursor);
       }
       cursor.close();
     }
     if (mCurrentThemeInfo == null) {
       HomeUtils.markThemeAsApply(
           getContext(), HomeDataBaseHelper.getInstance(getContext()).getDefaultThemeID());
       cursor = contentResolver.query(ThemeColumns.CONTENT_URI, null, where, null, null);
       if (cursor != null) {
         if (cursor.moveToFirst()) {
           mCurrentThemeInfo = ThemeInfo.CreateFromDB(cursor);
         }
         cursor.close();
       }
     }
     if (mCurrentThemeInfo == null) {
       // 数据库错误,删除数据库
       HomeUtils.deleteFile(getContext().getDatabasePath(ProviderUtils.DATABASE_NAME).getParent());
       Process.killProcess(Process.myPid());
     }
   }
   mCurrentThemeInfo.initFromXML(getContext());
   return mCurrentThemeInfo;
 }
  private void analysisAttribute() {
    long videoId = -1;
    String whereClause = MediaStore.Video.Media.DISPLAY_NAME + "='" + mFileName + "'";
    ContentResolver cr = AndroidFactory.getApplicationContext().getContentResolver();
    Cursor cursor = null;
    try {
      cursor =
          cr.query(
              MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
              new String[] {
                MediaStore.Video.VideoColumns._ID, MediaStore.Video.VideoColumns.DURATION
              },
              whereClause,
              null,
              null);
      if (cursor != null && cursor.getCount() != 0) {
        cursor.moveToFirst();
        videoId = cursor.getLong(cursor.getColumnIndex(MediaStore.Video.VideoColumns._ID));
        int duration = cursor.getInt(cursor.getColumnIndex(MediaStore.Video.VideoColumns.DURATION));
        setDuration(duration);
      } else {
        Logger.w(TAG, "analysisAttribute(), cursor is null!");
      }
    } finally {
      if (cursor != null) {
        cursor.close();
        cursor = null;
      }
    }

    if (videoId != -1) {
      whereClause = android.provider.MediaStore.Video.Thumbnails.VIDEO_ID + "='" + videoId + "'";
      try {
        cursor =
            cr.query(
                android.provider.MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI,
                new String[] {android.provider.MediaStore.Video.Thumbnails.DATA},
                whereClause,
                null,
                null);
        if (cursor != null && cursor.getCount() != 0) {
          cursor.moveToFirst();
          String thumbnailPath =
              cursor.getString(
                  cursor.getColumnIndex(android.provider.MediaStore.Video.Thumbnails.DATA));
          setThumbPath(thumbnailPath);
        } else {
          Logger.w(TAG, "analysisAttribute(), cursor is null!");
        }
      } finally {
        if (cursor != null) {
          cursor.close();
          cursor = null;
        }
      }
    } else {
      Logger.w(TAG, "analysisAttribute(), have no this image!");
    }
  }
  // This method will set right value on the togle buttons
  private void setToggleButtons() {
    DbAdapter db = new DbAdapter(this);
    db.open();

    // carb togle button
    Cursor cSettingCarb = db.fetchSettingByName(DbSettings.setting_value_carb_onoff);
    if (cSettingCarb.getCount() > 0) {
      cSettingCarb.moveToFirst();
      if (cSettingCarb.getInt(cSettingCarb.getColumnIndexOrThrow(DbAdapter.DATABASE_SETTINGS_VALUE))
          == 1) {
        tgCarb.setChecked(true);
      } else {
        tgCarb.setChecked(false);
      }
    }
    cSettingCarb.close();

    // prot togle button
    Cursor cSettingProt = db.fetchSettingByName(DbSettings.setting_value_prot_onoff);
    if (cSettingProt.getCount() > 0) {
      cSettingProt.moveToFirst();
      if (cSettingProt.getInt(cSettingProt.getColumnIndexOrThrow(DbAdapter.DATABASE_SETTINGS_VALUE))
          == 1) {
        tgProt.setChecked(true);
      } else {
        tgProt.setChecked(false);
      }
    }
    cSettingProt.close();

    // fat togle button
    Cursor cSettingFat = db.fetchSettingByName(DbSettings.setting_value_fat_onoff);
    if (cSettingFat.getCount() > 0) {
      cSettingFat.moveToFirst();
      if (cSettingFat.getInt(cSettingFat.getColumnIndexOrThrow(DbAdapter.DATABASE_SETTINGS_VALUE))
          == 1) {
        tgFat.setChecked(true);
      } else {
        tgFat.setChecked(false);
      }
    }
    cSettingFat.close();

    // kcal togle button
    Cursor cSettingKcal = db.fetchSettingByName(DbSettings.setting_value_kcal_onoff);
    if (cSettingKcal.getCount() > 0) {
      cSettingKcal.moveToFirst();
      if (cSettingKcal.getInt(cSettingKcal.getColumnIndexOrThrow(DbAdapter.DATABASE_SETTINGS_VALUE))
          == 1) {
        tgKcal.setChecked(true);
      } else {
        tgKcal.setChecked(false);
      }
    }

    cSettingKcal.close();

    db.close();
  }
Example #29
0
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.delete) {
      dbhelper.deleteMarkByID(ChalkmarkID);
      Context context = getApplicationContext();
      AlertDialog.Builder alertbox = new AlertDialog.Builder(context);
      alertbox.setMessage("The Mark Was Deleted");
      SharedPreferences.Editor editor = mPreferences.edit();
      editor.putInt("DefaultTab", 1);
      editor.commit();
      Intent intent = new Intent().setClass(MessageDetails.this, ChalkMarkTabHost.class);
      startActivity(intent);
      finish();
    } else if (item.getItemId() == R.id.map) {
      Intent i = new Intent(MessageDetails.this, MarkInfoMap.class);

      c = dbhelper.getByID(ChalkmarkID);
      c.moveToFirst();

      Double latitude = dbhelper.getLat(c);
      Double longitude = dbhelper.getLon(c);

      i.putExtra(MarkInfoMap.EXTRA_LATITUDE, latitude);
      i.putExtra(MarkInfoMap.EXTRA_LONGITUDE, longitude);
      i.putExtra(MarkInfoMap.EXTRA_NAME, dbhelper.getFromName(c));
      i.putExtra(MarkInfoMap.EXTRA_SUBJECT, dbhelper.getSubject(c));

      dbhelper.close();
      startActivity(i);
    } else if (item.getItemId() == R.id.unread) { // Make the Chalkmark unread
      c = dbhelper.getByID(ChalkmarkID);
      c.moveToFirst();
      dbhelper.updateStatus(ChalkmarkID, "unread");
    } else if (item.getItemId() == R.id.unread) { // Make the Chalkmark unread
      c = dbhelper.getByID(ChalkmarkID);
      c.moveToFirst();
      dbhelper.updateStatus(ChalkmarkID, "unread");
    } else if (item.getItemId() == R.id.repost) {
      c = dbhelper.getByID(ChalkmarkID);
      c.moveToFirst();

      SharedPreferences.Editor editor = mPreferences.edit();
      editor.putString("SavedSubject", dbhelper.getSubject(c));
      editor.putString("SavedBody", dbhelper.getBody(c));
      editor.putInt("SavedExpiration", 25);
      editor.putInt("SavedRadius", 1000);
      editor.putBoolean("SavedImageFlag", imageflag);
      editor.putString("RandomString", dbhelper.getImagePair(c));
      editor.putFloat("MarkLat", (float) dbhelper.getLat(c));
      editor.putFloat("MarkLon", (float) dbhelper.getLon(c));
      editor.commit();

      Intent i = new Intent(MessageDetails.this, MakeMark.class);
      startActivity(i);
      finish();
    }

    return (super.onOptionsItemSelected(item));
  }
  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();
  }