@Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
      case REQUEST_CODE_PUBLIC_KEYS:
        {
          if (resultCode == Activity.RESULT_OK) {
            Bundle bundle = data.getExtras();
            setEncryptionKeyIds(
                bundle.getLongArray(SelectPublicKeyActivity.RESULT_EXTRA_MASTER_KEY_IDS));
          }
          break;
        }

      case REQUEST_CODE_SECRET_KEYS:
        {
          if (resultCode == Activity.RESULT_OK) {
            Uri uriMasterKey = data.getData();
            setSignatureKeyId(Long.valueOf(uriMasterKey.getLastPathSegment()));
          } else {
            setSignatureKeyId(Constants.key.none);
          }
          break;
        }

      default:
        {
          super.onActivityResult(requestCode, resultCode, data);

          break;
        }
    }
  }
 private int getResourceForMedia(Resources resources, Uri uri) {
   int drawable = 0;
   if (uri.getScheme().equals("file")) {
     if (uri.getLastPathSegment().endsWith("3gp")) {
       drawable = R.drawable.media_film;
     } else if (uri.getLastPathSegment().endsWith("jpg")) {
       drawable = R.drawable.media_camera;
     } else if (uri.getLastPathSegment().endsWith("txt")) {
       drawable = R.drawable.media_notepad;
     }
   } else if (uri.getScheme().equals("content")) {
     if (uri.getAuthority().equals(GPStracking.AUTHORITY + ".string")) {
       drawable = R.drawable.media_mark;
     } else if (uri.getAuthority().equals("media")) {
       drawable = R.drawable.media_speech;
     }
   }
   synchronized (sBitmapCache) {
     if (sBitmapCache.get(drawable) == null) {
       Bitmap bitmap = BitmapFactory.decodeResource(resources, drawable);
       sBitmapCache.put(drawable, bitmap);
     }
   }
   return drawable;
 }
Пример #3
0
  @Override
  public int delete(Uri uri, String selection, String[] selectionArgs) {
    Log.d(TAG, "delete() uri " + uri);
    int uriType = sURIMatcher.match(uri);
    int rowsDeleted = 0;
    String id;
    SQLiteDatabase sqlDB = database.getWritableDatabase();

    switch (uriType) {
      case EVENTS:
        rowsDeleted = sqlDB.delete(TABLE_EVENTS, selection, selectionArgs);
        break;
      case RECORDS:
        rowsDeleted = sqlDB.delete(TABLE_RECORDS, selection, selectionArgs);
        break;
      case EMPLOYEES:
        rowsDeleted = sqlDB.delete(TABLE_EMPLOYEES, selection, selectionArgs);
        break;
      case EVENT_ID:
        id = uri.getLastPathSegment();
        rowsDeleted =
            sqlDB.delete(TABLE_EVENTS, EventManager.EventQuery.SELECTION_ID, new String[] {id});
        break;
      case EMPLOYEE_ID:
        id = uri.getLastPathSegment();
        rowsDeleted =
            sqlDB.delete(TABLE_EMPLOYEES, EventManager.EventQuery.SELECTION_ID, new String[] {id});
        break;
      default:
        break;
    }
    getContext().getContentResolver().notifyChange(uri, null);
    Log.d(TAG, "delete() rowsDeleted " + rowsDeleted);
    return rowsDeleted;
  }
  @Override
  public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {

    String LOG_TAG = CLASS_NAME + " ";

    Log.d(LOG_TAG, "Called with uri: '" + uri + "'." + uri.getLastPathSegment());

    // Check incoming Uri against the matcher
    switch (uriMatcher.match(uri)) {

        // If it returns 1 - then it matches the Uri defined in onCreate
      case 1:

        // The desired file name is specified by the last segment of the
        // path
        //
        // Take this and build the path to the file
        String fileLocation =
            getContext().getCacheDir() + File.separator + uri.getLastPathSegment();

        // Create & return a ParcelFileDescriptor pointing to the file
        // Note: I don't care what mode they ask for - they're only getting
        // read only
        ParcelFileDescriptor pfd =
            ParcelFileDescriptor.open(new File(fileLocation), ParcelFileDescriptor.MODE_READ_ONLY);
        return pfd;

        // Otherwise unrecognised Uri
      default:
        Log.v(LOG_TAG, "Unsupported uri: '" + uri + "'.");
        throw new FileNotFoundException("Unsupported uri: " + uri.toString());
    }
  }
 private Integer getResourceForMedia(Resources resources, Uri uri) {
   int drawable = 0;
   if (uri.getScheme().equals("file")) {
     if (uri.getLastPathSegment().endsWith("3gp")) {
       drawable = R.drawable.media_film;
     } else if (uri.getLastPathSegment().endsWith("jpg")) {
       drawable = R.drawable.media_camera;
     } else if (uri.getLastPathSegment().endsWith("txt")) {
       drawable = R.drawable.media_notepad;
     }
   } else if (uri.getScheme().equals("content")) {
     if (uri.getAuthority().equals(GPStracking.AUTHORITY + ".string")) {
       drawable = R.drawable.media_mark;
     } else if (uri.getAuthority().equals("media")) {
       drawable = R.drawable.media_speech;
     }
   }
   Bitmap bitmap = null;
   Integer bitmapKey = new Integer(drawable);
   synchronized (sBitmapCache) {
     if (!sBitmapCache.containsKey(bitmapKey)) {
       bitmap = BitmapFactory.decodeResource(resources, drawable);
       sBitmapCache.put(bitmapKey, bitmap);
     }
     bitmap = sBitmapCache.get(bitmapKey);
   }
   return bitmapKey;
 }
