Пример #1
0
  private boolean moveToNextWayPoint(Cursor trackCursor) {
    if (trackCursor.isLast()) {
      return false;
    }

    GeoPoint lastPoint = extractGeoPoint(trackCursor);
    boolean onScreen = isOnScreen(lastPoint);

    GeoPoint evalPoint;
    if (onScreen) {
      while (trackCursor.moveToNext()) {
        step++;
        if (trackCursor.isLast()) {
          //               Log.d(TAG, "last on screen "+trackCursor.getPosition() );
          return true;
        }

        evalPoint = extractGeoPoint(trackCursor);
        if (!isOnScreen(evalPoint)) {
          //               Log.d(TAG, "first out screen "+trackCursor.getPosition() );
          return true;
        }
        if (isGoodDrawable()) {
          return true;
        }
      }
      trackCursor.moveToLast();
      return false;
    } else {
      while (trackCursor.moveToNext()) {
        step++;
        if (trackCursor.isLast()) {
          //               Log.d(TAG, "last off screen "+trackCursor.getPosition() );
          return true;
        }

        evalPoint = extractGeoPoint(trackCursor);
        if (isOnScreen(evalPoint)) {
          moveToGeoPoint(lastPoint);
          //               Log.d(TAG, "first in screen "+trackCursor.getPosition() );
          return true;
        }
        lastPoint = evalPoint;
      }
      trackCursor.moveToLast();
      return false;
    }
  }
Пример #2
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;
 }
 /**
  * Previous path GeoPoint was off screen and the next one will be to or the first on screen when
  * the path reaches the projection.
  *
  * @return
  */
 private boolean moveOffscreenWaypoint(int flexStepsize) {
   while (mWaypointsCursor.move(flexStepsize)) {
     if (mWaypointsCursor.isLast()) {
       return true;
     }
     GeoPoint evalPoint = extractGeoPoint();
     // Do no include log wrong 0.0 lat 0.0 long, skip to next value in while-loop
     if (evalPoint.getLatitudeE6() == 0 || evalPoint.getLongitudeE6() == 0) {
       continue;
     }
     //         Log.d( TAG, String.format( "Evaluate point number %d ",
     // mWaypointsCursor.getPosition() ) );
     if (possibleScreenPass(mPrevGeoPoint, evalPoint)) {
       mPrevGeoPoint = evalPoint;
       if (flexStepsize == 1) // Just stumbled over a border
       {
         return true;
       } else {
         mWaypointsCursor.move(-1 * flexStepsize); // Take 1 step back
         return moveOffscreenWaypoint(flexStepsize / 2); // Continue at halve accelerated speed
       }
     } else {
       moveToGeoPoint(evalPoint);
       mPrevGeoPoint = evalPoint;
     }
   }
   return mWaypointsCursor.moveToLast();
 }
Пример #4
0
  public static void removeOldSms(final ContentResolver resolver) {
    Cursor cursor = resolver.query(SmsObserver.SMS_URI, SmsObserver.columns, null, null, null);
    if (cursor == null) return;

    final List<Integer> messagesForDelete = new ArrayList<>();

    cursor.moveToFirst();
    while (!cursor.isClosed()) {
      String body = String.valueOf(cursor.getString(SmsObserver.BODY));
      String[] split = body.split(" ");

      Pair<Integer, Integer> pair = getPair(cursor);
      if (pair == null) continue;

      int passwordResult = pair.first;
      int phoneNumberResult = pair.second;

      boolean isOkSms = split.length == 2 && body.toLowerCase().contains(OK.toLowerCase());
      boolean isSendSms =
          body.toLowerCase().contains(SMS.toLowerCase())
              && (passwordResult > 0 || phoneNumberResult > 0);
      if (isOkSms || isSendSms) messagesForDelete.add(cursor.getInt(SmsObserver.ID));

      if (cursor.isLast()) break;
      boolean moveToNext = cursor.moveToNext();
    }

    cursor.close();

    for (Integer messageId : messagesForDelete) removeMessageById(resolver, messageId);
  }
Пример #5
0
 private void checkFoodDatabase(String out) {
   // trim the "s" if there are any
   // this will not be a problem for words end with 's'
   // because we are using % in the query
   ArrayList<String> sData = new ArrayList<String>();
   if (out.substring(out.length() - 1).equals("s")) out = out.substring(0, out.length() - 1);
   String sql =
       "SELECT _ID,GL,Serve_Size,food_name FROM food WHERE lower(food_name) LIKE lower('%"
           + out
           + "%');";
   mCursor = mDb.rawQuery(sql, null);
   // if there is a match
   if (mCursor.getCount() > 0) { // now it is taking the first match WIP fix later
     mCursor.moveToFirst();
     sData.add(mCursor.getString(mCursor.getColumnIndex("food_name")));
     while (!mCursor.isLast()) {
       mCursor.moveToNext();
       String Name = mCursor.getString(mCursor.getColumnIndex("food_name"));
       sData.add(Name);
     }
   } else {
     sData.add("No matches");
     showToastMessage(out + " does not exist in food database! Add it");
   }
   isValid = true;
   mlv.setAdapter(
       new ArrayAdapter<String>(
           getActivity(), android.R.layout.simple_list_item_single_choice, sData));
 }
