Exemplo n.º 1
0
    @Override
    protected MergeCursor doInBackground(String... params) {
      // TODO Auto-generated method stub
      mType = params[0];
      if (params[0].equals(SqlTypeAdd)) {
        DbUtils.exeSql(buildBeforAddSql(params[1]), false); // 先删除再添加
        DbUtils.exeSql(buildAddSql(params[1]), false);
      } else if (params[0].equals(SqlTypeClear)) {
        DbUtils.exeSql(new SqlExeObj(buildDeleteSql()), false);
      } else {
        try {
          Cursor cursor = DbUtils.query(buildQuerySql(), null, false);
          if (cursor != null && cursor.moveToFirst()) {
            MatrixCursor m = new MatrixCursor(new String[] {"_id", "subkey", "code", "name"});
            m.addRow(new String[] {"100", SpecialRow, "null", "清除浏览记录"});
            return new MergeCursor(new Cursor[] {cursor, m});
          }
        } catch (WrapException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }

      return null;
    }
 /**
  * If values are passed in, replaces any cached cursor with one containing new values, and then
  * closes the previously cached one (if any, and if not in use) If values are not passed in,
  * removes the row from cache If the row was locked, unlock it
  *
  * @param id the id of the row
  * @param values new ContentValues for the row (or null if row should simply be removed)
  * @param wasLocked whether or not the row was locked; if so, the lock will be removed
  */
 private void unlockImpl(String id, ContentValues values, boolean wasLocked) {
   Cursor c = get(id);
   if (c != null) {
     if (MailActivityEmail.DEBUG && DEBUG_CACHE) {
       LogUtils.d(mLogTag, "=========== Unlocking cache for: " + id);
     }
     if (values != null && !sLockCache) {
       MatrixCursor cursor = getMatrixCursor(id, mBaseProjection, values);
       if (cursor != null) {
         if (MailActivityEmail.DEBUG && DEBUG_CACHE) {
           LogUtils.d(mLogTag, "=========== Recaching with new values: " + id);
         }
         cursor.moveToFirst();
         mLruCache.put(id, cursor);
       } else {
         mLruCache.remove(id);
       }
     } else {
       mLruCache.remove(id);
     }
     // If there are no cursors using the old cached cursor, close it
     if (!sActiveCursors.contains(c)) {
       c.close();
     }
   }
   if (wasLocked) {
     mLockMap.subtract(id);
   }
 }
  private Cursor createCursor(SearchResult searchResult) {
    MatrixCursor cursor = new MatrixCursor(COLUMNS);
    if (searchResult == null) {
      return cursor;
    }

    for (Artist artist : searchResult.getArtists()) {
      String icon = RESOURCE_PREFIX + R.drawable.ic_action_artist;
      cursor.addRow(
          new Object[] {
            artist.getId(), artist.getName(), null, artist.getId(), artist.getName(), icon
          });
    }
    for (MusicDirectory.Entry album : searchResult.getAlbums()) {
      String icon = RESOURCE_PREFIX + R.drawable.ic_action_album;
      cursor.addRow(
          new Object[] {
            album.getId(),
            album.getTitle(),
            album.getArtist(),
            album.getId(),
            album.getTitle(),
            icon
          });
    }
    for (MusicDirectory.Entry song : searchResult.getSongs()) {
      String icon = RESOURCE_PREFIX + R.drawable.ic_action_song;
      cursor.addRow(
          new Object[] {
            song.getId(), song.getTitle(), song.getArtist(), song.getParent(), null, icon
          });
    }
    return cursor;
  }
Exemplo n.º 4
0
  @SmallTest
  public void testCardFromCursor() {
    MatrixCursor cursor = new MatrixCursor(CardsQuery.PROJECTION);
    cursor.moveToFirst();
    Object[] values =
        new Object[] {
          123456789L,
          "question",
          "answer",
          "ftag1 ftag2",
          "mtag",
          "model",
          2,
          13000.0,
          25.0,
          1.25,
          12950.0,
        };
    cursor.addRow(values);
    cursor.moveToFirst();

    HashMap<String, String> card = CardsQuery.newCardFromCursor(cursor);

    assertEquals("123456789", card.get("id"));
    assertEquals("question", card.get("question"));
    assertEquals("answer", card.get("answer"));
    assertEquals("00", card.get("flags"));
    assertEquals("ftag1 ftag2 mtag model", card.get("tags"));
    assertEquals("13000.0", card.get("due"));
    assertEquals("25.0", card.get("interval"));
    assertEquals("1.25", card.get("factor"));
    assertEquals("12950.0", card.get("created"));
  }
  @Override
  public Cursor querySearchDocuments(String rootId, String query, String[] projection)
      throws FileNotFoundException {
    final MatrixCursor result = new MatrixCursor(resolveDocumentProjection(projection));

    final File parent;
    synchronized (mRootsLock) {
      parent = mRoots.get(rootId).path;
    }

    final LinkedList<File> pending = new LinkedList<File>();
    pending.add(parent);
    while (!pending.isEmpty() && result.getCount() < 24) {
      final File file = pending.removeFirst();
      if (file.isDirectory()) {
        for (File child : file.listFiles()) {
          pending.add(child);
        }
      }
      if (file.getName().toLowerCase().contains(query)) {
        includeFile(result, null, file);
      }
    }
    return result;
  }
  // Visible for testing
  /* package */ static Cursor removeDuplicateDestinations(Cursor original) {
    final MatrixCursor result = new MatrixCursor(original.getColumnNames(), original.getCount());
    final HashSet<String> destinationsSeen = new HashSet<String>();

    original.moveToPosition(-1);
    while (original.moveToNext()) {
      final String destination = original.getString(Query.DESTINATION);
      if (destinationsSeen.contains(destination)) {
        continue;
      }
      destinationsSeen.add(destination);

      result.addRow(
          new Object[] {
            original.getString(Query.NAME),
            original.getString(Query.DESTINATION),
            original.getInt(Query.DESTINATION_TYPE),
            original.getString(Query.DESTINATION_LABEL),
            original.getLong(Query.CONTACT_ID),
            original.getLong(Query.DATA_ID),
            original.getString(Query.PHOTO_THUMBNAIL_URI),
            original.getInt(Query.DISPLAY_NAME_SOURCE)
          });
    }

    return result;
  }
  private void populateChallengesList() {
    Log.d(TAG, "populating challenger list");
    challenges.moveToFirst();
    Log.d(
        TAG,
        "first challenger: "
            + challenges.getString(challenges.getColumnIndex(CHALLENGE_SOURCE_HANDLE_COL)));
    String[] from = {CHALLENGE_SOURCE_HANDLE_COL};
    int[] to = {R.id.challenger_text_view};

    SimpleCursorAdapter adapter =
        new SimpleCursorAdapter(this, R.layout.challenger_text_view, challenges, from, to);
    ListView lv = (ListView) findViewById(R.id.view_challenges);
    lv.setAdapter(adapter);
    final CursorWrapper c = new CursorWrapper(challenges);

    lv.setOnItemClickListener(
        new OnItemClickListener() {
          public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
            // Move the cursor to the selected item
            c.moveToPosition(pos);

            int cid = c.getInt(c.getColumnIndex("_id"));
            int sourceId = c.getInt(c.getColumnIndex(CHALLENGE_SOURCE_ID_COL));
            String sourceHandle = c.getString(c.getColumnIndex(CHALLENGE_SOURCE_HANDLE_COL));
            int targetId = c.getInt(c.getColumnIndex(CHALLENGE_TARGET_COL));
            challengeDialog(cid, sourceId, sourceHandle, targetId);
          }
        });
  }
  protected MatrixCursor handleLocalAllQuery() {

    MatrixCursor cursor =
        new MatrixCursor(new String[] {CommonConstants.KEY_FIELD, CommonConstants.VALUE_FIELD});
    File filesDir = getContext().getFilesDir();
    FileInputStream inputStream;
    try {
      for (File file : filesDir.listFiles()) {
        String filename = null;
        filename = file.getName();
        inputStream = getContext().openFileInput(filename);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line = null;
        String string = "";
        while ((line = reader.readLine()) != null) {
          string = string + line;
        }

        inputStream.close();
        reader.close();
        String[] keyArr = filename.split(CommonConstants.DOLLAR_SEP_SPLIT);
        String key = keyArr[2];
        MatrixCursor.RowBuilder rowBuilder = cursor.newRow();
        rowBuilder.add(CommonConstants.KEY_FIELD, key);
        rowBuilder.add(CommonConstants.VALUE_FIELD, string);
        // Log.v(TAG,"Added "+ key +" : "+string+" to response");
      }
    } catch (Exception e) {
      e.printStackTrace();
      // Log.v("query", "File read failed");
    }
    return cursor;
  }