Пример #6
0
  @Override
  public final synchronized int delete(
      final Uri uri, final String selection, final String[] selectionArgs) {
    int affectedRows = 0;

    int match = URI_MATCHER.match(uri);
    if (match == KEY) {
      SQLiteDatabase database = fOpenHelper.getWritableDatabase();
      affectedRows = database.delete(KEY_TABLE, selection, selectionArgs);
    } else if (match == KEY_ID) {
      SQLiteDatabase database = fOpenHelper.getWritableDatabase();
      affectedRows =
          database.delete(KEY_TABLE, BaseColumns._ID + " = " + uri.getLastPathSegment(), null);
    } else if (match == LAYOUT) {
      SQLiteDatabase database = fOpenHelper.getWritableDatabase();
      affectedRows = database.delete(LAYOUT_TABLE, selection, selectionArgs);
    } else if (match == LAYOUT_ID) {
      SQLiteDatabase database = fOpenHelper.getWritableDatabase();
      affectedRows =
          database.delete(LAYOUT_TABLE, BaseColumns._ID + " = " + uri.getLastPathSegment(), null);
    } else if (match == PC) {
      SQLiteDatabase database = fOpenHelper.getWritableDatabase();
      affectedRows = database.delete(PC_TABLE, selection, selectionArgs);
    } else if (match == PC_ID) {
      SQLiteDatabase database = fOpenHelper.getWritableDatabase();
      affectedRows =
          database.delete(PC_TABLE, BaseColumns._ID + " = " + uri.getLastPathSegment(), null);
    }

    return (affectedRows);
  }
  protected void initView() {
    mHandler = new Handler(this);
    mDialog = new LoadingDialog(this);
    mFragmentManager = getSupportFragmentManager();
    getSupportActionBar().setTitle(R.string.main_name);
    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm); // 获取屏幕信息
    indicatorWidth = dm.widthPixels / 4; // 指示器宽度为屏幕宽度的4/1

    mMainShow = (LinearLayout) findViewById(R.id.main_show);
    mMainConversationLiner = (RelativeLayout) findViewById(R.id.main_conversation_liner);
    mMainGroupLiner = (RelativeLayout) findViewById(R.id.main_group_liner);
    mMainChatroomLiner = (RelativeLayout) findViewById(R.id.main_chatroom_liner);
    mMainCustomerLiner = (RelativeLayout) findViewById(R.id.main_customer_liner);
    mMainConversationTv = (TextView) findViewById(R.id.main_conversation_tv);
    mMainGroupTv = (TextView) findViewById(R.id.main_group_tv);
    mMainChatroomTv = (TextView) findViewById(R.id.main_chatroom_tv);
    mMainCustomerTv = (TextView) findViewById(R.id.main_customer_tv);
    mViewPager = (ViewPager) findViewById(R.id.main_viewpager);
    mMainSelectImg = (ImageView) findViewById(R.id.main_switch_img);
    mUnreadNumView = (TextView) findViewById(R.id.de_num);
    mCustomerNoRead = (TextView) findViewById(R.id.customer_noread);

    ViewGroup.LayoutParams cursor_Params = mMainSelectImg.getLayoutParams();
    cursor_Params.width = indicatorWidth; // 初始化滑动下标的宽
    mMainSelectImg.setLayoutParams(cursor_Params);
    // 获取布局填充器
    mInflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);

    if (getIntent() != null) {
      if (getIntent().hasExtra("PUSH_TOKEN") && getIntent().hasExtra("PUSH_INTENT")) {

        Uri uri = getIntent().getParcelableExtra("PUSH_INTENT");
        String token = getIntent().getStringExtra("PUSH_TOKEN").toString();
        String pathSegments;
        String conversationType = null;
        String targetId = null;

        if (uri.getPathSegments().get(0).equals("conversation")) {
          pathSegments = uri.getPathSegments().get(0);
          conversationType =
              Conversation.ConversationType.valueOf(
                      uri.getLastPathSegment().toUpperCase(Locale.getDefault()))
                  .toString();
          targetId = uri.getQueryParameter("targetId").toString();
        } else {
          pathSegments = uri.getLastPathSegment();
        }
        reconnect(token, pathSegments, conversationType, targetId);

        if (DemoContext.getInstance() != null) {
          mGetMyGroupsRequest =
              DemoContext.getInstance().getDemoApi().getMyGroups(MainActivity.this);
        }
      }
    }
  }
  @Override
  public Cursor query(
      Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    String table = null;
    final int code = uriMatcher.match(uri);

    if (code == CONTACT || code == CONTACT_ID) {
      table = ContactTable.TABLE_NAME;
      if (sortOrder == null) {
        sortOrder = ContactTable.DEFAULT_SORT_ORDER;
      }

      if (code == CONTACT_ID) {
        selection = ContactTable._ID + "=?";
        selectionArgs = new String[] {uri.getLastPathSegment()};
      }
    } else if (code == CONTACT_REQUEST || code == CONTACT_REQUEST_ID) {
      table = ContactRequestTable.TABLE_NAME;
      if (sortOrder == null) {
        sortOrder = ContactRequestTable.DEFAULT_SORT_ORDER;
      }

      if (code == CONTACT_REQUEST_ID) {
        selection = ContactRequestTable._ID + "=?";
        selectionArgs = new String[] {uri.getLastPathSegment()};
      }
    } else if (code == CHAT_MESSAGE || code == CHAT_MESSAGE_ID) {
      table = ChatMessageTable.TABLE_NAME;
      if (sortOrder == null) {
        sortOrder = ChatMessageTable.DEFAULT_SORT_ORDER;
      }

      if (code == CHAT_MESSAGE_ID) {
        selection = ChatMessageTable._ID + "=?";
        selectionArgs = new String[] {uri.getLastPathSegment()};
      }
    } else if (code == CONVERSATION || code == CONVERSATION_ID) {
      table = ConversationTable.TABLE_NAME;
      if (sortOrder == null) {
        sortOrder = ConversationTable.DEFAULT_SORT_ORDER;
      }

      if (code == CONVERSATION_ID) {
        selection = ConversationTable._ID + "=?";
        selectionArgs = new String[] {uri.getLastPathSegment()};
      }
    } else {
      throw new IllegalArgumentException("Unknown URI " + uri);
    }

    SQLiteDatabase db = dbHelper.getReadableDatabase();
    Cursor c = db.query(table, projection, selection, selectionArgs, null, null, sortOrder);
    c.setNotificationUri(getContext().getContentResolver(), uri);

    return c;
  }
  @Nullable
  @Override
  public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {

    Log.d(this, "openFile:" + uri.getLastPathSegment());

    File dir = new File(Environment.getExternalStorageDirectory().getAbsoluteFile(), "/radar");
    return ParcelFileDescriptor.open(
        new File(dir, uri.getLastPathSegment()), ParcelFileDescriptor.MODE_READ_ONLY);
  }
  @Override
  public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
    // TODO Auto-generated method stub
    int count;
    try {
      if (URI_MATCHER.match(uri) == BT_PROFILES_ID) {
        Long id = Long.parseLong(uri.getLastPathSegment());
        count = db.update(Table_BlueTooth, values, "_id=" + id, null);

        getContext().getContentResolver().notifyChange(uri, null);

        return count;
      } else if (URI_MATCHER.match(uri) == BT_PROFILES) {
        count = db.update(Table_BlueTooth, values, selection, null);

        getContext().getContentResolver().notifyChange(uri, null);

        return count;
      }
      if (URI_MATCHER.match(uri) == WLAN_PROFILES_ID) {
        Long id = Long.parseLong(uri.getLastPathSegment());
        count = db.update(Table_Wlan, values, "_id=" + id, null);

        getContext().getContentResolver().notifyChange(uri, null);

        return count;
      } else if (URI_MATCHER.match(uri) == WLAN_PROFILES) {
        count = db.update(Table_Wlan, values, selection, null);

        getContext().getContentResolver().notifyChange(uri, null);

        return count;
      }
      if (URI_MATCHER.match(uri) == USER_PROFILES_ID) {
        Long id = Long.parseLong(uri.getLastPathSegment());
        count = db.update(Table_User, values, "_id=" + id, null);

        getContext().getContentResolver().notifyChange(uri, null);

        return count;
      } else if (URI_MATCHER.match(uri) == USER_PROFILES) {
        count = db.update(Table_User, values, selection, null);

        getContext().getContentResolver().notifyChange(uri, null);

        return count;
      } else {
        throw new IllegalArgumentException();
      }
    } catch (SQLiteException e) {
      return 0;
    }
  }
