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;
  }
  @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;
  }
Exemplo n.º 3
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;
    }
 /** 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.º 5
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;
  }
  @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;
  }
Exemplo n.º 7
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;
    }
Exemplo n.º 8
0
 private Cursor querySettings(String settingName) {
   SharedPreferences prefs =
       getContext().getSharedPreferences(PREF_SETTINGS, Context.MODE_WORLD_READABLE);
   MatrixCursor cursor = new MatrixCursor(new String[] {COL_SETTING, COL_VALUE});
   if (settingName == null)
     for (String settingKey : prefs.getAll().keySet())
       try {
         cursor.addRow(
             new Object[] {getSettingName(settingKey), prefs.getString(settingKey, null)});
       } catch (Throwable ex) {
         // Legacy boolean
       }
   else
     cursor.addRow(new Object[] {settingName, prefs.getString(getSettingPref(settingName), null)});
   return cursor;
 }
Exemplo n.º 9
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"));
  }
  // 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;
  }
Exemplo n.º 11
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.º 12
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;
 }
Exemplo n.º 13
0
  private void initClusterDrawer() {
    emptyClusterCursor = new MatrixCursor(CLUSTER_PROJECTION);
    emptyClusterCursor.addRow(new String[] {allClusters, null, null, null});

    SimpleCursorAdapter clusterListAdapter =
        new SimpleCursorAdapter(
            this,
            R.layout.cluster_list_item,
            null,
            CLUSTER_PROJECTION,
            new int[] {R.id.cluster_view},
            0);

    CursorAdapterLoader clusterAdapterLoader =
        new CursorAdapterLoader(clusterListAdapter) {
          @Override
          public Loader<Cursor> onCreateLoader(int id, Bundle args) {
            return provider.query(Cluster.class).orderBy(NAME).asLoader();
          }

          @Override
          public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
            super.onLoadFinished(loader, new MergeCursor(new Cursor[] {emptyClusterCursor, data}));
          }
        };

    clusterListAdapter.setViewBinder(
        new SimpleCursorAdapter.ViewBinder() {
          @Override
          public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
            if (columnIndex != 0) {
              // do not display id column
              return true;
            }
            TextView textView = (TextView) view;
            String clusterName =
                cursor.getString(
                    cursor.getColumnIndex(NAME)); // only names selected, thus only 1 column
            textView.setText(clusterName);

            return true;
          }
        });
    clusterDrawer.setAdapter(clusterListAdapter);

    getSupportLoaderManager().initLoader(CLUSTER_LOADER, null, clusterAdapterLoader);

    drawerToggle =
        new ActionBarDrawerToggle(
            this, drawerLayout, R.string.navigation_drawer_open, R.string.navigation_drawer_close);

    drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
    drawerLayout.setDrawerListener(drawerToggle);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

    drawerToggle.syncState();
  }
 /** 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));
  }
 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;
 }
 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.º 19
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // setContentView(R.layout.activity_main);

    String[] lista = {"_id", "imagen", "titulo", "descripcion"};
    MatrixCursor cursor = new MatrixCursor(lista);
    cursor.addRow(new Object[] {"0", R.drawable.pudge, "Heroe", "Accesorio de DOTA2"});
    cursor.addRow(new Object[] {"1", R.drawable.bu, "Imagen", "Bailando con Bu"});

    String[] Desdeestascolumnas = {"imagen", "titulo", "Descripcion"};
    int[] Aestascolumnas = {R.id.Imag, R.id.Texto1, R.id.Texto2};
    SimpleCursorAdapter simple =
        new SimpleCursorAdapter(
            this, R.layout.activity_main, cursor, Desdeestascolumnas, Aestascolumnas, 0);

    final ListView l = getListView();
    l.setAdapter(simple);

    l.setOnItemClickListener(
        new AdapterView.OnItemClickListener() {
          @Override
          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch (position) {
              case 0:
                Toast.makeText(getApplicationContext(), "Profe una helenas", Toast.LENGTH_SHORT)
                    .show();
                Intent item = new Intent(MainActivity.this, Main2Activity.class);
                startActivity(item);
                break;
              case 1:
                Toast.makeText(
                        getApplicationContext(), "Profe no quiere bailar n.n", Toast.LENGTH_SHORT)
                    .show();
                break;
            }
          }
        });
  }
 @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.º 21
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.º 22
0
 private void getUsage(int uid, String restrictionName, String methodName, MatrixCursor cursor) {
   SharedPreferences prefs =
       getContext()
           .getSharedPreferences(
               PREF_USAGE + "." + restrictionName,
               Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS);
   String values = prefs.getString(getUsagePref(uid, methodName), null);
   if (values != null) {
     String[] value = values.split(":");
     long timeStamp = Long.parseLong(value[0]);
     boolean restricted = Boolean.parseBoolean(value[1]);
     cursor.addRow(new Object[] {uid, restrictionName, methodName, restricted, timeStamp});
   }
 }
Exemplo n.º 23
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;
  }
Exemplo n.º 24
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.º 25
0
    /**
     * @param projection Projection to use. If <code>null</code>, use the default projection.
     * @return Never <code>null</code>.
     * @throws InterruptedException
     */
    protected MatrixCursor getMessages(final String[] projection) throws InterruptedException {
      final BlockingQueue<List<MessageInfoHolder>> queue =
          new SynchronousQueue<List<MessageInfoHolder>>();

      // new code for integrated inbox, only execute this once as it will be processed afterwards
      // via the listener
      final SearchAccount integratedInboxAccount =
          SearchAccount.createUnifiedInboxAccount(getContext());
      final MessagingController msgController = MessagingController.getInstance(K9.app);

      msgController.searchLocalMessages(
          integratedInboxAccount, null, new MesssageInfoHolderRetrieverListener(queue));

      final List<MessageInfoHolder> holders = queue.take();

      // TODO add sort order parameter
      Collections.sort(
          holders,
          new MessageList.ReverseComparator<MessageInfoHolder>(new MessageList.DateComparator()));

      final String[] projectionToUse;
      if (projection == null) {
        projectionToUse = DEFAULT_MESSAGE_PROJECTION;
      } else {
        projectionToUse = projection;
      }

      final LinkedHashMap<String, FieldExtractor<MessageInfoHolder, ?>> extractors =
          resolveMessageExtractors(projectionToUse, holders.size());
      final int fieldCount = extractors.size();

      final String[] actualProjection = extractors.keySet().toArray(new String[fieldCount]);
      final MatrixCursor cursor = new MatrixCursor(actualProjection);

      for (final MessageInfoHolder holder : holders) {
        final Object[] o = new Object[fieldCount];

        int i = 0;
        for (final FieldExtractor<MessageInfoHolder, ?> extractor : extractors.values()) {
          o[i] = extractor.getField(holder);
          i += 1;
        }

        cursor.addRow(o);
      }

      return cursor;
    }
