예제 #1
1
  private ArrayList<Sms> getAllSms() {
    ArrayList<Sms> allSms = new ArrayList<Sms>();
    Sms objSms;
    Uri message = Uri.parse("content://sms/");
    ContentResolver cr = getContentResolver();

    Cursor c = cr.query(message, null, null, null, null);
    startManagingCursor(c);
    int totalSMS = c.getCount();

    if (c.moveToFirst()) {
      for (int i = 0; i < totalSMS; i++) {

        objSms = new Sms();
        objSms.setId(c.getString(c.getColumnIndexOrThrow("_id")));
        objSms.setAddress(c.getString(c.getColumnIndexOrThrow("address")));
        objSms.setMsg(c.getString(c.getColumnIndexOrThrow("body")));
        objSms.setReadState(c.getString(c.getColumnIndex("read")));
        objSms.setTime(c.getString(c.getColumnIndexOrThrow("date")));
        if (c.getString(c.getColumnIndexOrThrow("type")).contains("1")) {
          objSms.setFolderName("inbox");
        } else {
          objSms.setFolderName("sent");
        }

        allSms.add(objSms);
        c.moveToNext();
      }
    }
    c.close();
    return allSms;
  }
  // The bindView method is used to bind all data to a given view
  // such as setting the text on a TextView.
  @Override
  public void bindView(View view, Context context, Cursor cursor) {
    ImageView myImage = (ImageView) view.findViewById(R.id.imageForBookStatus);
    // Find fields to populate in inflated template
    TextView bookName = (TextView) view.findViewById(R.id.book_name_author_field);
    TextView bookCategory = (TextView) view.findViewById(R.id.textView_category_field);
    // Extract properties from cursor
    String category = cursor.getString(cursor.getColumnIndexOrThrow(DBManager.KEY_TASK_CATEGORY));
    String bookNameColumn = cursor.getString(cursor.getColumnIndexOrThrow(DBManager.KEY_TASK_NAME));

    // Get the information from the columns, assign them to the the following varialbes.
    String userCurrentlyReading =
        cursor.getString(cursor.getColumnIndexOrThrow(DBManager.KEY_TASK_CREADING));
    String userCompletedBook =
        cursor.getString(cursor.getColumnIndexOrThrow(DBManager.KEY_TASK_READ));

    // to check to see if the user is currently reading the book,
    // if so, display image on the list view beside the book name.
    if ((userCurrentlyReading.equals("True") && (userCompletedBook.equals("True")))
        || (userCurrentlyReading.equals("True"))) {
      myImage.setImageResource(R.drawable.imageread);
    }

    if (userCompletedBook.equals("True") && (userCurrentlyReading.equals("False"))) {
      myImage.setImageResource(R.drawable.tick_50_x_50);
    }
    // Populate fields with extracted properties
    bookName.setText(bookNameColumn);
    bookCategory.setText(category);
  }
예제 #3
0
  @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);

    Cursor note = extObjDB.fetchNote(id);
    startManagingCursor(note);
    ObjSource s;
    int resource_id = note.getInt(note.getColumnIndexOrThrow(ExternObjDB.KEY_RESRC_ID));
    if (resource_id == -1) {
      // obj from sdcard
      String path = note.getString(note.getColumnIndexOrThrow(ExternObjDB.KEY_PATH));
      s = new ObjFromSDcard(path);
    } else {
      // obj from resource
      s = new ObjFromResource(resource_id);
    }
    s.Title = note.getString(note.getColumnIndexOrThrow(ExternObjDB.KEY_TITLE));
    s.Info = note.getString(note.getColumnIndexOrThrow(ExternObjDB.KEY_INFO));
    s.ID = note.getInt(note.getColumnIndexOrThrow(ExternObjDB.KEY_ROWID));
    Bundle bundle = new Bundle();

    bundle.putSerializable(ObjSource.TITLE, s);

    Intent mIntent = new Intent();
    mIntent.putExtras(bundle);
    setResult(RESULT_OK, mIntent);
    finish();
  }