Пример #11
0
    /**
     * Get CacheEntry list for given phone URIs. This method will do single one query to get
     * expected contacts from provider. Be sure passed in URIs are not null and contains only valid
     * URIs.
     */
    public List<Contact> getContactInfoForPhoneUris(Parcelable[] uris) {
      if (uris.length == 0) {
        return null;
      }
      StringBuilder idSetBuilder = new StringBuilder();
      boolean first = true;
      for (Parcelable p : uris) {
        Uri uri = (Uri) p;
        if ("content".equals(uri.getScheme())) {
          if (first) {
            first = false;
            idSetBuilder.append(uri.getLastPathSegment());
          } else {
            idSetBuilder.append(',').append(uri.getLastPathSegment());
          }
        }
      }
      // Check whether there is content URI.
      if (first) return null;
      Cursor cursor = null;
      if (idSetBuilder.length() > 0) {
        final String whereClause = Phone._ID + " IN (" + idSetBuilder.toString() + ")";
        cursor =
            mContext
                .getContentResolver()
                .query(PHONES_WITH_PRESENCE_URI, CALLER_ID_PROJECTION, whereClause, null, null);
      }

      if (cursor == null) {
        return null;
      }

      List<Contact> entries = new ArrayList<Contact>();

      try {
        while (cursor.moveToNext()) {
          Contact entry =
              new Contact(
                  cursor.getString(PHONE_NUMBER_COLUMN), cursor.getString(CONTACT_NAME_COLUMN));
          fillPhoneTypeContact(entry, cursor);
          ArrayList<Contact> value = new ArrayList<Contact>();
          value.add(entry);
          // Put the result in the cache.
          mContactsHash.put(key(entry.mNumber, sStaticKeyBuffer), value);
          entries.add(entry);
        }
      } finally {
        cursor.close();
      }
      return entries;
    }