Exemplo n.º 9
0
    public Cursor getAccountUnread(int accountNumber) {
      String[] projection = new String[] {"accountName", "unread"};

      MatrixCursor ret = new MatrixCursor(projection);

      Account myAccount;
      AccountStats myAccountStats = null;

      Object[] values = new Object[2];

      for (Account account : Preferences.getPreferences(getContext()).getAvailableAccounts()) {
        if (account.getAccountNumber() == accountNumber) {
          myAccount = account;
          try {
            myAccountStats = account.getStats(getContext());
            values[0] = myAccount.getDescription();
            if (myAccountStats == null) {
              values[1] = 0;
            } else {
              values[1] = myAccountStats.unreadMessageCount;
            }

            ret.addRow(values);
          } catch (MessagingException e) {
            Log.e(K9.LOG_TAG, e.getMessage());
            values[0] = "Unknown";
            values[1] = 0;
          }
        }
      }

      return ret;
    }
  @Override
  public Cursor query(
      Uri uri, String[] projections, String selection, String[] selectionArgs, String sortOrder) {
    if (selection != null && !selection.equals(Items.NAME + " = ?")) {
      return null;
    }

    if (data == null) {
      data = new ArrayList<String[]>();
      if (!load()) {
        return null;
      }
    }

    MatrixCursor cursor = new MatrixCursor(Items.COLUMNS);
    for (String[] row : data) {
      if (selection == null) {
        cursor.addRow(row);
      } else if (row[6].equals(selectionArgs[0])) {
        cursor.addRow(row);
      }
    }

    return cursor;
  }
  @Override
  public synchronized Cursor query(
      Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    assert (uri.getPathSegments().isEmpty());

    final MatrixCursor c =
        new MatrixCursor(new String[] {Columns.ID, Columns.ITEM, Columns.CREATION_DATE});

    ipAddress = selection;

    String result = httpRequest("http://" + ipAddress + "/postitlist.php", null);

    // Parse the received JSON data
    if (!result.equals("")) {
      try {
        JSONObject jdata = new JSONObject(result);
        JSONArray jArray = jdata.getJSONArray("items");

        for (int i = 0; i < jArray.length(); i++) {
          JSONObject jobj = jArray.getJSONObject(i);
          String item = jobj.getString(Columns.ITEM);
          String date = jobj.getString(Columns.CREATION_DATE);
          c.addRow(new Object[] {i, item, date});
        }

      } catch (JSONException e) {
        Log.e(PostitListWidgetProvider.TAG, "Error parsing data " + e.toString());
      }
    }

    return c;
  }
 /** Return a Cursor containing just one message from the ICC. */
 private Cursor getSingleMessageFromIcc(String messageIndexString) {
   int messageIndex = -1;
   try {
     Integer.parseInt(messageIndexString);
   } catch (NumberFormatException exception) {
     throw new IllegalArgumentException("Bad SMS ICC ID: " + messageIndexString);
   }
   ArrayList<SmsMessage> messages;
   final SmsManager smsManager = SmsManager.getDefault();
   // Use phone id to avoid AppOps uid mismatch in telephony
   long token = Binder.clearCallingIdentity();
   try {
     messages = smsManager.getAllMessagesFromIcc();
   } finally {
     Binder.restoreCallingIdentity(token);
   }
   if (messages == null) {
     throw new IllegalArgumentException("ICC message not retrieved");
   }
   final SmsMessage message = messages.get(messageIndex);
   if (message == null) {
     throw new IllegalArgumentException("Message not retrieved. ID: " + messageIndexString);
   }
   MatrixCursor cursor = new MatrixCursor(ICC_COLUMNS, 1);
   cursor.addRow(convertIccToSms(message, 0));
   return withIccNotificationUri(cursor);
 }