예제 #4
0
  /**
   * 获取count条未读短消息(有bug,获取的都是已读的)
   *
   * @param count
   * @return
   */
  public JSArray getUnreadSms(int count) {
    boolean limit = count > 0; // count大于0,则加上limit
    JSArray smsArray = new JSArray();
    ContentResolver resolver = context.getContentResolver();
    // 查询短消息详细信息,按日期降序排列
    Cursor cursor =
        resolver.query(
            Telephony.Sms.Inbox.CONTENT_URI,
            null,
            Telephony.Sms.Inbox.READ + "=?",
            new String[] {"0"},
            Telephony.Sms.DEFAULT_SORT_ORDER + (limit ? " limit 0," + count : ""));
    int idIndex = cursor.getColumnIndexOrThrow(Telephony.Sms._ID);
    int addressIndex = cursor.getColumnIndexOrThrow(Telephony.Sms.ADDRESS);
    int dateIndex = cursor.getColumnIndexOrThrow(Telephony.Sms.DATE);
    int pidIndex = cursor.getColumnIndexOrThrow(Telephony.Sms.PERSON_ID);
    int bodyIndex = cursor.getColumnIndexOrThrow(Telephony.Sms.BODY);

    while (cursor.moveToNext()) {
      long id = cursor.getLong(idIndex);
      String address = cursor.getString(addressIndex);
      long pid = cursor.getLong(pidIndex);
      long date = cursor.getLong(dateIndex);
      String body = cursor.getString(bodyIndex);

      SmsInfo sms = new SmsInfo(body, date, address, id, pid);
      smsArray.add(sms);
    }
    return smsArray;
  }
  @Override
  protected void initTempProvider(SyncableContentProvider cp) {
    // TODO: don't use the real db's calendar id's.  create new ones locally and translate
    // during CalendarProvider's merge.

    // populate temp provider with calendar ids, so joins work.
    ContentValues map = new ContentValues();
    Cursor c =
        getContext()
            .getContentResolver()
            .query(
                Calendar.Calendars.CONTENT_URI,
                CALENDARS_PROJECTION,
                SELECT_BY_ACCOUNT,
                new String[] {getAccount()},
                null /* sort order */);
    final int idIndex = c.getColumnIndexOrThrow(Calendars._ID);
    final int urlIndex = c.getColumnIndexOrThrow(Calendars.URL);
    final int timezoneIndex = c.getColumnIndexOrThrow(Calendars.TIMEZONE);
    while (c.moveToNext()) {
      map.clear();
      map.put(Calendars._ID, c.getLong(idIndex));
      map.put(Calendars.URL, c.getString(urlIndex));
      map.put(Calendars.TIMEZONE, c.getString(timezoneIndex));
      cp.insert(Calendar.Calendars.CONTENT_URI, map);
    }
    c.close();
  }
        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
          String[] mFilterDirs = getResources().getStringArray(R.array.filter_out_dirs);
          if (data != null) {
            List<Image> images = new ArrayList<Image>();
            int count = data.getCount();
            if (count > 0) {
              data.moveToFirst();
              do {
                String path = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[0]));
                String name = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[1]));
                long dateTime = data.getLong(data.getColumnIndexOrThrow(IMAGE_PROJECTION[2]));
                Image image = new Image(path, name, dateTime);
                File file = new File(path);
                if (file.exists()) {
                  String imageParentName = file.getParentFile().getName();
                  if (!isFilterOutDir(imageParentName, mFilterDirs)) {
                    images.add(image);
                  }
                }
                if (!hasFolderGened) {
                  // 获取文件夹名称
                  File imageFile = new File(path);
                  if (imageFile.exists()) {
                    File folderFile = imageFile.getParentFile();
                    Folder folder = new Folder();
                    folder.name = folderFile.getName();
                    folder.path = folderFile.getAbsolutePath();
                    folder.cover = image;
                    if (!mResultFolder.contains(folder)) {
                      List<Image> imageList = new ArrayList<Image>();
                      if (!isFilterOutDir(folder.name, mFilterDirs)) {
                        imageList.add(image);
                        folder.images = imageList;
                        mResultFolder.add(folder);
                      }
                    } else {
                      // 更新
                      Folder f = mResultFolder.get(mResultFolder.indexOf(folder));
                      if (!isFilterOutDir(folder.name, mFilterDirs)) {
                        f.images.add(image);
                      }
                    }
                  }
                }

              } while (data.moveToNext());

              mImageAdapter.setData(images);

              // 设定默认选择
              if (resultList != null && resultList.size() > 0) {
                mImageAdapter.setDefaultSelected(resultList);
              }

              mFolderAdapter.setData(mResultFolder);
              hasFolderGened = true;
            }
          }
        }
예제 #7
0
  public void testTrackingIds() {
    final int count = 3;

    // Test suggested sites with IDs.
    resources.setSuggestedSitesResource(generateSites(count, true, ""));
    SuggestedSites suggestedSites = new SuggestedSites(context);
    Cursor c = suggestedSites.get(DEFAULT_LIMIT);
    assertEquals(count, c.getCount());

    for (int i = 0; i < count; i++) {
      c.moveToNext();
      String url = c.getString(c.getColumnIndexOrThrow(BrowserContract.SuggestedSites.URL));
      assertTrue(suggestedSites.contains(url));
      assertEquals(i, suggestedSites.getTrackingIdForUrl(url));
    }
    c.close();

    // Test suggested sites where IDs are undefined.
    resources.setSuggestedSitesResource(generateSites(count, false, ""));
    suggestedSites = new SuggestedSites(context);
    c = suggestedSites.get(DEFAULT_LIMIT);
    assertEquals(count, c.getCount());

    for (int i = 0; i < count; i++) {
      c.moveToNext();
      String url = c.getString(c.getColumnIndexOrThrow(BrowserContract.SuggestedSites.URL));
      assertTrue(suggestedSites.contains(url));
      assertEquals(SuggestedSites.TRACKING_ID_NONE, suggestedSites.getTrackingIdForUrl(url));
    }
    c.close();
  }
  void removeContact(Cursor c) {
    final IImConnection conn = getConnection(c);

    String nickname = c.getString(c.getColumnIndexOrThrow(Imps.Contacts.NICKNAME));
    final String address = c.getString(c.getColumnIndexOrThrow(Imps.Contacts.USERNAME));
    DialogInterface.OnClickListener confirmListener =
        new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int whichButton) {
            try {
              IContactListManager manager = conn.getContactListManager();
              int res = manager.removeContact(address);
              if (res != ImErrorInfo.NO_ERROR) {
                mHandler.showAlert(
                    R.string.error, ErrorResUtils.getErrorRes(getResources(), res, address));
              }
            } catch (RemoteException e) {

              mHandler.showServiceErrorAlert(e.getLocalizedMessage());
              LogCleaner.error(ImApp.LOG_TAG, "remote error", e);
            }
          }
        };

    Resources r = getResources();

    new AlertDialog.Builder(mContext)
        .setTitle(R.string.confirm)
        .setMessage(r.getString(R.string.confirm_delete_contact, nickname))
        .setPositiveButton(R.string.yes, confirmListener) // default button
        .setNegativeButton(R.string.no, null)
        .setCancelable(false)
        .show();
  }