Пример #12
0
  @Override
  public Cursor query(
      @NonNull Uri uri,
      String[] projection,
      String selection,
      String[] selectionArgs,
      String sortOrder) {
    final SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

    switch (mMatcher.match(uri)) {
      case MAPS:
        queryBuilder.setTables(Database.Maps.TABLE_NAME);
        break;
      case MAPS_ID:
        queryBuilder.setTables(Database.Maps.TABLE_NAME);
        queryBuilder.appendWhere(Database.Maps.ID + "=" + uri.getLastPathSegment());
        break;
      case META:
        queryBuilder.setTables(Database.Meta.TABLE_NAME);
        break;
      case META_ID:
        queryBuilder.setTables(Database.Meta.TABLE_NAME);
        queryBuilder.appendWhere(Database.Meta.ID + "=" + uri.getLastPathSegment());
        break;
      case READINGS:
        queryBuilder.setTables(Database.Readings.TABLE_NAME);
        break;
      case READINGS_ID:
        queryBuilder.setTables(Database.Readings.TABLE_NAME);
        queryBuilder.appendWhere(Database.Readings.ID + "=" + uri.getLastPathSegment());
        break;
      case PROBES:
        queryBuilder.setTables(Database.Probes.TABLE_NAME);
        break;
      case PROBES_ID:
        queryBuilder.setTables(Database.Probes.TABLE_NAME);
        queryBuilder.appendWhere(Database.Probes.ID + "=" + uri.getLastPathSegment());
        break;
      default:
        throw new IllegalArgumentException("Unmatchable URI " + uri);
    }

    final Cursor cursor =
        queryBuilder.query(
            mDb.getReadableDatabase(), projection, selection, selectionArgs, null, null, sortOrder);
    cursor.setNotificationUri(getContext().getContentResolver(), uri);

    return cursor;
  }
 @Override
 public Cursor query(
     Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
   // TODO Auto-generated method stub
   try {
     if (URI_MATCHER.match(uri) == BT_PROFILES || URI_MATCHER.match(uri) == BT_PROFILES_ID) {
       SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
       qb.setTables(Table_BlueTooth);
       if (URI_MATCHER.match(uri) == BT_PROFILES_ID) {
         qb.appendWhere("_id=" + uri.getLastPathSegment());
       }
       Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);
       if (null != c) {
         c.setNotificationUri(getContext().getContentResolver(), uri);
       }
       return c;
     }
     if (URI_MATCHER.match(uri) == WLAN_PROFILES || URI_MATCHER.match(uri) == WLAN_PROFILES_ID) {
       SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
       qb.setTables(Table_Wlan);
       if (URI_MATCHER.match(uri) == WLAN_PROFILES_ID) {
         qb.appendWhere("_id=" + uri.getLastPathSegment());
       }
       Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);
       if (null != c) {
         c.setNotificationUri(getContext().getContentResolver(), uri);
       }
       return c;
     }
     if (URI_MATCHER.match(uri) == USER_PROFILES || URI_MATCHER.match(uri) == USER_PROFILES_ID) {
       SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
       qb.setTables(Table_User);
       if (URI_MATCHER.match(uri) == USER_PROFILES_ID) {
         qb.appendWhere("_id=" + uri.getLastPathSegment());
       }
       Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);
       if (null != c) {
         c.setNotificationUri(getContext().getContentResolver(), uri);
       }
       return c;
     } else {
       throw new IllegalArgumentException();
     }
   } catch (SQLiteException e) {
     return null;
   } catch (Exception e) {
     return null;
   }
 }