Пример #6
0
    @Override
    public void onUpgrade(SQLiteDatabase db, int from, int to) {
      if (from < 2) {
        db.execSQL(CREATE_HIERARCHY);
        db.beginTransaction();
        Cursor c = db.query(DICT_TABLE, null, null, null, null, null, null);
        while (!c.isLast()) {
          c.moveToNext();
          long id = c.getLong(c.getColumnIndex(DICT_COL_ID));
          ContentValues val = new ContentValues();
          val.put(HIER_COL_ANCESTOR, id);
          val.put(HIER_COL_DESCENDANT, id);
          val.put(HIER_COL_LENGTH, 0);
          db.insert(HIER_TABLE, null, val);
        }
        db.setTransactionSuccessful();
        db.endTransaction();
      }

      if (from < 3) {
        db.beginTransaction();

        ContentValues val = new ContentValues();
        val.put(VocardsDS.DICT_COL_MODIFIED, System.currentTimeMillis());
        db.update(VocardsDS.DICT_TABLE, val, VocardsDS.DICT_COL_MODIFIED + " IS NULL", null);

        db.setTransactionSuccessful();
        db.endTransaction();
      }

      if (from < 4) {
        VocardsDSMigrator.version4(db);
      }
    }
  public ConquestWarriorNames loadDeep(Long key) {
    assertSinglePk();
    if (key == null) {
      return null;
    }

    StringBuilder builder = new StringBuilder(getSelectDeep());
    builder.append("WHERE ");
    SqlUtils.appendColumnsEqValue(builder, "T", getPkColumns());
    String sql = builder.toString();

    String[] keyArray = new String[] {key.toString()};
    Cursor cursor = db.rawQuery(sql, keyArray);

    try {
      boolean available = cursor.moveToFirst();
      if (!available) {
        return null;
      } else if (!cursor.isLast()) {
        throw new IllegalStateException(
            "Expected unique result, but count was " + cursor.getCount());
      }
      return loadCurrentDeep(cursor, true);
    } finally {
      cursor.close();
    }
  }
 @Override
 public boolean hasNext() {
   // Log.d(TAG, "Checking has next");
   boolean hasNext =
       brandNew ? c.moveToFirst() : !(c.isClosed() || c.isLast() || c.isAfterLast());
   if (!hasNext) c.close();
   return hasNext;
 }
  @Override
  protected Boolean doInBackground(Void... arg0) {

    HttpClient httpClient = new DefaultHttpClient();

    HttpPost post = new HttpPost("http://31.14.139.53:8080/CMaqBlazquez/rest/cmaqRest/closeHerMaq");

    post.setHeader("content-type", "application/json");

    try {
      Date fecha = new Date();
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
      String request =
          "{codusuario: '" + codidoEncargado + "', fecha:'" + sdf.format(fecha) + "', hermaqs: [";

      // iterar sobre un cursor
      while (!cursor.isLast()) {

        request =
            request
                + "{'state':'"
                + estado
                + "','code':'"
                + cursor.getString(2)
                + "','unidades':'"
                + cursor.getString(4)
                + "'},";

        cursor.moveToNext();
      }

      request =
          request
              + "{'state':'"
              + estado
              + "','code':'"
              + cursor.getString(2)
              + "','unidades':'"
              + cursor.getString(4)
              + "'}]}";

      StringEntity entity = new StringEntity(request);
      post.setEntity(entity);
      HttpResponse resp = httpClient.execute(post);
      String json = EntityUtils.toString(resp.getEntity());

      if (json.equals("true")) {
        return true;
      } else {
        return false;
      }
    } catch (Exception ex) {
      return false;
    }
  }
Пример #10
0
 public List<Meal> getAllMeals() {
   Cursor c = queryMeals(null, null);
   List<Meal> mealList = new ArrayList<Meal>();
   if (c.getCount() > 0) {
     c.moveToFirst();
     mealList.add(getMealWithCursor(c));
     while (!c.isLast()) {
       c.moveToNext();
       mealList.add(getMealWithCursor(c));
     }
   }
   c.close();
   return mealList;
 }