예제 #9
0
  public static String getAddress(Cursor c) {
    StringBuilder address = new StringBuilder();
    // street
    String street = c.getString(c.getColumnIndexOrThrow(Wheelmap.POIsColumns.STREET));
    if (street != null) {
      address.append(street);
      address.append(' ');
    }
    // house number
    String nr = c.getString(c.getColumnIndexOrThrow(Wheelmap.POIsColumns.HOUSE_NUM));
    if (nr != null) {
      address.append(nr);
    }
    // post code  & city
    String postcode = c.getString(c.getColumnIndexOrThrow(Wheelmap.POIsColumns.POSTCODE));
    String city = c.getString(c.getColumnIndexOrThrow(Wheelmap.POIsColumns.CITY));
    if ((street != null || nr != null) && (postcode != null || city != null)) address.append(", ");

    if (postcode != null) {
      address.append(postcode);
      address.append(' ');
    }
    if (city != null) {
      address.append(city);
    }
    return address.toString();
  }
예제 #10
0
 private ContactInfo getContactInfoFromEmailUri(Uri emailLookupUri, String email) {
   Uri uri = Uri.withAppendedPath(emailLookupUri, Uri.encode(email));
   Cursor cursor =
       mResolver.query(
           uri,
           new String[] {
             Email.CONTACT_ID,
             Email.DISPLAY_NAME_PRIMARY,
             Email.PHOTO_URI,
             Email.PHOTO_ID,
             Email.PHOTO_THUMBNAIL_URI,
           },
           null,
           null,
           null);
   if (cursor == null) {
     return null;
   }
   ContactInfo result = null;
   if (cursor.moveToFirst()) {
     result =
         new ContactInfo(
             cursor.getString(cursor.getColumnIndexOrThrow(Email.CONTACT_ID)),
             cursor.getString(cursor.getColumnIndexOrThrow(Email.DISPLAY_NAME_PRIMARY)),
             cursor.getString(cursor.getColumnIndexOrThrow(Email.PHOTO_URI)),
             cursor.getString(cursor.getColumnIndexOrThrow(Email.PHOTO_THUMBNAIL_URI)),
             cursor.getString(cursor.getColumnIndexOrThrow(Email.PHOTO_ID)));
   }
   cursor.close();
   return result;
 }
예제 #11
0
 private ContactInfo getContactInfoFromPhoneLookup(Uri uri, boolean isForSip) {
   Cursor cursor =
       mResolver.query(
           uri,
           new String[] {
             PhoneLookup._ID,
             PhoneLookup.DISPLAY_NAME,
             PhoneLookup.PHOTO_URI,
             PhoneLookup.PHOTO_THUMBNAIL_URI,
             PhoneLookup.PHOTO_ID
           },
           null,
           null,
           null);
   if (cursor == null) {
     return null;
   }
   ContactInfo result = null;
   if (cursor.moveToFirst()) {
     result =
         new ContactInfo(
             cursor.getString(cursor.getColumnIndexOrThrow(PhoneLookup._ID)),
             cursor.getString(cursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME)),
             cursor.getString(cursor.getColumnIndexOrThrow(PhoneLookup.PHOTO_URI)),
             cursor.getString(cursor.getColumnIndexOrThrow(PhoneLookup.PHOTO_THUMBNAIL_URI)),
             cursor.getString(cursor.getColumnIndexOrThrow(PhoneLookup.PHOTO_ID)));
   }
   cursor.close();
   return result;
 }