Пример #14
0
  @Override
  public Cursor query(
      Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    Cursor result = null;
    if (URI_ITEMS.equals(uri)) {
      result =
          DatabaseHandler.getInstance(getContext())
              .getReadableDatabase()
              .query(Item.TABLE_NAME, Item.FIELDS, null, null, null, null, null, null);
      result.setNotificationUri(getContext().getContentResolver(), URI_ITEMS);
    } else if (uri.toString().startsWith(ITEM_BASE)) {
      final long id = Long.parseLong(uri.getLastPathSegment());
      result =
          DatabaseHandler.getInstance(getContext())
              .getReadableDatabase()
              .query(
                  Item.TABLE_NAME,
                  Item.FIELDS,
                  Item._ID + " IS ?",
                  new String[] {String.valueOf(id)},
                  null,
                  null,
                  null,
                  null);
      result.setNotificationUri(getContext().getContentResolver(), URI_ITEMS);
    } else {
      throw new UnsupportedOperationException("Not yet implemented");
    }

    return result;
  }
  @Override
  public Cursor query(
      Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {

    // Uisng SQLiteQueryBuilder instead of query() method
    SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

    // check if the caller has requested a column which does not exists
    checkColumns(projection);

    // Set the table
    queryBuilder.setTables(RescueTable.RESCUE_TABLE);

    int uriType = sURIMatcher.match(uri);
    switch (uriType) {
      case URI_MATCHER:
        break;
      case URI_MATCHER_ID:
        // adding the ID to the original query
        queryBuilder.appendWhere(RescueTable.COLUMN_ID + "=" + uri.getLastPathSegment());

        break;
      default:
        throw new IllegalArgumentException("Unknown URI: " + uri);
    }

    SQLiteDatabase db = database.getWritableDatabase();
    Cursor cursor =
        queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder);
    // make sure that potential listeners are getting notified
    cursor.setNotificationUri(getContext().getContentResolver(), uri);

    return cursor;
  }
  @Override
  public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {

    int uriType = sURIMatcher.match(uri);
    SQLiteDatabase sqlDB = database.getWritableDatabase();
    int rowsUpdated = 0;
    switch (uriType) {
      case URI_MATCHER:
        rowsUpdated = sqlDB.update(RescueTable.RESCUE_TABLE, values, selection, selectionArgs);
        break;
      case URI_MATCHER_ID:
        String id = uri.getLastPathSegment();
        if (TextUtils.isEmpty(selection)) {
          rowsUpdated =
              sqlDB.update(
                  RescueTable.RESCUE_TABLE, values, RescueTable.COLUMN_ID + "=" + id, null);
        } else {
          rowsUpdated =
              sqlDB.update(
                  RescueTable.RESCUE_TABLE,
                  values,
                  RescueTable.COLUMN_ID + "=" + id + " and " + selection,
                  selectionArgs);
        }
        break;
      default:
        throw new IllegalArgumentException("Unknown URI: " + uri);
    }
    getContext().getContentResolver().notifyChange(uri, null);
    return rowsUpdated;
  }
 private void handleSendDraftIntent(Intent intent) {
   final Uri uri = intent.getData();
   if (uri == null) return;
   final long draftId = ParseUtils.parseLong(uri.getLastPathSegment(), -1);
   if (draftId == -1) return;
   final Expression where = Expression.equals(Drafts._ID, draftId);
   final Cursor c =
       getContentResolver().query(Drafts.CONTENT_URI, Drafts.COLUMNS, where.getSQL(), null, null);
   final DraftItem.CursorIndices i = new DraftItem.CursorIndices(c);
   final DraftItem item;
   try {
     if (!c.moveToFirst()) return;
     item = new DraftItem(c, i);
   } finally {
     c.close();
   }
   if (item.action_type == Drafts.ACTION_UPDATE_STATUS || item.action_type <= 0) {
     updateStatuses(new ParcelableStatusUpdate(this, item));
   } else if (item.action_type == Drafts.ACTION_SEND_DIRECT_MESSAGE) {
     final long recipientId = item.action_extras.optLong(EXTRA_RECIPIENT_ID);
     if (item.account_ids == null || item.account_ids.length <= 0 || recipientId <= 0) {
       return;
     }
     final long accountId = item.account_ids[0];
     final String imageUri =
         item.media != null && item.media.length > 0 ? item.media[0].uri : null;
     sendMessage(accountId, recipientId, item.text, imageUri);
   }
 }
  // Atualiza uma nota
  @Override
  public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
    int uriTipo = sURIMatcher.match(uri);
    SQLiteDatabase sqlDB = notasDB.getWritableDatabase();

    int totalEditadas = 0;
    switch (uriTipo) {
      case NOTAS:
        totalEditadas = sqlDB.update(Nota.TABELA, values, selection, selectionArgs);
        break;
      case NOTAS_ID:
        String id = uri.getLastPathSegment();
        if (TextUtils.isEmpty(selection)) {
          totalEditadas = sqlDB.update(Nota.TABELA, values, "_id=" + id, selectionArgs);
        } else {
          totalEditadas =
              sqlDB.update(Nota.TABELA, values, "_id=" + id + " and " + selection, selectionArgs);
        }
        break;
      default:
        throw new IllegalArgumentException("URI desconhecida: " + uri);
    }
    // Notifica as mudanças
    getContext().getContentResolver().notifyChange(uri, null);

    // Retorna o número de notas que foram editadas
    return totalEditadas;
  }