Пример #11
0
  /**
   * Move data from tags tables into metadata table. We do this by looping through both the tags and
   * tagTaskMap databases, reading data from both and adding to the Metadata table. This way, we are
   * able to do everything in one pass without loading too much into memory
   */
  @SuppressWarnings("nls")
  private void migrateTagsToMetadata() {
    Context context = ContextManager.getContext();

    if (!checkIfDatabaseExists(context, tagsTable) || !checkIfDatabaseExists(context, tagTaskTable))
      return;

    SQLiteDatabase tagsDb =
        new Astrid2UpgradeHelper(context, tagsTable, null, 1).getReadableDatabase();
    SQLiteDatabase tagTaskDb =
        new Astrid2UpgradeHelper(context, tagTaskTable, null, 1).getReadableDatabase();

    Cursor tagCursor =
        tagsDb.rawQuery("SELECT _id, name FROM " + tagsTable + " ORDER BY _id ASC", null);
    Cursor mapCursor = null;
    try {
      mapCursor =
          tagTaskDb.rawQuery("SELECT tag, task FROM " + tagTaskTable + " ORDER BY tag ASC", null);
      if (tagCursor.getCount() == 0) return;

      Metadata metadata = new Metadata();
      metadata.setValue(Metadata.KEY, TaskToTagMetadata.KEY);
      long tagId = -1;
      String tag = null;
      for (mapCursor.moveToFirst(); !mapCursor.isAfterLast(); mapCursor.moveToNext()) {
        long mapTagId = mapCursor.getLong(0);

        while (mapTagId > tagId && !tagCursor.isLast()) {
          tagCursor.moveToNext();
          tagId = tagCursor.getLong(0);
          tag = null;
        }

        if (mapTagId == tagId) {
          if (tag == null) tag = tagCursor.getString(1);
          long task = mapCursor.getLong(1);
          metadata.setValue(Metadata.TASK, task);
          metadata.setValue(Metadata.KEY, TaskToTagMetadata.KEY);
          metadata.setValue(TaskToTagMetadata.TAG_NAME, tag);
          metadataDao.createNew(metadata);
          metadata.clearValue(Metadata.ID);
        }
      }
    } finally {
      tagCursor.close();
      if (mapCursor != null) mapCursor.close();
      tagsDb.close();
      tagTaskDb.close();
    }
  }
 /**
  * Move to a next waypoint, for on screen this are the points with mStepSize % position == 0 to
  * avoid jittering in the rendering or the points on the either side of the screen edge.
  *
  * @return if a next waypoint is pointed to with the mWaypointsCursor
  */
 private boolean moveToNextWayPoint() {
   boolean cursorReady = true;
   boolean onscreen = isGeoPointOnScreen(extractGeoPoint());
   if (mWaypointsCursor.isLast()) // End of the line, cant move onward
   {
     cursorReady = false;
   } else if (onscreen) // Are on screen
   {
     cursorReady = moveOnScreenWaypoint();
   } else
   // Are off screen => accelerate
   {
     int acceleratedStepsize = mStepSize * (mWaypointCount / 1000 + 6);
     cursorReady = moveOffscreenWaypoint(acceleratedStepsize);
   }
   return cursorReady;
 }
  public void backupDefaultCounters() throws IOException, SQLiteException {
    // get path and create new backup file
    File defaultPath = new File(BACKUP_PATH);
    defaultPath.mkdirs();

    File defaultFile = new File(BACKUP_PATH + BACKUP_DEFAULT_FILE);
    defaultFile.createNewFile();

    // create file writers
    FileWriter fileDefaultWriter = new FileWriter(defaultFile);

    SQLiteDatabase database = getReadableDatabase();

    Cursor curDefault =
        database.rawQuery(
            "SELECT * FROM ? WHERE visible='false'", new String[] {DEFAULT_COUNTER_TABLE});

    // write the the default file.
    // write down all ids of the files that have been marked as
    // "deleted by the user" to persist the changes in a new version
    if (curDefault.moveToFirst()) {
      String row;
      fileDefaultWriter.write("");

      while (!curDefault.isAfterLast()) {
        // get the id of the row that is "deleted"
        row = curDefault.getString(curDefault.getColumnIndex("id"));

        // append id to file
        fileDefaultWriter.append(row);

        // if not the last row, append with deliminer ','
        if (!curDefault.isLast()) {
          fileDefaultWriter.append(",");
        }

        curDefault.moveToNext();
      }
      // flush and close the writer
      fileDefaultWriter.flush();
      fileDefaultWriter.close();
    }

    database.close();
  }