예제 #12
0
 protected WaitItem readCursor(Cursor cursor) {
   WaitItem item = null;
   try {
     item =
         new WaitItem(
             cursor.getString(cursor.getColumnIndexOrThrow(GoalDatabase.WaitItemEntry.COL_TEXT)));
     item.setId(cursor.getInt(cursor.getColumnIndexOrThrow(GoalDatabase.WaitItemEntry._ID)));
     item.setGoalId(
         cursor.getInt(cursor.getColumnIndexOrThrow(GoalDatabase.WaitItemEntry.COL_GOAL_ID)));
     item.setResponsible(
         cursor.getString(
             cursor.getColumnIndexOrThrow(GoalDatabase.WaitItemEntry.COL_RESPONSIBLE)));
     int dueYear = cursor.getInt(cursor.getColumnIndex(GoalDatabase.WaitItemEntry.COL_DUE_YEAR));
     int dueMonth = cursor.getInt(cursor.getColumnIndex(GoalDatabase.WaitItemEntry.COL_DUE_MONTH));
     int dueDay = cursor.getInt(cursor.getColumnIndex(GoalDatabase.WaitItemEntry.COL_DUE_DAY));
     item.setDueDate(new GregorianCalendar(dueYear, dueMonth, dueDay));
     int requestYear =
         cursor.getInt(cursor.getColumnIndex(GoalDatabase.WaitItemEntry.COL_REQUEST_YEAR));
     int requestMonth =
         cursor.getInt(cursor.getColumnIndex(GoalDatabase.WaitItemEntry.COL_REQUEST_MONTH));
     int requestDay =
         cursor.getInt(cursor.getColumnIndex(GoalDatabase.WaitItemEntry.COL_REQUEST_DAY));
     item.setRequestDate(new GregorianCalendar(requestYear, requestMonth, requestDay));
   } catch (android.database.CursorIndexOutOfBoundsException e) {
     // nothing found - that is ok
   }
   return item;
 }
예제 #13
0
  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
      if (requestCode == 100) {
        Uri uri = data.getParcelableExtra("uri");
        String[] projects =
            new String[] {MediaStore.Video.Media.DATA, MediaStore.Video.Media.DURATION};
        Cursor cursor = getActivity().getContentResolver().query(uri, projects, null, null, null);
        int duration = 0;
        String filePath = null;

        if (cursor.moveToFirst()) {
          // 路径:MediaStore.Audio.Media.DATA
          filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
          // 总播放时长:MediaStore.Audio.Media.DURATION
          duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION));
          EMLog.d(TAG, "duration:" + duration);
        }
        if (cursor != null) {
          cursor.close();
          cursor = null;
        }

        getActivity()
            .setResult(
                Activity.RESULT_OK,
                getActivity().getIntent().putExtra("path", filePath).putExtra("dur", duration));
        getActivity().finish();
      }
    }
  }
예제 #14
0
 @Override
 protected void onPostExecute(Boolean result) {
   super.onPostExecute(result);
   if (result) {
     Utils.setFolderCount(
         getNavigationViewMenu(), Utils.getTrashNavId(context), 0); // Set count to 0 for trash
     if (action == R.id.action_delete_all) {
       Utils.showToast(context, getString(R.string.all_notes_were_removed));
     } else {
       Utils.updateAllWidgets(context);
       if (cursor.getCount() > 0) { // check if trash is empty
         do {
           Utils.incrementFolderCount(
               getNavigationViewMenu(),
               cursor.getInt(cursor.getColumnIndexOrThrow(Constants.ID_COL)),
               cursor.getInt(cursor.getColumnIndexOrThrow(Constants.NOTES_COUNT_COL)));
         } while (cursor.moveToNext());
       }
       cursor.close();
       Utils.showToast(context, getString(R.string.all_notes_were_restored));
     }
     ((NoteListFragment) fragmentManager.findFragmentByTag(Constants.FRAGMENT_LIST))
         .reloadList();
   }
 }
예제 #15
0
  /**
   * Lookup a contact by a given nickname.
   *
   * <p>The returned contact will come with all known contact numbers and a lookup key.
   *
   * @param nickname
   * @return A contact, or null if none found or on error.
   */
  public Contact contactByNickname(String nickname) {
    if (!contactsReadModuleInstalled()) return null;

    final String[] projection = new String[] {Data.LOOKUP_KEY, DISPLAY_NAME, Nickname.NAME};
    final String selection =
        Nickname.NAME
            + "=?"
            + AND
            + Data.MIMETYPE
            + "='"
            + Nickname.CONTENT_ITEM_TYPE
            + "'"
            + LIMIT_1;
    final String[] selectionArgs = new String[] {nickname};
    Cursor c =
        mContentResolver.query(MAXS_DATA_CONTENT_URI, projection, selection, selectionArgs, null);

    Contact contact = null;
    if (c.moveToFirst()) {
      String lookupKey = c.getString(c.getColumnIndexOrThrow(Data.LOOKUP_KEY));
      String displayName = c.getString(c.getColumnIndexOrThrow(DISPLAY_NAME));
      nickname = c.getString(c.getColumnIndexOrThrow(Nickname.NAME));
      contact = new Contact(displayName, lookupKey);
      contact.setNickname(nickname);
      lookupContactNumbersFor(contact);
    }
    c.close();

    return contact;
  }