Пример #19
0
  @Override
  public Cursor query(
      Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();
    sqlBuilder.setTables(EVENTS_TABLE);

    if (uriMatcher.match(uri) == 1) {
      sqlBuilder.setProjectionMap(mMap);
    } else if (uriMatcher.match(uri) == 2) {
      sqlBuilder.setProjectionMap(mMap);
      sqlBuilder.appendWhere(ID + "=?");
      selectionArgs =
          DatabaseUtils.appendSelectionArgs(selectionArgs, new String[] {uri.getLastPathSegment()});
    } else if (uriMatcher.match(uri) == 3) {
      sqlBuilder.setProjectionMap(mMap);
      sqlBuilder.appendWhere(START + ">=? OR ");
      sqlBuilder.appendWhere(END + "<=?");
      List<String> list = uri.getPathSegments();
      String start = list.get(1);
      String end = list.get(2);
      selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs, new String[] {start, end});
    }
    if (sortOrder == null || sortOrder == "") sortOrder = START + " COLLATE LOCALIZED ASC";
    Cursor c = sqlBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder);
    c.setNotificationUri(getContext().getContentResolver(), uri);
    return c;
  }
Пример #20
0
  @Override
  public int delete(Uri uri, String selection, String[] selectionArgs) {
    SelectionBuilder builder = new SelectionBuilder();
    final SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
    final int match = sUriMatcher.match(uri);
    int count;
    switch (match) {
      case ROUTE_EMOTES:
        count =
            builder
                .table(EmotesContract.Emote.TABLE_NAME)
                .where(selection, selectionArgs)
                .delete(db);
        break;
      case ROUTE_EMOTES_ID:
        String id = uri.getLastPathSegment();
        count =
            builder
                .table(EmotesContract.Emote.TABLE_NAME)
                .where(EmotesContract.Emote._ID + "=?", id)
                .where(selection, selectionArgs)
                .delete(db);
        break;
      default:
        throw new UnsupportedOperationException("Unknown uri: " + uri);
    }

    // Send broadcast to registered ContentObservers, to refresh UI.
    Context ctx = getContext();
    assert ctx != null;
    ctx.getContentResolver().notifyChange(uri, null, false);

    return count;
  }
  @Override
  public Cursor query(
      Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    SQLiteDatabase db = helper.getReadableDatabase();
    SQLiteQueryBuilder builder = new SQLiteQueryBuilder();

    switch (sURIMatcher.match(uri)) {
      case PRODUCTS_LIST:
        builder.setTables(ProductsTable.TABLE_PRODUCTS);
        if (TextUtils.isEmpty(sortOrder)) {
          sortOrder = ProductsTable.SORT_ORDER_DEFAULT;
        }
        break;
      case PRODUCTS_ID:
        builder.setTables(ProductsTable.TABLE_PRODUCTS);
        builder.appendWhere(ProductsTable.COLUMN_ID + " = " + uri.getLastPathSegment());
        break;

      default:
        throw new IllegalArgumentException("Unsupported URI: " + uri);
    }

    Cursor cursor = builder.query(db, projection, selection, selectionArgs, null, null, sortOrder);
    cursor.setNotificationUri(getContext().getContentResolver(), uri);

    return cursor;
  }
  @Override
  public int delete(Uri uri, String selection, String[] selectionArgs) {
    SQLiteDatabase db = helper.getWritableDatabase();
    int delCount = 0;

    String idStr = "";
    String where = "";
    switch (sURIMatcher.match(uri)) {
      case PRODUCTS_LIST:
        delCount = db.delete(ProductsTable.TABLE_PRODUCTS, selection, selectionArgs);
        break;
      case PRODUCTS_ID:
        idStr = uri.getLastPathSegment();
        where = ProductsTable.COLUMN_ID + " = " + idStr;
        if (!TextUtils.isEmpty(selection)) {
          where += " AND " + selection;
        }
        delCount = db.delete(ProductsTable.TABLE_PRODUCTS, where, selectionArgs);
        break;

      default:
        throw new IllegalArgumentException("Unsupported URI: " + uri);
    }

    getContext().getContentResolver().notifyChange(uri, null);

    return delCount;
  }