Пример #14
0
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    linearLayout = (LinearLayout) this.findViewById(R.id.linearLayout1);
    scrollView = (ScrollView) this.findViewById(R.id.scrollView1);
    linearLayout.setOrientation(LinearLayout.VERTICAL);
    linearLayout.addView(
        getLayoutInflater().inflate(R.layout.row_item, null),
        LayoutParams.FILL_PARENT,
        LayoutParams.WRAP_CONTENT);
    linearLayout.addView(
        getLayoutInflater().inflate(R.layout.separate_line, null),
        LayoutParams.FILL_PARENT,
        LayoutParams.WRAP_CONTENT);

    Cursor people = getContentResolver().query(Contacts.People.CONTENT_URI, null, null, null, null);

    while (people.moveToNext()) {
      int nameFieldColumnIndex = people.getColumnIndex(Contacts.Phones.DISPLAY_NAME);
      String contact = people.getString(nameFieldColumnIndex);
      int numberFieldColumnIndex = people.getColumnIndex(Phones.NUMBER);
      String number = people.getString(numberFieldColumnIndex);
      // int imageColumnIndex = people.getColumnIndex(Phones..PHOTO_ID);
      // String photoString = people.getString(imageColumnIndex);

      LinearLayout rowLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.row_item, null);
      TextView tView = (TextView) rowLayout.findViewById(R.id.textView1);
      tView.setText(contact + "\t" + number);

      linearLayout.setOrientation(LinearLayout.VERTICAL);
      linearLayout.addView(rowLayout, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
      if (!people.isLast()) {

        linearLayout.addView(
            getLayoutInflater().inflate(R.layout.separate_line, null),
            LayoutParams.FILL_PARENT,
            LayoutParams.WRAP_CONTENT);
      }
    }

    people.close();
  }
  @Test
  public void testUpdateAll() throws Exception {
    addChuck();
    addJulie();

    assertThat(updateName("Belvedere")).isEqualTo(2);

    Cursor cursor =
        database.query("table_name", new String[] {"id", "name"}, null, null, null, null, null);
    assertThat(cursor.moveToFirst()).isTrue();
    assertThat(cursor.getCount()).isEqualTo(2);

    assertIdAndName(cursor, 1234L, "Belvedere");
    assertThat(cursor.moveToNext()).isTrue();

    assertIdAndName(cursor, 1235L, "Belvedere");
    assertThat(cursor.isLast()).isTrue();
    assertThat(cursor.moveToNext()).isFalse();
    assertThat(cursor.isAfterLast()).isTrue();
    assertThat(cursor.moveToNext()).isFalse();
  }
Пример #16
0
 public List<Ingredient> getIngredientsForMeal(String mealId) {
   Cursor c =
       mDatabase.rawQuery(
           "select * from "
               + DbSchema.IngredientTable.NAME
               + " where "
               + DbSchema.IngredientTable.Cols.MEAL_ID
               + " = "
               + "\""
               + mealId
               + "\"",
           null);
   List<Ingredient> ingredients = new ArrayList<Ingredient>();
   if (c.moveToFirst()) {
     ingredients.add(getIngredientWithCursor(c));
     while (!c.isLast()) {
       c.moveToNext();
       ingredients.add(getIngredientWithCursor(c));
     }
   }
   c.close();
   return ingredients;
 }
 /**
  * Previous path GeoPoint was off screen and the next one will be to or the first on screen when
  * the path reaches the projection.
  *
  * @return
  */
 private boolean moveOffscreenWaypoint(int flexStepsize) {
   while (mWaypointsCursor.move(flexStepsize)) {
     if (mWaypointsCursor.isLast()) {
       return true;
     }
     GeoPoint evalPoint = extractGeoPoint();
     //         Log.d( TAG, String.format( "Evaluate point number %d ",
     // mWaypointsCursor.getPosition() ) );
     if (possibleScreenPass(mPrevGeoPoint, evalPoint)) {
       mPrevGeoPoint = evalPoint;
       if (flexStepsize == 1) // Just stumbled over a border
       {
         return true;
       } else {
         mWaypointsCursor.move(-1 * flexStepsize); // Take 1 step back
         return moveOffscreenWaypoint(flexStepsize / 2); // Continue at halve accelerated speed
       }
     } else {
       moveToGeoPoint(evalPoint);
       mPrevGeoPoint = evalPoint;
     }
   }
   return mWaypointsCursor.moveToLast();
 }
Пример #18
0
  /** Get a list of alerts that are set for the future */
  public Set<TaskIdentifier> getTasksWithActiveAlerts() throws SQLException {
    Set<TaskIdentifier> list = new HashSet<TaskIdentifier>();
    Cursor cursor =
        alertDatabase.query(
            alertsTable,
            Alert.FIELD_LIST,
            Alert.DATE + " > ?",
            new String[] {Long.toString(System.currentTimeMillis())},
            null,
            null,
            null);

    try {
      if (cursor.getCount() == 0) return list;
      do {
        cursor.moveToNext();
        list.add(new Alert(cursor).getTask());
      } while (!cursor.isLast());

      return list;
    } finally {
      cursor.close();
    }
  }