Exemplo n.º 13
0
  /** Loads search results from server */
  private Cursor search(String query) {
    String[] columns =
        new String[] {
          BaseColumns._ID, SearchManager.SUGGEST_COLUMN_TEXT_1, SearchManager.SUGGEST_COLUMN_TEXT_2
        };
    MatrixCursor res = new MatrixCursor(columns);
    if (query == null) return null;

    query = query.toLowerCase();
    ServerResponse result = ApiHandler.getArray(ApiHandler.searchURL + query, getContext());
    JSONArray mData = result.getArrayData();
    if (mData != null)
      for (int i = 0; i < mData.length(); i++) {
        JSONObject user;
        try {
          user = mData.getJSONObject(i);
          res.addRow(
              new String[] {
                user.getString("id"), user.getString("first_name"), user.getString("last_name")
              });
        } catch (JSONException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }

    return res;
  }
Exemplo n.º 14
0
  public Cursor getHugeCursor(String[] projection) {
    Cursor c = createSourceCursor(60);
    MatrixCursor matrixCursor;
    String[] columnRow;

    HashMap<String, String> sFullProjection = new HashMap<String, String>();

    sFullProjection.put(COLUMN_01, null);
    sFullProjection.put(COLUMN_02, null);
    sFullProjection.put(COLUMN_03, null);
    sFullProjection.put(COLUMN_04, null);
    sFullProjection.put(COLUMN_05, null);
    sFullProjection.put(COLUMN_06, null);
    sFullProjection.put(COLUMN_07, null);
    sFullProjection.put(COLUMN_08, null);
    sFullProjection.put(COLUMN_09, null);
    sFullProjection.put(COLUMN_10, null);

    // if null fulfill whole projection array
    if (projection == null) {
      Set<String> keys = sFullProjection.keySet();
      projection = new String[keys.size()];
      int i = 0;
      loki("No column names, create some");
      for (String key : keys) {
        projection[i++] = key;
        loki(key);
      }
    }

    // Create suitable matrix cursor
    matrixCursor = new MatrixCursor(projection, c.getCount());
    columnRow = new String[projection.length];

    // Iterate through source cursor and fulfill new cursor
    while (c.moveToNext()) {
      // Projection array have to contain all output cursor default columns, so some of then could
      // be empty
      sFullProjection.put(COLUMN_01, c.getString(c.getColumnIndex("one")));
      sFullProjection.put(COLUMN_02, c.getString(c.getColumnIndex("two")));
      sFullProjection.put(COLUMN_03, c.getString(c.getColumnIndex("three")));
      sFullProjection.put(COLUMN_04, c.getString(c.getColumnIndex("four")));
      sFullProjection.put(COLUMN_05, null);
      sFullProjection.put(COLUMN_06, "always");
      sFullProjection.put(COLUMN_07, null);
      sFullProjection.put(COLUMN_08, null);
      sFullProjection.put(COLUMN_09, null);
      sFullProjection.put(COLUMN_10, null);

      // Prepare row for new cursor
      for (int i = 0; i < columnRow.length; i++) {
        columnRow[i] = sFullProjection.get(projection[i]);
      }
      matrixCursor.addRow(columnRow);
    }
    c.close();

    return matrixCursor;
  }
Exemplo n.º 15
0
  private Message createMsgFromCursor(MatrixCursor mCursor) {
    Message msg = new Message();

    msg.setUserId(mCursor.getInt(1));
    msg.setText(mCursor.getString(2));
    msg.setTimestamp(formatting.formatStringToDate(mCursor.getString(3), msg.FORMAT));
    return msg;
  }
Exemplo n.º 16
0
 protected Cursor buildCursorFromMap(Map<String, ? extends Object> map) {
   if (map == null) {
     return null;
   }
   MatrixCursor cursor = new MatrixCursor(map.keySet().toArray(new String[map.size()]));
   cursor.addRow(map.values());
   return cursor;
 }
 private Cursor a()
 {
   String[] arrayOfString = b;
   MatrixCursor localMatrixCursor = new MatrixCursor(arrayOfString, 1);
   MatrixCursor.RowBuilder localRowBuilder1 = localMatrixCursor.newRow();
   Boolean localBoolean = Boolean.valueOf(gu.h());
   MatrixCursor.RowBuilder localRowBuilder2 = localRowBuilder1.add(localBoolean);
   return localMatrixCursor;
 }
 /** Creates a cursor that contains a single row and maps the section to the given value. */
 private Cursor createHeaderCursorFor(int section) {
   MatrixCursor matrixCursor = new MatrixCursor(CallLogQuery.EXTENDED_PROJECTION);
   // The values in this row correspond to default values for _PROJECTION from CallLogQuery
   // plus the section value.
   matrixCursor.addRow(
       new Object[] {
         0L, "", 0L, 0L, 0, "", "", "", null, 0, null, null, null, null, 0L, null, 0, section
       });
   return matrixCursor;
 }
  /** Create chat list adapter with unique chat ID entries */
  private ChatListAdapter createChatListAdapter() {
    Uri uri = RichMessagingData.CONTENT_URI;
    String[] PROJECTION =
        new String[] {
          RichMessagingData.KEY_ID,
          RichMessagingData.KEY_CHAT_ID,
          RichMessagingData.KEY_CHAT_SESSION_ID,
          RichMessagingData.KEY_TYPE,
          RichMessagingData.KEY_CONTACT,
          RichMessagingData.KEY_DATA,
          RichMessagingData.KEY_TIMESTAMP
        };
    String sortOrder = RichMessagingData.KEY_TIMESTAMP + " DESC ";
    String where =
        "("
            + RichMessagingData.KEY_TYPE
            + "="
            + EventsLogApi.TYPE_GROUP_CHAT_SYSTEM_MESSAGE
            + " OR "
            + RichMessagingData.KEY_TYPE
            + "="
            + EventsLogApi.TYPE_CHAT_SYSTEM_MESSAGE
            + ") AND ("
            + RichMessagingData.KEY_STATUS
            + "="
            + EventsLogApi.EVENT_INITIATED
            + " OR "
            + RichMessagingData.KEY_STATUS
            + "="
            + EventsLogApi.EVENT_INVITED
            + ")";
    Cursor cursor = getContentResolver().query(uri, PROJECTION, where, null, sortOrder);

    Vector<String> items = new Vector<String>();
    MatrixCursor matrix = new MatrixCursor(PROJECTION);
    while (cursor.moveToNext()) {
      String chatId = cursor.getString(1);
      if (!items.contains(chatId)) {
        matrix.addRow(
            new Object[] {
              cursor.getInt(0),
              cursor.getString(1),
              cursor.getString(2),
              cursor.getInt(3),
              cursor.getString(4),
              cursor.getString(5),
              cursor.getString(6)
            });
        items.add(chatId);
      }
    }
    cursor.close();

    return new ChatListAdapter(this, matrix);
  }
  private void processDisplayFor(final Foods foods) {
    String[] columns = {"_id", "name", "descr"};
    int[] viewsToBind = {R.id.food_id, R.id.food_name, R.id.food_description};

    MatrixCursor cursor = new MatrixCursor(columns);

    for (Food food : foods.getFood()) {
      cursor.addRow(food.getColumnValuesForCursor());
    }

    setListAdapter(new SimpleCursorAdapter(this, R.layout.list_item, cursor, columns, viewsToBind));
  }
 public Cursor query(
     Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
   String[] columnNames = {
     SocialContract.Community.NAME,
     SocialContract.Community.OWNER_ID,
     SocialContract.Community.CREATION_DATE
   };
   MatrixCursor cursor = new MatrixCursor(columnNames, 10);
   String[] columnValues = {"XYZ", "*****@*****.**", "today"};
   cursor.addRow(columnValues);
   return cursor;
 }
Exemplo n.º 22
0
 @Override
 public Cursor query(
     Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
   MatrixCursor matrixCursor = new MatrixCursor(new String[] {"_id", "gitdir"});
   for (File repoDir : reposDir.listFiles()) {
     File gitdir = RepositoryCache.FileKey.resolve(repoDir, FS.detect());
     if (gitdir != null) {
       matrixCursor.newRow().add(gitdir.hashCode()).add(gitdir);
     }
   }
   return matrixCursor;
 }
 private Cursor getSuggestions(String query) {
   MatrixCursor cursor = new MatrixCursor(COLUMNS);
   if (query == null) {
     return cursor;
   }
   Set<SearchTerm> results = layerManager.getObjectNamesMatchingPrefix(query);
   Log.d("SearchTermsProvider", "Got results n=" + results.size());
   for (SearchTerm result : results) {
     cursor.addRow(columnValuesOfSuggestion(result));
   }
   return cursor;
 }
 @Override
 public Cursor queryRoots(String[] projection) throws FileNotFoundException {
   final MatrixCursor result = new MatrixCursor(resolveRootProjection(projection));
   final RowBuilder row = result.newRow();
   row.add(Root.COLUMN_ROOT_ID, DOC_ID_ROOT);
   row.add(
       Root.COLUMN_FLAGS,
       Root.FLAG_LOCAL_ONLY | Root.FLAG_SUPPORTS_RECENTS | Root.FLAG_SUPPORTS_CREATE);
   row.add(Root.COLUMN_ICON, R.mipmap.ic_launcher_download);
   row.add(Root.COLUMN_TITLE, getContext().getString(R.string.root_downloads));
   row.add(Root.COLUMN_DOCUMENT_ID, DOC_ID_ROOT);
   return result;
 }
Exemplo n.º 25
0
 // checks if any exercises have been removed and updates the global list accordingly
 // also rewrites the workouts file on the device
 private void checkRemoved() {
   ArrayList<Integer> positions = adapter.getCursorPositions();
   ArrayList<Exercise> newExercises = new ArrayList<Exercise>();
   if (cursor != null) {
     cursor.moveToFirst();
     for (int i = 0; i < positions.size(); i++) {
       int cursorPosition = positions.get(i);
       cursor.moveToPosition(cursorPosition);
       String c = cursor.getString(1);
       newExercises.add(workout.getExercise(c));
     }
     workout.setExercises(newExercises);
   }
 }
 @Override
 public void onLoadFinished(Loader<Cursor> arg0, Cursor data) {
   if (getArguments().getBoolean(KEY_WITH_ROOT)) {
     MatrixCursor extras = new MatrixCursor(projection);
     extras.addRow(
         new String[] {
           "0", getString(R.string.transform_subcategory_to_main),
         });
     mCursor = new MergeCursor(new Cursor[] {extras, data});
   } else {
     mCursor = data;
   }
   mAdapter.swapCursor(mCursor);
 }
Exemplo n.º 27
0
    public Cursor getAllAccounts() {
      String[] projection = new String[] {"accountNumber", "accountName"};

      MatrixCursor ret = new MatrixCursor(projection);

      for (Account account : Preferences.getPreferences(getContext()).getAccounts()) {
        Object[] values = new Object[2];
        values[0] = account.getAccountNumber();
        values[1] = account.getDescription();
        ret.addRow(values);
      }

      return ret;
    }
Exemplo n.º 28
0
  /**
   * Returns a cursor based on the data in the attachments table, or null if the attachment is not
   * recorded in the table.
   *
   * <p>Supports REST Uri only, for a single row - selection, selection args, and sortOrder are
   * ignored (non-null values should probably throw an exception....)
   */
  @Override
  public Cursor query(
      Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    if (projection == null) {
      projection =
          new String[] {
            AttachmentProviderColumns._ID, AttachmentProviderColumns.DATA,
          };
    }

    List<String> segments = uri.getPathSegments();
    String accountId = segments.get(0);
    String id = segments.get(1);
    String format = segments.get(2);
    String name = null;
    int size = -1;
    String contentUri = null;

    uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, Long.parseLong(id));
    Cursor c = getContext().getContentResolver().query(uri, PROJECTION_QUERY, null, null, null);
    try {
      if (c.moveToFirst()) {
        name = c.getString(0);
        size = c.getInt(1);
        contentUri = c.getString(2);
      } else {
        return null;
      }
    } finally {
      c.close();
    }

    MatrixCursor ret = new MatrixCursor(projection);
    Object[] values = new Object[projection.length];
    for (int i = 0, count = projection.length; i < count; i++) {
      String column = projection[i];
      if (AttachmentProviderColumns._ID.equals(column)) {
        values[i] = id;
      } else if (AttachmentProviderColumns.DATA.equals(column)) {
        values[i] = contentUri;
      } else if (AttachmentProviderColumns.DISPLAY_NAME.equals(column)) {
        values[i] = name;
      } else if (AttachmentProviderColumns.SIZE.equals(column)) {
        values[i] = size;
      }
    }
    ret.addRow(values);
    return ret;
  }