예제 #16
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Find contact by given number
    Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode("xxxxxxxxx"));
    String[] projection =
        new String[] {PhoneLookup.DISPLAY_NAME, PhoneLookup.NUMBER, PhoneLookup.NORMALIZED_NUMBER};
    Cursor c = getContentResolver().query(uri, projection, null, null, null);
    if (c.moveToFirst()) { // while(c.moveToNext()){
      // get display name
      String name = c.getString(c.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
      // get number assigned by user to given contact
      String number = c.getString(c.getColumnIndexOrThrow(PhoneLookup.NUMBER));
      // get normalized E164 number
      String normalized = c.getString(c.getColumnIndexOrThrow(PhoneLookup.NORMALIZED_NUMBER));
      Toast.makeText(
              getApplicationContext(),
              "Name: " + name + "Number: " + number + "; normalized: " + normalized,
              Toast.LENGTH_LONG)
          .show();
    }
    c.close();
  }
예제 #17
0
  /**
   * Lookup the numbers for a given contact.
   *
   * <p>Usually this is not needed because most methods already return the contacts with all known
   * contact numbers. Make sure to call {@link #contactsReadModuleInstalled()} first.
   *
   * @param contact
   */
  public void lookupContactNumbersFor(Contact contact) {
    if (!contactsReadModuleInstalled()) return;

    String lookupKey = contact.getLookupKey();
    // @formatter:off
    final String[] projection =
        new String[] {Phone.NUMBER, Phone.TYPE, Phone.LABEL, Phone.IS_SUPER_PRIMARY};
    // @formatter:on
    final String selection =
        ContactsContract.PhoneLookup.LOOKUP_KEY
            + "=?"
            + AND
            + ContactsContract.Data.MIMETYPE
            + "='"
            + Phone.CONTENT_ITEM_TYPE
            + "'";
    final String[] selectionArgs = new String[] {lookupKey};
    Cursor c =
        mContentResolver.query(MAXS_DATA_CONTENT_URI, projection, selection, selectionArgs, null);

    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
      String number =
          c.getString(c.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
      int type = c.getInt(c.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.TYPE));
      String label =
          c.getString(c.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.LABEL));
      boolean superPrimary =
          c.getInt(c.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.IS_SUPER_PRIMARY))
                  > 0
              ? true
              : false;
      contact.addNumber(number, type, label, superPrimary);
    }
    c.close();
  }
예제 #18
0
  public View newView(Context context, Cursor cursor, ViewGroup parent) {
    View view;
    final ViewHolder holder = new ViewHolder();

    if (!mIsList) {
      view = mInflater.inflate(R.layout.application_boxed, parent, false);
    } else {
      view = mInflater.inflate(R.layout.application_list, parent, false);
      holder.description = (TextView) view.findViewById(R.id.description);
      holder.icon = (ImageView) view.findViewById(R.id.icon);
    }

    holder.name = (TextView) view.findViewById(R.id.name);

    holder.idIndex = cursor.getColumnIndexOrThrow(LiveFolders._ID);
    holder.nameIndex = cursor.getColumnIndexOrThrow(LiveFolders.NAME);
    holder.descriptionIndex = cursor.getColumnIndex(LiveFolders.DESCRIPTION);
    holder.intentIndex = cursor.getColumnIndex(LiveFolders.INTENT);
    holder.iconBitmapIndex = cursor.getColumnIndex(LiveFolders.ICON_BITMAP);
    holder.iconResourceIndex = cursor.getColumnIndex(LiveFolders.ICON_RESOURCE);
    holder.iconPackageIndex = cursor.getColumnIndex(LiveFolders.ICON_PACKAGE);

    view.setTag(holder);

    return view;
  }
예제 #19
0
    @Override
    public ContextMenuSubject getSubject() {
      // Use the history id in order to allow removing history entries
      int id = mCursor.getInt(mCursor.getColumnIndexOrThrow(Combined.HISTORY_ID));

      String keyword = null;
      int keywordCol = mCursor.getColumnIndex(URLColumns.KEYWORD);
      if (keywordCol != -1) keyword = mCursor.getString(keywordCol);

      final String url = mCursor.getString(mCursor.getColumnIndexOrThrow(URLColumns.URL));

      Bitmap bitmap = Favicons.getInstance().getFaviconFromMemCache(url);
      byte[] favicon = null;

      if (bitmap != null) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        favicon = stream.toByteArray();
      }

      return new ContextMenuSubject(
          id,
          url,
          favicon,
          mCursor.getString(mCursor.getColumnIndexOrThrow(URLColumns.TITLE)),
          keyword,
          mCursor.getInt(mCursor.getColumnIndexOrThrow(Combined.DISPLAY)));
    }
예제 #20
0
 // Utility Functions
 // TODO: Move to Utils
 public static File convertImageUriToFile(Uri imageUri, Activity activity) {
   Cursor cursor = null;
   try {
     String[] proj = {
       MediaStore.Images.Media.DATA,
       MediaStore.Images.Media._ID,
       MediaStore.Images.ImageColumns.ORIENTATION
     };
     cursor =
         activity.managedQuery(
             imageUri, proj, // Which columns to return
             null, // WHERE clause; which rows to return (all rows)
             null, // WHERE clause selection arguments (none)
             null); // Order-by clause (ascending by name)
     int file_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
     int orientation_ColumnIndex =
         cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.ORIENTATION);
     if (cursor.moveToFirst()) {
       String orientation = cursor.getString(orientation_ColumnIndex);
       if (orientation == null) {
         Log.v("RHIMAGE Orientation", "Null Orientation");
       } else {
         Log.v("RHIMAGE Orientation", orientation);
       }
       return new File(cursor.getString(file_ColumnIndex));
     }
     return null;
   } finally {
     if (cursor != null) {
       cursor.close();
     }
   }
 }