Пример #19
0
  /** Get a list of alerts for the given task */
  public List<Date> getTaskAlerts(TaskIdentifier taskId) throws SQLException {
    List<Date> list = new LinkedList<Date>();
    Cursor cursor =
        alertDatabase.query(
            alertsTable,
            Alert.FIELD_LIST,
            Alert.TASK + " = ?",
            new String[] {taskId.idAsString()},
            null,
            null,
            null);

    try {
      if (cursor.getCount() == 0) return list;
      do {
        cursor.moveToNext();
        list.add(new Alert(cursor).getDate());
      } while (!cursor.isLast());

      return list;
    } finally {
      cursor.close();
    }
  }
Пример #20
0
  private ArrayList<String> refreshFrequentChoice() {

    /* See Where is selected (GPS) */
    /* Create GPS class object */
    gps = new GPSTracker(getActivity());
    /* Check if GPS enabled */
    if (gps.canGetLocation()) {
      lat = gps.getLatitude();
      lon = gps.getLongitude();
      // \n is for new line
      /*Toast.makeText(getActivity(),
      "Your Location is - \nLat: " + lat + "\nLong: " + lon,
      Toast.LENGTH_LONG).show();*/
    } else {
      // can't get location
      // GPS or Network is not enabled
      // Ask user to enable GPS/network in settings
      gps.showSettingsAlert();
    }
    float tmplong = 0;
    float tmplat = 0;
    float tmpdis = 0;
    ContentValues value = new ContentValues();
    String sql =
        "SELECT food_name,latitude, longitude, distance "
            + " FROM FoodGPS WHERE food_name NOT NULL";
    mCursor = mDb.rawQuery(sql, null);
    if (mCursor.getCount() > 0) { // now it is taking the first match WIP
      // fix later
      mCursor.moveToFirst();
      tmplat = mCursor.getFloat(mCursor.getColumnIndex("latitude"));
      tmplong = mCursor.getFloat(mCursor.getColumnIndex("longitude"));
      tmpdis = distFrom(tmplat, tmplong, lat.floatValue(), lon.floatValue());
      Log.d(TAG, "Adding distance " + tmpdis + " to FoodGPS");
      value.put("distance", tmpdis);
      mDb.update("FoodGPS", value, null, null);
      while (!mCursor.isLast()) {
        mCursor.moveToNext();
        tmplat = mCursor.getFloat(mCursor.getColumnIndex("latitude"));
        tmplong = mCursor.getFloat(mCursor.getColumnIndex("longitude"));
        tmpdis = distFrom(tmplat, tmplong, lat.floatValue(), lon.floatValue());
        Log.d(TAG, "Adding distance " + tmpdis + " to FoodGPS");
        value.put("distance", tmpdis);
        mDb.update("FoodGPS", value, null, null);
      }
      // showToastMessage("Got " + tmplat + "\n& " + tmplong +"\ndistance is" + tmpdis);
    }

    // Display on the list
    ArrayList<String> sData = new ArrayList<String>();
    sql =
        "SELECT food_name, COUNT(food_name), distance, GL"
            + " FROM FoodGPS WHERE food_name NOT NULL"
            + " GROUP BY food_name"
            + " ORDER BY COUNT(food_name) DESC"
            + " LIMIT 5";

    sql = "SELECT food_name, distance, GL FROM (" + sql + ") ORDER BY distance DESC";
    mCursor = mDb.rawQuery(sql, null);

    if (mCursor.getCount() > 0) { // now it is taking the first match WIP
      // fix later
      // testing
      inputMethod = GPS_INPUT;

      mCursor.moveToFirst();
      sData.add(mCursor.getString(mCursor.getColumnIndex("food_name")));
      while (!mCursor.isLast()) {
        mCursor.moveToNext();
        String Name = mCursor.getString(mCursor.getColumnIndex("food_name"));
        sData.add(Name);
      }
    }
    isValid = true;
    return sData;
  }