Пример #23
0
 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
   boolean handled = false;
   Intent intent;
   switch (item.getItemId()) {
     case MENU_GRAPHTYPE:
       showDialog(DIALOG_GRAPHTYPE);
       handled = true;
       break;
     case MENU_TRACKLIST:
       intent = new Intent(this, TrackList.class);
       intent.putExtra(Tracks._ID, mTrackUri.getLastPathSegment());
       startActivityForResult(intent, MENU_TRACKLIST);
       break;
     case MENU_SHARE:
       intent = new Intent(Intent.ACTION_RUN);
       intent.setDataAndType(mTrackUri, Tracks.CONTENT_ITEM_TYPE);
       intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
       Bitmap bm = mViewFlipper.getDrawingCache();
       Uri screenStreamUri = ShareTrack.storeScreenBitmap(bm);
       intent.putExtra(Intent.EXTRA_STREAM, screenStreamUri);
       startActivityForResult(
           Intent.createChooser(intent, getString(R.string.share_track)), MENU_SHARE);
       handled = true;
       break;
     default:
       handled = super.onOptionsItemSelected(item);
   }
   return handled;
 }
Пример #24
0
  @Override
  public int delete(Uri uri, String where, String[] whereArgs) {
    switch (uriMatcher.match(uri)) {
      case PODCASTS:
        break;
      case PODCAST_ID:
        String extraWhere = COLUMN_ID + " = " + uri.getLastPathSegment();
        if (where != null) where = extraWhere + " AND " + where;
        else where = extraWhere;
        break;
      default:
        throw new IllegalArgumentException("Illegal URI for delete");
    }

    // find out what we're deleting and delete downloaded files
    SQLiteDatabase db = _dbAdapter.getWritableDatabase();
    String[] columns = new String[] {COLUMN_ID};
    String podcastsWhere = "queuePosition IS NOT NULL";
    if (where != null) podcastsWhere = where + " AND " + podcastsWhere;
    Cursor c = db.query("podcasts", columns, podcastsWhere, whereArgs, null, null, null);
    while (c.moveToNext()) {
      updateQueuePosition(c.getLong(0), null);
      deleteDownload(getContext(), c.getLong(0));
    }
    c.close();

    int count = db.delete("podcasts", where, whereArgs);
    if (!uri.equals(URI)) getContext().getContentResolver().notifyChange(URI, null);
    getContext().getContentResolver().notifyChange(uri, null);
    return count;
  }
Пример #25
0
  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK || resultCode == Activity.RESULT_CANCELED) {
      switch (requestCode) {
        case ACTION_REQUEST_FEATHER:
          Uri mImageUri = data.getData();
          Boolean mChanged = data.getBooleanExtra("EXTRA_OUT_BITMAP_CHANGED", false);

          try {
            JSONObject returnVal = new JSONObject();
            // returnVal.put("changed", mChanged); // doesn't ever seem to be anything other than
            // false

            if (mImageUri != null) {
              returnVal.put("src", mImageUri.toString());
              returnVal.put("name", mImageUri.getLastPathSegment());
            }

            this.callbackContext.success(returnVal);
          } catch (JSONException ex) {
            Log.e(LOG_TAG, ex.toString());
            this.callbackContext.error(ex.getMessage());
          }
          break;
      }
    }
  }
 @Override
 public Cursor query(
     Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
   Log.d(TAG, "Got query for " + uri);
   if (!TextUtils.isEmpty(selection)) {
     throw new IllegalArgumentException("selection not allowed for " + uri);
   }
   if (selectionArgs != null && selectionArgs.length != 0) {
     throw new IllegalArgumentException("selectionArgs not allowed for " + uri);
   }
   if (!TextUtils.isEmpty(sortOrder)) {
     throw new IllegalArgumentException("sortOrder not allowed for " + uri);
   }
   switch (uriMatcher.match(uri)) {
     case SEARCH_SUGGEST:
       String query = null;
       if (uri.getPathSegments().size() > 1) {
         query = uri.getLastPathSegment();
       }
       Log.d(TAG, "Got suggestions query for " + query);
       return getSuggestions(query);
     default:
       throw new IllegalArgumentException("Unknown URL " + uri);
   }
 }
  @Override
  public Cursor query(
      Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    // Uisng SQLiteQueryBuilder instead of query() method
    SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

    // Check if the caller has requested a column which does not exists
    checkColumns(projection);

    // Set the table
    queryBuilder.setTables(DontForgetMomDbInformation.Trip.CONTENT_PROVIDER_TABLE_NAME);

    int uriType = sURIMatcher.match(uri);
    switch (uriType) {
      case TRIPS:
        break;
      case TRIP_ID:
        // Adding the ID to the original query
        queryBuilder.appendWhere(
            DontForgetMomDbInformation.Trip._ID + "=" + uri.getLastPathSegment());
        break;
      default:
        throw new IllegalArgumentException("Unknown URI: " + uri);
    }

    SQLiteDatabase db = dbHelper.getWritableDatabase();
    Cursor cursor =
        queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder);
    // Make sure that potential listeners are getting notified
    cursor.setNotificationUri(getContext().getContentResolver(), uri);

    return cursor;
  }