Exemplo n.º 29
0
  @Override
  public Cursor query(
      Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {

    String[] columnNames = (projection == null) ? DEFAULT_PROJECTION : projection;

    List<String> segments = uri.getPathSegments();
    String dbName = segments.get(0);
    String id = segments.get(1);

    // Versions of K-9 before 3.400 had a database name here, not an
    // account UID, so implement a bit of backcompat
    if (dbName.endsWith(".db")) {
      dbName = dbName.substring(0, dbName.length() - 3);
    }

    final AttachmentInfo attachmentInfo;
    try {
      final Account account = Preferences.getPreferences(getContext()).getAccount(dbName);
      attachmentInfo = LocalStore.getInstance(account, getContext()).getAttachmentInfo(id);
    } catch (MessagingException e) {
      Log.e(K9.LOG_TAG, "Unable to retrieve attachment info from local store for ID: " + id, e);
      return null;
    }

    if (attachmentInfo == null) {
      if (K9.DEBUG) {
        Log.d(K9.LOG_TAG, "No attachment info for ID: " + id);
      }
      return null;
    }

    MatrixCursor ret = new MatrixCursor(columnNames);
    Object[] values = new Object[columnNames.length];
    for (int i = 0, count = columnNames.length; i < count; i++) {
      String column = columnNames[i];
      if (AttachmentProviderColumns._ID.equals(column)) {
        values[i] = id;
      } else if (AttachmentProviderColumns.DATA.equals(column)) {
        values[i] = uri.toString();
      } else if (AttachmentProviderColumns.DISPLAY_NAME.equals(column)) {
        values[i] = attachmentInfo.name;
      } else if (AttachmentProviderColumns.SIZE.equals(column)) {
        values[i] = attachmentInfo.size;
      }
    }
    ret.addRow(values);
    return ret;
  }
 @Override
 public Cursor queryRoots(String[] projection) throws FileNotFoundException {
   final MatrixCursor result = new MatrixCursor(resolveRootProjection(projection));
   synchronized (mRootsLock) {
     for (RootInfo root : mRoots.values()) {
       final RowBuilder row = result.newRow();
       row.add(Root.COLUMN_ROOT_ID, root.rootId);
       row.add(Root.COLUMN_FLAGS, root.flags);
       row.add(Root.COLUMN_TITLE, root.title);
       row.add(Root.COLUMN_DOCUMENT_ID, root.docId);
       row.add(Root.COLUMN_AVAILABLE_BYTES, root.path.getFreeSpace());
     }
   }
   return result;
 }