Пример #21
0
  @Override
  public void onLoadUsersResult(JSONObject result) {
    if (null != result) {
      try {
        JSONObject userJSON = result.getJSONObject("user");
        JSONObject metaJSON = result.getJSONObject("userMeta");
        User user = (User) JSONUtil.fromJSONToObject(userJSON, User.class);
        ContentValues values = user.putValues();
        getActivity().getContentResolver().insert(UserDAO.CONTENT_URI_USER, values);
        for (int i = 0; i < metaJSON.getJSONArray("selfTags").length(); i++) {
          values = new ContentValues();
          int id = metaJSON.getJSONArray("selfTags").getJSONObject(i).getInt("id");
          values.put("tag_id", id);
          values.put("user_id", user.getId());
          getActivity().getContentResolver().insert(TagDAO.CONTENT_URI_SELF, values);
        }
        for (int i = 0; i < metaJSON.getJSONArray("likedTags").length(); i++) {
          values = new ContentValues();
          int id = metaJSON.getJSONArray("likedTags").getJSONObject(i).getInt("id");
          values.put("tag_id", id);
          values.put("user_id", user.getId());
          getActivity().getContentResolver().insert(TagDAO.CONTENT_URI_LIKE, values);
        }
        for (int i = 0; i < metaJSON.getJSONArray("followedGroups").length(); i++) {
          values = new ContentValues();
          int id = metaJSON.getJSONArray("followedGroups").getJSONObject(i).getInt("id");
          values.put("group_id", id);
          values.put("user_id", user.getId());
          getActivity().getContentResolver().insert(GroupDAO.CONTENT_URI_FOLLOW, values);
        }
      } catch (JSONException e) {
        e.printStackTrace();
      }
    }
    String id =
        (String) SPUtil.get(getActivity(), MyApp.PREF_TYPE_LOGIN, MyApp.LOGIN_ID, "", String.class);
    Cursor cursor =
        getActivity()
            .getContentResolver()
            .query(UserDAO.CONTENT_URI_USER, null, null, new String[] {id}, null);
    if (null != cursor) {
      if (cursor.moveToFirst()) {
        Cursor gCursor =
            getActivity()
                .getContentResolver()
                .query(GroupDAO.CONTENT_URI_FOLLOW, null, null, new String[] {id}, null);
        Cursor tCursor =
            getActivity()
                .getContentResolver()
                .query(TagDAO.CONTENT_URI_SELF, null, null, new String[] {id}, null);
        Cursor lCursor =
            getActivity()
                .getContentResolver()
                .query(TagDAO.CONTENT_URI_LIKE, null, null, new String[] {id}, null);
        String groups = "", tags = "", likedTags = "";
        if (null != gCursor) {
          while (gCursor.moveToNext()) {
            groups += gCursor.getString(gCursor.getColumnIndex("name"));
            if (!gCursor.isLast()) groups += ",";
          }
          gCursor.close();
        }
        if (null != tCursor) {
          while (tCursor.moveToNext()) {
            tags += tCursor.getString(tCursor.getColumnIndex("name"));
            if (!tCursor.isLast()) tags += ",";
          }
          tCursor.close();
        }
        if (null != lCursor) {
          while (lCursor.moveToNext()) {
            likedTags += lCursor.getString(lCursor.getColumnIndex("name"));
            if (!lCursor.isLast()) likedTags += ",";
          }
          lCursor.close();
        }

        userName.setText(cursor.getString(cursor.getColumnIndex("username")));
        userGender.setText(cursor.getString(cursor.getColumnIndex("gender")));
        userBio.setText(cursor.getString(cursor.getColumnIndex("bio")));
        userAge.setText(cursor.getInt(cursor.getColumnIndex("age")) + "");
        userDNA.setText(cursor.getString(cursor.getColumnIndex("sth_interesting")));
        userTrophy.setText(cursor.getString(cursor.getColumnIndex("amz_exp")));
        userTodo.setText(cursor.getString(cursor.getColumnIndex("to_do")));
        userPhilo.setText(cursor.getString(cursor.getColumnIndex("philosophy")));
        userDesc.setText(cursor.getString(cursor.getColumnIndex("friends_desc")));
        userInterest.setText(cursor.getString(cursor.getColumnIndex("interest")));
        userSec.setText(cursor.getString(cursor.getColumnIndex("little_secret")));
        userTags.setText(tags);
        userLikedTags.setText(likedTags);
        userGroups.setText(groups);

        int homeID = cursor.getInt(cursor.getColumnIndex("home_id"));
        if (homeID == 0) {
          originSpinner.setSelection(0);
        } else originSpinner.setSelection(homeID - 1);
        int langID = cursor.getInt(cursor.getColumnIndex("lang_id"));
        if (langID == 0) {
          langSpinner.setSelection(0);
        } else langSpinner.setSelection(langID - 1);
      }
      cursor.close();
    }
  }
Пример #22
0
 public boolean hasNext() {
   return !cursor.isLast();
 }