예제 #21
0
  public People getFriend(int id) {
    Cursor cursor =
        _database.query(
            true,
            DATABASE_TABLE,
            new String[] {"_id", "email", "first_name", "last_name", "user_image_url", "status"},
            "_id=" + id,
            null,
            null,
            null,
            null,
            null);

    if (cursor == null || !cursor.moveToFirst()) return null;

    People friend = new People();
    friend.setId(cursor.getString(cursor.getColumnIndexOrThrow("_id")));
    friend.setEmail(cursor.getString(cursor.getColumnIndexOrThrow("email")));
    friend.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
    friend.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
    friend.setUserImageURL(cursor.getString(cursor.getColumnIndexOrThrow("user_image_url")));
    //
    //	friend.setFriendDate(Long.parseLong(cursor.getString(cursor.getColumnIndexOrThrow("user_date"))));
    friend.setStatus(People.STATUS_FRIEND);

    cursor.close();
    return friend;
  }
예제 #22
0
  public static Refuel getById(SQLiteDatabase db, long id) {
    Cursor c =
        db.query(
            RefuelTable.TABLE_NAME + " , " + ExpenseTable.TABLE_NAME,
            Utils.concat(RefuelTable.PROJECTION, ExpenseTable.PROJECTION),
            RefuelTable.EXP_ID + " = " + ExpenseTable.ID + " AND " + RefuelTable.ID + " = " + id,
            null,
            null,
            null,
            null);

    c.moveToFirst();
    Refuel ref =
        new Refuel(
            c.getInt(c.getColumnIndexOrThrow(ID)),
            c.getDouble(c.getColumnIndexOrThrow(ODOMETER)),
            c.getDouble(c.getColumnIndexOrThrow(RATE)),
            c.getDouble(c.getColumnIndexOrThrow(LITRE)),
            c.getString(c.getColumnIndexOrThrow(PUMP_NAME)),
            (c.getInt(c.getColumnIndexOrThrow(FULL_TANK)) != 0),
            new Expense(
                c.getInt(c.getColumnIndexOrThrow(ExpenseTable.ID)),
                c.getDouble(c.getColumnIndexOrThrow(ExpenseTable.AMOUNT)),
                c.getLong(c.getColumnIndexOrThrow(ExpenseTable.TIMESTAMP)),
                c.getString(c.getColumnIndexOrThrow(ExpenseTable.DESC)),
                c.getString(c.getColumnIndexOrThrow(ExpenseTable.TYPE))));
    c.close();
    return ref;
  }
예제 #23
0
 /**
  * @param cursor
  * @return
  */
 public static long[] getRandomSongListForCursor(Cursor cursor) {
   if (cursor == null) {
     return sEmptyList;
   }
   int len = cursor.getCount();
   long[] list = new long[len];
   cursor.moveToFirst();
   int colidx = -1;
   try {
     colidx = cursor.getColumnIndexOrThrow(Playlists.Members.AUDIO_ID);
   } catch (IllegalArgumentException ex) {
     colidx = cursor.getColumnIndexOrThrow(BaseColumns._ID);
   }
   for (int i = 0; i < len; i++) {
     list[i] = cursor.getLong(colidx);
     cursor.moveToNext();
   }
   int index;
   Random random = new Random();
   for (int i = list.length - 1; i > 0; i--) {
     index = random.nextInt(i + 1);
     if (index != i) {
       list[index] ^= list[i];
       list[i] ^= list[index];
       list[index] ^= list[i];
     }
   }
   return list;
 }