Пример #28
0
  public String uri2string(Uri intent_uri)
      throws FileNotFoundException, MalformedURLException, IOException {

    if (intent_uri.toString().startsWith("/"))
      return FileHelper.file2String(new File(intent_uri.toString()));

    InputStream in;

    if (intent_uri.toString().startsWith("content://"))
      in = getContentResolver().openInputStream(intent_uri);
    else in = new BufferedInputStream(new URL("" + intent_uri).openStream(), 4096);

    FileOutputStream file_writer = null;

    // if it comes from network
    if (intent_uri.toString().startsWith("http")) { // https catched also
      new File(GoPrefs.getSGFPath() + "/downloads").mkdirs();
      File f = new File(GoPrefs.getSGFPath() + "/downloads/" + intent_uri.getLastPathSegment());
      f.createNewFile();
      file_writer = new FileOutputStream(f);
    }

    StringBuffer out = new StringBuffer();
    byte[] b = new byte[4096];
    for (int n; (n = in.read(b)) != -1; ) {
      out.append(new String(b, 0, n));
      if (file_writer != null) file_writer.write(b, 0, n);
    }
    if (file_writer != null) file_writer.close();

    return out.toString();
  }
Пример #29
0
 @Override
 public int delete(Uri uri, String selection, String[] selectionArgs) {
   int uriType = sURIMatcher.match(uri);
   SQLiteDatabase sqlDB = database.getWritableDatabase();
   int rowsDeleted = 0;
   switch (uriType) {
     case SCORES:
       rowsDeleted = sqlDB.delete(ScoreTable.TABLE_SCORE, selection, selectionArgs);
       break;
     case SCORE_ID:
       String id = uri.getLastPathSegment();
       if (TextUtils.isEmpty(selection)) {
         rowsDeleted = sqlDB.delete(ScoreTable.TABLE_SCORE, ScoreTable.COLUMN_ID + "=" + id, null);
       } else {
         rowsDeleted =
             sqlDB.delete(
                 ScoreTable.TABLE_SCORE,
                 ScoreTable.COLUMN_ID + "=" + id + " and " + selection,
                 selectionArgs);
       }
       break;
     default:
       throw new IllegalArgumentException("Unknown URI: " + uri);
   }
   getContext().getContentResolver().notifyChange(uri, null);
   return rowsDeleted;
 }
  /* Scan the files in the new directory, and store them in the filelist.
   * Update the UI by refreshing the list adapter.
   */
  private void loadDirectory(String newdirectory) {
    if (newdirectory.equals("../")) {
      try {
        directory = new File(directory).getParent();
      } catch (Exception e) {
      }
    } else {
      directory = newdirectory;
    }
    SharedPreferences.Editor editor = getPreferences(0).edit();
    editor.putString("lastBrowsedDirectory", directory);
    editor.commit();
    directoryView.setText(directory);

    filelist = new ArrayList<FileUri>();
    ArrayList<FileUri> sortedDirs = new ArrayList<FileUri>();
    ArrayList<FileUri> sortedFiles = new ArrayList<FileUri>();
    if (!newdirectory.equals(rootdir)) {
      String parentDirectory = new File(directory).getParent() + "/";
      Uri uri = Uri.parse("file://" + parentDirectory);
      sortedDirs.add(new FileUri(uri, parentDirectory));
    }
    try {
      File dir = new File(directory);
      File[] files = dir.listFiles();
      if (files != null) {
        for (File file : files) {
          if (file == null) {
            continue;
          }
          String filename = file.getName();
          if (file.isDirectory()) {
            Uri uri = Uri.parse("file://" + file.getAbsolutePath() + "/");
            FileUri fileuri = new FileUri(uri, uri.getPath());
            sortedDirs.add(fileuri);
          } else if (filename.endsWith(".mid")
              || filename.endsWith(".MID")
              || filename.endsWith(".midi")
              || filename.endsWith(".MIDI")) {

            Uri uri = Uri.parse("file://" + file.getAbsolutePath());
            FileUri fileuri = new FileUri(uri, uri.getLastPathSegment());
            sortedFiles.add(fileuri);
          }
        }
      }
    } catch (Exception e) {
    }

    if (sortedDirs.size() > 0) {
      Collections.sort(sortedDirs, sortedDirs.get(0));
    }
    if (sortedFiles.size() > 0) {
      Collections.sort(sortedFiles, sortedFiles.get(0));
    }
    filelist.addAll(sortedDirs);
    filelist.addAll(sortedFiles);
    adapter = new IconArrayAdapter<FileUri>(this, android.R.layout.simple_list_item_1, filelist);
    this.setListAdapter(adapter);
  }