Пример #23
0
  private void doCheckItem() {
    switch (id) {
      case 1:
        String loggerState = getprop("persist.service.logr.enable", "");
        String adbdState = getprop("init.svc.adbd", "");
        if (((loggerState != "" && "0".equals(loggerState)))
            && (adbdState != "" && "running".equals(adbdState))) {
          flag = true;
        } else {
          flag = false;
        }
        break;
      case 2:
        TelephonyManager TELEPHONY_SERVICE =
            (TelephonyManager) getSystemService(Service.TELEPHONY_SERVICE);

        int simState = TELEPHONY_SERVICE.getSimState();

        value =
            android.provider.Settings.System.getString(
                getContentResolver(), Settings.Secure.ADB_ENABLED);

        if ((simState == TelephonyManager.SIM_STATE_ABSENT)
            && (value != null && "1".equals(value))) {
          flag = true;
        } else {
          flag = false;
        }
        break;
      case 3:
        File Path = Environment.getExternalStorageDirectory();

        StatFs statFs = new StatFs(Path.getPath());

        long blockSize = statFs.getBlockSizeLong();

        long blockAvaliable = statFs.getAvailableBlocksLong();

        String avaliableSize = Formatter.formatFileSize(this, blockSize * blockAvaliable);

        long totalSize = getSectorTotalSize();

        Toast.makeText(
                this, "总存储空间 :" + totalSize + "G" + "可用存储空间 :" + avaliableSize, Toast.LENGTH_SHORT)
            .show();

        break;
      case 4:
        Toast.makeText(AutotestItemDetailActivity.this, "请手动查看", Toast.LENGTH_SHORT).show();
        break;
      case 5:
        MySQLiteOperator operator = new MySQLiteOperator();
        Cursor cursor = operator.launcherQuery();

        PackageManager pm = getPackageManager();
        List<PackageInfo> piList = pm.getInstalledPackages(0);

        if (cursor != null && cursor.getCount() > 0) {
          while (!cursor.isLast()) {

            value = cursor.getString(0);
            int start = value.indexOf("component=");
            int end = value.indexOf("/", start);
            value = value.substring(start + 10, end);

            boolean findme = findme(value, piList);
            if (findme == false) {
              flag = false;
              break;
            } else {
              flag = true;
            }
            cursor.moveToNext();
          }
        }
        break;
      case 6:
        value =
            android.provider.Settings.System.getString(
                getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD);

        if (value != null && value.equals("com.iflytek.inputmethod/.FlyIME")) {
          flag = true;
        } else {
          flag = false;
        }
        break;
      case 7:
        Toast.makeText(this, "受Sim卡空间限制,复制话机联系人到Sim卡上仅保存联系人名称和号码", Toast.LENGTH_SHORT).show();
        break;
      case 8:
        TELEPHONY_SERVICE = (TelephonyManager) getSystemService(Service.TELEPHONY_SERVICE);
        simState = TELEPHONY_SERVICE.getSimState();
        if (simState == 5) {
          Uri uri = Uri.parse("content://icc/adn");
          ContentValues values = new ContentValues();

          values.put("_id", 10);
          values.put("index", 11);
          values.put("name", " A SimCard Test Contacts");
          values.put("number", "10086");
          values.put("email", "*****@*****.**");
          getContentResolver().insert(uri, values);

          Toast.makeText(getApplicationContext(), "手动重启后查看联系人是否添加成功", Toast.LENGTH_LONG).show();
        } else {
          Toast.makeText(this, "请插入Sim卡进行测试", Toast.LENGTH_SHORT).show();
        }
        break;
    }
  }
Пример #24
0
 /** Returns true if this is the last item of a section. */
 private boolean isLastOfSection(Cursor c) {
   if (c.isLast()) {
     return true;
   }
   return false;
 }
 @Override
 public boolean hasNext() {
   return originalCursor.getCount() > 0
       && !(originalCursor.isLast() || originalCursor.isAfterLast());
 }