예제 #24
0
  public static ArrayList<Refuel> getByArg(SQLiteDatabase db, String whereClause, String sortBy) {
    Cursor c =
        db.query(
            RefuelTable.TABLE_NAME + " , " + ExpenseTable.TABLE_NAME,
            Utils.concat(RefuelTable.PROJECTION, ExpenseTable.PROJECTION),
            RefuelTable.EXP_ID
                + " = "
                + ExpenseTable.ID
                + ((whereClause != null) ? " AND " + whereClause : ""),
            null,
            null,
            null,
            (sortBy != null) ? sortBy : ID + " DESC");

    ArrayList<Refuel> refuels = new ArrayList<>();
    c.moveToFirst();
    while (!c.isAfterLast()) {
      refuels.add(
          new Refuel(
              c.getInt(c.getColumnIndexOrThrow(ID)),
              c.getDouble(c.getColumnIndexOrThrow(ODOMETER)),
              c.getDouble(c.getColumnIndexOrThrow(RATE)),
              c.getDouble(c.getColumnIndexOrThrow(LITRE)),
              c.getString(c.getColumnIndexOrThrow(PUMP_NAME)),
              (c.getInt(c.getColumnIndexOrThrow(FULL_TANK)) != 0),
              new Expense(
                  c.getInt(c.getColumnIndexOrThrow(ExpenseTable.ID)),
                  c.getDouble(c.getColumnIndexOrThrow(ExpenseTable.AMOUNT)),
                  c.getLong(c.getColumnIndexOrThrow(ExpenseTable.TIMESTAMP)),
                  c.getString(c.getColumnIndexOrThrow(ExpenseTable.DESC)),
                  c.getString(c.getColumnIndexOrThrow(ExpenseTable.TYPE)))));
    }
    c.close();
    return refuels;
  }
  public void onAccountsChanged(String[] accountsArray) {
    if (!"yes".equals(SystemProperties.get("ro.config.sync"))) {
      return;
    }

    // - Get a cursor (A) over all selected calendars over all accounts
    // - Get a cursor (B) over all subscribed feeds for calendar
    // - If an item is in A but not B then add a subscription
    // - If an item is in B but not A then remove the subscription

    ContentResolver cr = getContext().getContentResolver();
    Cursor cursorA = null;
    Cursor cursorB = null;
    try {
      cursorA =
          Calendar.Calendars.query(
              cr,
              null /* projection */,
              Calendar.Calendars.SELECTED + "=1",
              CALENDAR_KEY_SORT_ORDER);
      int urlIndexA = cursorA.getColumnIndexOrThrow(Calendar.Calendars.URL);
      int accountIndexA = cursorA.getColumnIndexOrThrow(Calendar.Calendars._SYNC_ACCOUNT);
      cursorB =
          SubscribedFeeds.Feeds.query(
              cr,
              FEEDS_KEY_COLUMNS,
              SubscribedFeeds.Feeds.AUTHORITY + "=?",
              new String[] {Calendar.AUTHORITY},
              FEEDS_KEY_SORT_ORDER);
      int urlIndexB = cursorB.getColumnIndexOrThrow(SubscribedFeeds.Feeds.FEED);
      int accountIndexB = cursorB.getColumnIndexOrThrow(SubscribedFeeds.Feeds._SYNC_ACCOUNT);
      for (CursorJoiner.Result joinerResult :
          new CursorJoiner(cursorA, CALENDAR_KEY_COLUMNS, cursorB, FEEDS_KEY_COLUMNS)) {
        switch (joinerResult) {
          case LEFT:
            SubscribedFeeds.addFeed(
                cr,
                cursorA.getString(urlIndexA),
                cursorA.getString(accountIndexA),
                Calendar.AUTHORITY,
                CalendarClient.SERVICE);
            break;
          case RIGHT:
            SubscribedFeeds.deleteFeed(
                cr,
                cursorB.getString(urlIndexB),
                cursorB.getString(accountIndexB),
                Calendar.AUTHORITY);
            break;
          case BOTH:
            // do nothing, since the subscription already exists
            break;
        }
      }
    } finally {
      // check for null in case an exception occurred before the cursors got created
      if (cursorA != null) cursorA.close();
      if (cursorB != null) cursorB.close();
    }
  }
  protected ArrayList<ImageData> loadDevicePhotos() {
    String[] projection = {
      MediaStore.Images.Thumbnails._ID,
      MediaStore.Images.Thumbnails.DATA,
      MediaStore.Images.Thumbnails.HEIGHT,
      MediaStore.Images.Thumbnails.WIDTH
    };

    Cursor cursor =
        getContentResolver()
            .query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projection, null, null, null);
    ArrayList<ImageData> imageDatas = new ArrayList<ImageData>();
    int photoHeightIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.HEIGHT);
    int photoWidthIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.WIDTH);
    int fileLocationIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    while (cursor.moveToNext()) {

      int photoHeight = cursor.getInt(photoHeightIndex);
      int photoWidth = cursor.getInt(photoWidthIndex);
      String fileLocation = cursor.getString(fileLocationIndex);

      if (photoWidth > 0 && photoHeight > 0) {
        ImageData imageData = new ImageData(fileLocation, photoWidth, photoHeight);
        imageDatas.add(imageData);
      }
    }
    cursor.close();

    return imageDatas;
  }
예제 #27
0
  /**
   * 从uri中获取SmsInfo对象数组
   *
   * @param uri
   * @param count
   * @return
   */
  private JSArray getSmsInfoFromUri(Uri uri, int count) {
    boolean limit = count > 0; // count大于0,则加上limit
    JSArray smsArray = new JSArray();
    ContentResolver resolver = context.getContentResolver();
    Cursor cursor =
        resolver.query(
            uri,
            null,
            null,
            null,
            Telephony.Sms.DEFAULT_SORT_ORDER + (limit ? " limit 0," + count : ""));

    int idIndex = cursor.getColumnIndexOrThrow(Telephony.Sms._ID);
    int addressIndex = cursor.getColumnIndexOrThrow(Telephony.Sms.ADDRESS);
    int dateIndex = cursor.getColumnIndexOrThrow(Telephony.Sms.DATE);
    int pidIndex = cursor.getColumnIndexOrThrow(Telephony.Sms.PERSON_ID);
    int bodyIndex = cursor.getColumnIndexOrThrow(Telephony.Sms.BODY);

    while (cursor.moveToNext()) {
      long id = cursor.getLong(idIndex);
      String address = cursor.getString(addressIndex);
      long pid = cursor.getLong(pidIndex);
      long date = cursor.getLong(dateIndex);
      String body = cursor.getString(bodyIndex);

      SmsInfo sms = new SmsInfo(body, date, address, id, pid);
      smsArray.add(sms);
    }
    return smsArray;
  }