Exemplo n.º 26
0
 public static MatrixCursor getCursorForSingleTagMetadata() {
   String[] data = {TAG_ID, TAG_ID_NAME, TAG_NAME, TAG_CATEGORY, "2", "", "-3355444", ""};
   String[] columns = {
     "_id",
     "tag_id",
     "tag_name",
     "tag_category",
     "tag_order_in_category",
     "tag_abstract",
     "tag_color",
     "tag_photo_url"
   };
   MatrixCursor matrixCursor = new MatrixCursor(columns);
   matrixCursor.addRow(data);
   return matrixCursor;
 }
Exemplo n.º 27
0
  /**
   * Note: tag id is no longer a real column, so we pass in a UID generated from the tag string.
   *
   * @return two-column cursor: tag id (string) and tag name
   */
  public Cursor getTags() {

    Tag[] tags =
        TagService.getInstance().getGroupedTags(TagService.GROUPED_TAGS_BY_SIZE, Criterion.all);

    MatrixCursor ret = new MatrixCursor(TAGS_FIELD_LIST);

    for (int i = 0; i < tags.length; i++) {
      Object[] values = new Object[2];
      values[0] = tagNameToLong(tags[i].tag);
      values[1] = tags[i].tag;

      ret.addRow(values);
    }

    return ret;
  }
  @Override
  public Cursor query(
      Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    /*
     * TODO: You need to implement this method. Note that you need to return a Cursor object
     * with the right format. If the formatting is not correct, then it is not going to work.
     *
     * If you use SQLite, whatever is returned from SQLite is a Cursor object. However, you
     * still need to be careful because the formatting might still be incorrect.
     *
     * If you use a file storage option, then it is your job to build a Cursor * object. I
     * recommend building a MatrixCursor described at:
     * http://developer.android.com/reference/android/database/MatrixCursor.html
     */

    /* Help taken from http://developer.android.com/guide/topics/providers/content-provider-creating.html
     * http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
     */

    FileInputStream fis;
    String filename = selection;
    String[] columnNames = {"key", "value"};
    MatrixCursor cursor = new MatrixCursor(columnNames, 0);
    try {
      fis = getContext().openFileInput(filename);
      if (fis != null) {
        BufferedReader br = new BufferedReader(new InputStreamReader(fis));
        String val;
        String message = null;
        while ((val = br.readLine()) != null) {
          if (message == null) message = val;
          else message = message + val;
        }
        cursor.addRow(new String[] {selection, message});
        fis.close();
      } else {
        Log.e("query", "No such key value found : " + selection);
        fis.close();
      }

    } catch (Exception ex) {
      Log.e("query", "Error reading file");
    }
    Log.v("query", selection);
    return cursor;
  }
 private MatrixCursor getMatrixCursor(String id, String[] projection, ContentValues values) {
   Cursor c = get(id);
   if (c != null) {
     // Make a new MatrixCursor with the requested columns
     MatrixCursor mc = new MatrixCursorWithCachedColumns(projection, 1);
     if (c.getCount() == 0) {
       return mc;
     }
     Object[] row = new Object[projection.length];
     if (values != null) {
       // Make a copy; we don't want to change the original
       values = new ContentValues(values);
     }
     int i = 0;
     for (String column : projection) {
       int columnIndex = c.getColumnIndex(column);
       if (columnIndex < 0) {
         mStats.mProjectionMissCount++;
         return null;
       } else {
         String value;
         if (values != null && values.containsKey(column)) {
           Object val = values.get(column);
           if (val instanceof Boolean) {
             value = (val == Boolean.TRUE) ? "1" : "0";
           } else {
             value = values.getAsString(column);
           }
           values.remove(column);
         } else {
           value = c.getString(columnIndex);
         }
         row[i++] = value;
       }
     }
     if (values != null && values.size() != 0) {
       return null;
     }
     mc.addRow(row);
     mStats.mHitCount++;
     return mc;
   }
   mStats.mMissCount++;
   return null;
 }
  @Override
  public Cursor query(
      Uri uri, String[] projectionIn, String selection, String[] selectionArgs, String sortOrder) {
    Log.d(TAG, "query(" + uri + ")");

    MatrixCursor cursor = new MatrixCursor(COLUMNS);
    for (int i = 0; i < 100; i++) {
      cursor.addRow(
          new Object[] {
            i,
            "Spam suggestion " + i,
            "This is spam",
            Intent.ACTION_VIEW,
            "content://com.android.quicksearchbox.spammy/spam/" + i
          });
    }
    return cursor;
  }