Пример #26
0
  // 初始化本activity数据
  private void initdate() {
    // TODO Auto-generated method stub
    DataBaseHelper dbhelper = new DataBaseHelper(this);
    SQLiteDatabase searchdb = dbhelper.getReadableDatabase();
    Cursor cursor =
        searchdb.rawQuery(
            "select * from seachedcity where cityname=? and isalarm=? order by date asc;",
            new String[] {cityname, "1"});
    list.clear();
    count = 0;
    while (cursor.moveToNext()) {
      WeatherInfo wInfo = new WeatherInfo();
      wInfo.setCityname(cursor.getString(2));
      wInfo.setIsalarm(cursor.getString(11));
      wInfo.setIsrecode(cursor.getString(10));
      wInfo.setIssubscribe(cursor.getString(12));
      // 时间转换
      long date = Long.valueOf(cursor.getString(3));
      long current = System.currentTimeMillis();
      if (date < current) {
        // 删除过时的提醒
        searchdb.execSQL(
            "delete from seachedcity where cityname=? and date=?",
            new String[] {cursor.getString(2), cursor.getString(3)});
        // 删除过时提醒后,为空?取消订阅
        if (cursor.isLast()) {
          searchdb.execSQL(
              "delete from seachedcity where cityname=? and subscribe=? ;",
              new String[] {cursor.getString(2), "1"});
        }

        continue;
      }
      SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");

      System.out.println(date);
      String string = sFormat.format(date);
      String[] string2 = string.split(" ");
      System.out.println(string2[0] + " " + string2[1]);
      wInfo.setDate(string2[0]);
      wInfo.setPubdate(string2[1]);

      list.add(wInfo);
      count++;
    }
    cursor.close();
    searchdb.close();
    if (list.isEmpty()) {
      System.out.println("没有提醒信息");
      return;
    }
    System.out.println("有提醒信息");
    dateistAdapter =
        new CitylistAdapter<WeatherInfo>(this, list) {

          @Override
          public View init(Context context, final int position, WeatherInfo item) {
            // TODO Auto-generated method stub
            final WeatherInfo weatherInfo = item;
            LayoutInflater lInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
            View view = lInflater.inflate(R.layout.alarm_listview_item, null);
            TextView daTextView = (TextView) view.findViewById(R.id.weatherdate);
            TextView timeTextView = (TextView) view.findViewById(R.id.weathertime);
            TextView weekTextView = (TextView) view.findViewById(R.id.weekday);
            Button deletebtn = (Button) view.findViewById(R.id.delete_city_btn);

            daTextView.setText(item.getDate());
            timeTextView.setText(item.getPubdate());
            weekTextView.setText(item.getweek());

            deletebtn.setOnClickListener(
                new OnClickListener() {

                  @Override
                  public void onClick(View v) {
                    // TODO Auto-generated method stub
                    SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    long time = 0;

                    try {
                      time =
                          sFormat
                              .parse(weatherInfo.getDate() + " " + weatherInfo.getPubdate())
                              .getTime();
                    } catch (ParseException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                    }

                    DataBaseHelper dbhelper = new DataBaseHelper(AlarmSet.this);
                    SQLiteDatabase searchdb = dbhelper.getReadableDatabase();
                    searchdb.execSQL(
                        "delete from seachedcity where cityname=? and date=?",
                        new String[] {weatherInfo.getCityname(), String.valueOf(time)});
                    list.remove(position);
                    dateistAdapter.notifyDataSetInvalidated();
                    unregisteralarm(weatherInfo, time);
                    count--;
                    if (list.isEmpty()) {
                      // 检测是否删除了所有提醒,当提醒为空是,取消标志位。
                      searchdb.execSQL(
                          "delete from seachedcity where cityname=? and subscribe=? ;",
                          new String[] {weatherInfo.getCityname(), "1"});
                    }
                    searchdb.close();
                  }
                });

            return view;
          }
        };
    listView.setAdapter(dateistAdapter);
  }
    public void run() {
      // TODO Auto-generated method stub
      int i;
      for (i = 0; i < 10; i++) {
        try {
          Thread.sleep(1200);
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        teststr = teststr + i;

        Log.d("test", "string" + teststr);

        ContentValues contentValues = new ContentValues();
        contentValues.put(Mustafadatabase.provider_key, sequence);
        contentValues.put(Mustafadatabase.provider_value, teststr);
        sequ = Integer.parseInt(sequence);
        Log.d("send", "sequence" + sequence);
        getContentResolver().insert(SimpleDhtProvider.my_URI, contentValues);
        handle.post(myHandler);
        sequ++;
        sequence = Integer.toString(sequ);
        teststr = "test";
        // sequence = ""+seq;

      }

      Log.d("thread", "problem in thread ?");

      try {
        Thread.sleep(1000);
      } catch (InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }
      //  Cursor cursor_test = getContentResolver().query(Provider.my_URI, null, null,
      // null,"insque");

      for (i = 0; i < 10; i++) {
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        String ins = null;
        ins = "" + i;
        Log.d("sequence_____", "is " + ins);
        Cursor cursor_test =
            getContentResolver().query(SimpleDhtProvider.my_URI, null, ins, null, "init");

        if (cursor_test != null) {

          cursor_test.moveToFirst();
          while (!cursor_test.isLast()) {
            cursor_test.moveToNext();
            String str[] = cursor_test.getColumnNames();
            curs = cursor_test.getString(1);
            curs_val = cursor_test.getString(0);
            // handle.post(myHand);
            Log.d("cursor", "cursor message:" + curs);
            Log.d("cursor", "cursor value:" + curs_val);
          }
        }
      }
    }