예제 #28
0
  /**
   * Get all contacts for a given number
   *
   * @param number
   * @return All contacts with that number.
   */
  public Collection<Contact> contactsByNumber(String number) {
    if (!contactsReadModuleInstalled()) return null;

    number = ContactNumber.cleanNumber(number);
    if (!ContactNumber.isNumber(number)) return null;

    Uri uri = Uri.withAppendedPath(MAXS_PHONE_LOOKUP_CONTENT_FILTER_URI, Uri.encode(number));
    final String[] projection = new String[] {PhoneLookup.LOOKUP_KEY, DISPLAY_NAME};
    Cursor c = mContentResolver.query(uri, projection, null, null, null);

    Map<String, Contact> contactMap = new HashMap<String, Contact>();
    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
      String displayName = c.getString(c.getColumnIndexOrThrow(DISPLAY_NAME));
      String lookupKey = c.getString(c.getColumnIndexOrThrow(PhoneLookup.LOOKUP_KEY));

      Contact contact = contactMap.get(lookupKey);
      if (contact == null) {
        contact = new Contact(displayName, lookupKey);
        contactMap.put(lookupKey, contact);
        lookupContactNumbersFor(contact);
      }
    }
    c.close();

    return contactMap.values();
  }
  /**
   * Method to find the nearest location to the inputted origin Location
   *
   * @param c Cursor to set of a selection over all key location
   * @param origin Point to find nearest key location to (generally the user's current location)
   * @return Nearest key location to origin
   * @throws IllegalArgumentException if the Cursor does not contain the necessary latitude,
   *     longitude, and name columns
   */
  public static KeyLocation findNearestLoc(Cursor c, Location origin)
      throws IllegalArgumentException {
    // Initialize the nearest key location to null and the nearest_distance to infinity
    KeyLocation nearest = new KeyLocation();
    double nearest_dist = Double.MAX_VALUE;

    c.moveToFirst();
    do {
      // Iterate over all of the key locations and find the one nearest to the origin
      double longitude = c.getDouble(c.getColumnIndexOrThrow(KeyLocationEntry.COLUMN_LONGITUDE));
      double latitude = c.getDouble(c.getColumnIndexOrThrow(KeyLocationEntry.COLUMN_LATITUDE));

      Location loc = new Location("");
      loc.setLongitude(longitude);
      loc.setLatitude(latitude);

      double dist = loc.distanceTo(origin);
      if (dist < nearest_dist) {
        String name = c.getString(c.getColumnIndexOrThrow(KeyLocationEntry.COLUMN_NAME));
        double lt = c.getDouble(c.getColumnIndexOrThrow(KeyLocationEntry.COLUMN_LATITUDE));
        double lg = c.getDouble(c.getColumnIndexOrThrow(KeyLocationEntry.COLUMN_LONGITUDE));

        nearest = new KeyLocation(name, lt, lg);
        nearest_dist = dist;
      }
    } while (c.moveToNext());

    return nearest;
  }
  private DBTileSource(Context context, String path) throws SQLiteException {
    super(null);
    mDB =
        SQLiteDatabase.openDatabase(
            path, null, SQLiteDatabase.OPEN_READONLY | SQLiteDatabase.NO_LOCALIZED_COLLATORS);

    Cursor cursor = mDB.rawQuery("select * from zoom_levels", null);
    try {
      int bbox_x0 = cursor.getColumnIndexOrThrow("bbox_x0");
      int bbox_x1 = cursor.getColumnIndexOrThrow("bbox_x1");
      int bbox_y0 = cursor.getColumnIndexOrThrow("bbox_y0");
      int bbox_y1 = cursor.getColumnIndexOrThrow("bbox_y1");
      int product_code = cursor.getColumnIndexOrThrow("product_code");
      int zoom_level = cursor.getColumnIndexOrThrow("zoom_level");
      ArrayList<ZoomLevel> levels = new ArrayList<ZoomLevel>();
      while (cursor.moveToNext()) {
        ZoomLevel zl =
            new ZoomLevel(
                cursor.getInt(zoom_level),
                cursor.getString(product_code),
                cursor.getInt(bbox_x0),
                cursor.getInt(bbox_x1),
                cursor.getInt(bbox_y0),
                cursor.getInt(bbox_y1));

        levels.add(zl);
      }
      mZoomLevels = levels.toArray(new ZoomLevel[0]);
    } finally {
      cursor.close();
    }
  }