微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

android.content.ContentUris的实例源码

项目:Linphone4Android    文件ApiElevenPlus.java   
public static Intent prepareEditContactIntentWithSipAddress(int id,String sipUri) {
    Intent intent = new Intent(Intent.ACTION_EDIT,Contacts.CONTENT_URI);
    Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI,id);
    intent.setData(contactUri);

    ArrayList<ContentValues> data = new ArrayList<ContentValues>();
    ContentValues sipAddressRow = new ContentValues();
    sipAddressRow.put(Contacts.Data.MIMETYPE,SipAddress.CONTENT_ITEM_TYPE);
    sipAddressRow.put(SipAddress.SIP_ADDRESS,sipUri);
    data.add(sipAddressRow);
    intent.putParcelableArrayListExtra(Insert.DATA,data);

    return intent;
}
项目:android_firebase_green_thumb    文件PlantProvider.java   
@Nullable
@Override
public Uri insert(@NonNull Uri uri,ContentValues values) {
    final int match = sUriMatcher.match(uri);
    long id;
    switch (match) {
        case MATCH_CODE_PLANT:
            id = mDbHelper.getWritableDatabase()
                    .insert(PlantEntry.TABLE_NAME,null,values);
            break;
        default:
            throw new IllegalArgumentException("Insert is not supported for " + uri);
    }
    if (id == -1) {
        Log.e(TAG,"Failed to insert row for " + uri);
        return null;
    }
    getContext().getContentResolver().notifyChange(uri,null);
    return ContentUris.withAppendedId(uri,id);
}
项目:KomaMusic    文件MusicUtils.java   
/**
 * @param context The {@link Context} to use.
 * @param id      The id of the album.
 * @return The song count for an album.
 */
public static final int getSongCountForAlbumInt(final Context context,final long id) {
    int songCount = 0;
    if (id == -1) {
        return songCount;
    }

    Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,id);
    Cursor cursor = context.getContentResolver().query(uri,new String[]{AlbumColumns.NUMBER_OF_SONGS},null);
    if (cursor != null) {
        cursor.movetoFirst();
        if (!cursor.isAfterLast()) {
            if (!cursor.isNull(0)) {
                songCount = cursor.getInt(0);
            }
        }
        cursor.close();
        cursor = null;
    }

    return songCount;
}
项目:buildAPKsSamples    文件NotesList.java   
/**
 * This method is called when the user clicks a note in the displayed list.
 *
 * This method handles incoming actions of either PICK (get data from the provider) or
 * GET_CONTENT (get or create data). If the incoming action is EDIT,this method sends a
 * new Intent to start NoteEditor.
 * @param l The ListView that contains the clicked item
 * @param v The View of the individual item
 * @param position The position of v in the displayed list
 * @param id The row ID of the clicked item
 */
@Override
protected void onListItemClick(ListView l,View v,int position,long id) {

    // Constructs a new URI from the incoming URI and the row ID
    Uri uri = ContentUris.withAppendedId(getIntent().getData(),id);

    // Gets the action from the incoming Intent
    String action = getIntent().getAction();

    // Handles requests for note data
    if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)) {

        // Sets the result to return to the component that called this Activity. The
        // result contains the new URI
        setResult(RESULT_OK,new Intent().setData(uri));
    } else {

        // Sends out an Intent to start an Activity that can handle ACTION_EDIT. The
        // Intent's data is the note ID URI. The effect is to call NoteEdit.
        startActivity(new Intent(Intent.ACTION_EDIT,uri));
    }
}
项目:downloadmanager    文件DownloadManager.java   
private String getLocalUri() {
    long destinationType = getLong(getColumnIndex(Downloads.Impl.COLUMN_DESTINATION));
    if (destinationType == Downloads.Impl.DESTINATION_FILE_URI ||
            destinationType == Downloads.Impl.DESTINATION_EXTERNAL ||
            destinationType == Downloads.Impl.DESTINATION_NON_DOWNLOADMANAGER_DOWNLOAD) {
        String localPath = super.getString(getColumnIndex(COLUMN_LOCAL_FILENAME));
        if (localPath == null) {
            return null;
        }
        return Uri.fromFile(new File(localPath)).toString();
    }

    // return content URI for cache download
    long downloadId = getLong(getColumnIndex(Downloads.Impl._ID));
    return ContentUris.withAppendedId(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI,downloadId).toString();
}
项目:orgzly-android    文件BooksClient.java   
/**
 * @throws IOException if notebook with the same name already exists or some other failure.
 */
public static Book insert(Context context,Book book) throws IOException {
    if (doesExist(context,book.getName())) {
        throw new IOException("Can't insert notebook with the same name: " + book.getName());
    }

    ContentValues values = new ContentValues();
    BooksClient.toContentValues(values,book);
    Uri uri;
    try {
        uri = context.getContentResolver().insert(ProviderContract.Books.ContentUri.books(),values);
    } catch (Exception e) {
        throw ExceptionUtils.IOException(e,"Failed inserting book " + book.getName());
    }
    book.setId(ContentUris.parseId(uri));

    return book;
}
项目:PADC-SFC-News    文件MMNewsProvider.java   
@Nullable
@Override
public Uri insert(@NonNull Uri uri,@Nullable ContentValues values) {
    sqliteDatabase db = mDBHelper.getWritableDatabase();
    String tableName = getTableName(uri);
    long _id = db.insert(tableName,values);
    if (_id > 0) {
        Uri tableContentUri = getContentUri(uri);
        Uri insertedUri = ContentUris.withAppendedId(tableContentUri,_id);

        if (getContext() != null) {
            getContext().getContentResolver().notifyChange(uri,null);
        }

        return insertedUri;
    }

    return null;
}
项目:maklib    文件ContentHandler.java   
@Nullable
@Override
public Cursor query(@NonNull Uri uri,@Nullable String[] columns,@Nullable String selection,@Nullable String[] selectionArgs,@Nullable String sortOrder) {
    sqliteDatabase db = sqlHelper.getReadableDatabase();
    int uriRequest = uriMatcher.match(uri);
    Cursor cursor;

    if (uriRequest == ContentContract.TASK){
        cursor = db.query(ContentContract.TABLE,columns,selection,selectionArgs,sortOrder);
    } else {
        long id = ContentUris.parseId(uri);
        String [] ids = {id + ""};
        cursor = db.query(ContentContract.TABLE,ContentContract.COLUMN_ID + " = ?",ids,sortOrder);
    }

    cursor.setNotificationUri(getContext().getContentResolver(),uri);
    return cursor;
}
项目:KomaMusic    文件MusicUtils.java   
/**
 * @param context The {@link Context} to use.
 * @param id      The id of the album.
 * @return The release date for an album.
 */
public static final String getReleaseDateForAlbum(final Context context,final long id) {
    if (id == -1) {
        return null;
    }
    Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,new String[]{
            AlbumColumns.FirsT_YEAR
    },null);
    String releaseDate = null;
    if (cursor != null) {
        cursor.movetoFirst();
        if (!cursor.isAfterLast()) {
            releaseDate = cursor.getString(0);
        }
        cursor.close();
        cursor = null;
    }
    return releaseDate;
}
项目:firebase-testlab-instr-lib    文件NotesList.java   
@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterView.AdapterContextMenuInfo info;
    try {
         info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    } catch (ClassCastException e) {
        Log.e(TAG,"bad menuInfo",e);
        return false;
    }

    Uri noteUri = ContentUris.withAppendedId(getIntent().getData(),info.id);

    switch (item.getItemId()) {
    case R.id.context_open:
        // Launch activity to view/edit the currently selected item
        startActivity(new Intent(Intent.ACTION_EDIT,noteUri));
        return true;
    case R.id.context_delete:
        // Delete the note that the context menu is for
        getContentResolver().delete(noteUri,null);
        return true;
    default:
        return super.onContextItemSelected(item);
    }
}
项目:android-architecture-components    文件SampleContentProvider.java   
@Nullable
@Override
public Cursor query(@NonNull Uri uri,@Nullable String[] projection,@Nullable String sortOrder) {
    final int code = MATCHER.match(uri);
    if (code == CODE_CHEESE_DIR || code == CODE_CHEESE_ITEM) {
        final Context context = getContext();
        if (context == null) {
            return null;
        }
        CheeseDao cheese = SampleDatabase.getInstance(context).cheese();
        final Cursor cursor;
        if (code == CODE_CHEESE_DIR) {
            cursor = cheese.selectAll();
        } else {
            cursor = cheese.selectById(ContentUris.parseId(uri));
        }
        cursor.setNotificationUri(context.getContentResolver(),uri);
        return cursor;
    } else {
        throw new IllegalArgumentException("UnkNown URI: " + uri);
    }
}
项目:letv    文件UserInfoContentProvider.java   
public Uri insert(Uri uri,ContentValues values) {
    Uri newUri = null;
    int match = matcher.match(uri);
    sqliteDatabase db = this.userInfoDb.getWritableDatabase();
    switch (match) {
        case 1000:
            long rowId = db.insert(UserInfoDb.TABLE_NAME,values);
            if (rowId > 0) {
                newUri = ContentUris.withAppendedId(URI_USERINFO,rowId);
                break;
            }
            break;
    }
    if (newUri != null) {
        getContext().getContentResolver().notifyChange(uri,null);
    }
    return newUri;
}
项目:topnews    文件SettingFragment.java   
@TargetApi(19)
private void handleImageOnKitKat(Intent data){

    String imagePath=null;
    Uri uri=data.getData();
    if (DocumentsContract.isDocumentUri(getActivity(),uri)){
        //如果是 document 类型的 Uri,则通过document id处理
        String docId=DocumentsContract.getDocumentId(uri);
        if ("com.android.providers.media.documents".equals(uri.getAuthority())){
            String id=docId.split(":")[1];    //解析出数字格式的id
            String selection=MediaStore.Images.Media._ID+"="+id;
            imagePath=getimagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
        }else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())){
            Uri contentUri= ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docId));
            imagePath=getimagePath(contentUri,null);
        }
    }else if ("content".equalsIgnoreCase(uri.getScheme())){
        //如果是content类型的Uri 则使用普通方式处理
        imagePath=getimagePath(uri,null);
    }else if ("file".equalsIgnoreCase(uri.getScheme())){
        //如果是file类型的Uri,直接获取图片路径即可
        imagePath=uri.getPath();
    }
    displayImage(imagePath);      //根据图片路径显示图片
}
项目:buildAPKsApps    文件DbUtil.java   
public static Alarm get(Context context,long id) {
  Alarm s = null;
  final Cursor c = context.getContentResolver().query(
      ContentUris.withAppendedId(AlarmClockProvider.ALARMS_URI,id),new String[] {
        AlarmClockProvider.AlarmEntry.TIME,AlarmClockProvider.AlarmEntry.ENABLED,AlarmClockProvider.AlarmEntry.NAME,AlarmClockProvider.AlarmEntry.DAY_OF_WEEK,AlarmClockProvider.AlarmEntry.NEXT_SNOOZE },null);
  if (c.movetoFirst())
    s = new Alarm(c);
  else
    s = new Alarm();
  c.close();
  return s;
}
项目:siimobilityAppKit    文件AbstractCalendaraccessor.java   
@SuppressWarnings("MissingPermission") // already requested in calling method
public void deleteCalendar(String calendarName) {
    try {
        Uri evuri = CalendarContract.Calendars.CONTENT_URI;
        final ContentResolver contentResolver = cordova.getActivity().getContentResolver();
        Cursor result = contentResolver.query(evuri,new String[]{CalendarContract.Calendars._ID,CalendarContract.Calendars.NAME,CalendarContract.Calendars.CALENDAR_disPLAY_NAME},null);
        if (result != null) {
            while (result.movetoNext()) {
                if (result.getString(1).equals(calendarName) || result.getString(2).equals(calendarName)) {
                    long calid = result.getLong(0);
                    Uri deleteUri = ContentUris.withAppendedId(evuri,calid);
                    contentResolver.delete(deleteUri,null);
                }
            }
            result.close();
        }

        // also delete prevIoUsly crashing calendars,see https://github.com/EddyVerbruggen/Calendar-PhoneGap-Plugin/issues/241
        deleteCrashingCalendars(contentResolver);
    } catch (Throwable t) {
        System.err.println(t.getMessage());
        t.printstacktrace();
    }
}
项目:siimobilityAppKit    文件Calendar.java   
@TargetApi(14)
private void openCalendar(JSONArray args) {
  try {
    final Long millis = args.getJSONObject(0).optLong("date");

    cordova.getThreadPool().execute(new Runnable() {
      @Override
      public void run() {
        final Uri.Builder builder = CalendarContract.CONTENT_URI.buildUpon().appendpath("time");
        ContentUris.appendId(builder,millis);

        final Intent intent = new Intent(Intent.ACTION_VIEW).setData(builder.build());
        Calendar.this.cordova.startActivityForResult(Calendar.this,intent,RESULT_CODE_OPENCAL);

        callback.success();
      }
    });
  } catch (JSONException e) {
    System.err.println("Exception: " + e.getMessage());
    callback.error(e.getMessage());
  }
}
项目:Perfect-Day    文件TaskItemsContentProvider.java   
@Nullable
@Override
public Uri insert(@NonNull Uri uri,@Nullable ContentValues values) {
    final sqliteDatabase db = mTaskItemsDbHelper.getWritableDatabase();
    int match = sUriMATCHER.match(uri);
    Uri returnUri = null;
    switch (match) {
        case ITEM_TASKS:
            long id = db.insert(TABLE_NAME,values);
            if (id > 0) {
                returnUri = ContentUris.withAppendedId(TaskItemsContract.TaskItemsColumns.CONTENT_URI,id);
            }
            break;
        default:
            throw new UnsupportedOperationException("UnkNown Uri" + uri);
    }
    getContext().getContentResolver().notifyChange(uri,null);
    return returnUri;
}
项目:Udhari    文件TxProvider.java   
@Nullable
@Override
public Uri insert(Uri uri,ContentValues values) {
    final sqliteDatabase db = mCardsDBHelper.getWritableDatabase();

    Uri returnUri = null;
    int match = sUriMatcher.match(uri);
    switch (match) {
        case TRANSACTIONS: // Since insert and query all has same url
            long transactionId = db.insert(DatabaseContract.TABLE_TRANSACTIONS,values);
            if (transactionId > 0) {
                returnUri = ContentUris.withAppendedId(DatabaseContract.CONTENT_URI,transactionId);
                getContext().getContentResolver().notifyChange(uri,null);
            } else {
                throw new sqlException("Can't create ID");
            }
            break;
        default:
            throw new UnsupportedOperationException("This URI is not supported");
    }
    return returnUri;
}
项目:Todule-android    文件ToduleLabelAddFragment.java   
@Override
public boolean onoptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
        case R.id.action_save:
            ContentValues cv = new ContentValues();
            cv.put(ToduleDBContract.TodoLabel.COLUMN_NAME_TAG,preview_text.getText().toString());
            cv.put(ToduleDBContract.TodoLabel.COLUMN_NAME_COLOR,cpView.getSelectedColor());
            cv.put(ToduleDBContract.TodoLabel.COLUMN_NAME_TEXT_COLOR,preview_text.getCurrentTextColor());

            if (labelId == null){
                getContext().getContentResolver().insert(ToduleDBContract.TodoLabel.CONTENT_URI,cv);
                Toast.makeText(myActivity,"Label '" + tag_edit.getText().toString() + "' created",Toast.LENGTH_SHORT).show();
            } else {
                Uri itemUri = ContentUris.withAppendedId(ToduleDBContract.TodoLabel.CONTENT_ID_URI_BASE,labelId);
                getContext().getContentResolver().update(itemUri,cv,null);
                Toast.makeText(myActivity,"Label updated",Toast.LENGTH_SHORT).show();
            }
            getActivity().onBackpressed();
            return true;
    }
    return super.onoptionsItemSelected(item);
}
项目:orgzly-android    文件Provider.java   
private Uri insertCurrentRook(sqliteDatabase db,Uri uri,ContentValues contentValues) {
    String repoUrl = contentValues.getAsstring(ProviderContract.CurrentRooks.Param.REPO_URL);
    String rookUrl = contentValues.getAsstring(ProviderContract.CurrentRooks.Param.ROOK_URL);
    String revision = contentValues.getAsstring(ProviderContract.CurrentRooks.Param.ROOK_REVISION);
    long mtime = contentValues.getAsLong(ProviderContract.CurrentRooks.Param.ROOK_MTIME);

    long repoUrlId = getorInsertRepoUrl(db,repoUrl);
    long rookUrlId = DbrookUrl.getorInsert(db,rookUrl);
    long rookId = getorInsertRook(db,rookUrlId,repoUrlId);
    long versionedRookId = getorInsertVersionedRook(db,rookId,revision,mtime);

    ContentValues values = new ContentValues();
    values.put(DbCurrentVersionedRook.VERSIONED_ROOK_ID,versionedRookId);
    long id = db.insert(DbCurrentVersionedRook.TABLE,values);

    return ContentUris.withAppendedId(uri,id);
}
项目:orgzly-android    文件ProviderContract.java   
public static Uri notesIdProperties(long id) {
    Uri.Builder builder = AUTHORITY_URI.buildUpon();
    builder = builder.appendpath("notes");
    builder = ContentUris.appendId(builder,id);
    builder = builder.appendpath("properties");
    return builder.build();
}
项目:HistoryProvider_Library    文件WordsProvider.java   
private Uri insertPet(Uri uri,ContentValues values) {
    String name = values.getAsstring(WordContract.WordEntry.COLUMN_WORD_NAME);
    if (name == null) {
        throw new IllegalArgumentException("No Words entered");
    }


    sqliteDatabase database = mDbHelper.getWritableDatabase();
    long id = database.insert(WordContract.WordEntry.TABLE_NAME,values);
    if (id == -1) {
        Log.e(LOG_TAG,"Failed to insert row for " + uri);
        return null;
    }
    return ContentUris.withAppendedId(uri,id);
}
项目:aos-Video    文件ManualShowScrappingSearchFragment.java   
private Map<String,Long> createPosterIdMap(Context context,long showId) {
    HashMap<String,Long> result = new HashMap<String,Long>();
    ContentResolver cr = context.getContentResolver();
    Uri uri = ContentUris.withAppendedId(ScraperStore.ShowPosters.URI.BY_SHOW_ID,showId);
    Cursor c = cr.query(uri,POSTER_ID_PROJ,null);
    if (c != null) {
        while (c.movetoNext()) {
            Long id = Long.valueOf(c.getLong(0));
            String path = c.getString(1);
            result.put(path,id);
        }
        c.close();
    }
    return result;
}
项目:Boilerplate    文件TlProvider.java   
@Override
public Cursor query(@NonNull Uri uri,String[] projection,String selection,String[] selectionArgs,String sortOrder) {
    sqliteDatabase db = mDataBaseHelper.getWritableDatabase();
    Cursor cursor;

    switch (sUriMatcher.match(uri)) {
        case Code.ALL_USERS:
            cursor = db.query(
                    TlDataBase.USER_TABLE,projection,sortOrder
            );
            break;

        case Code.SINGLE_USER:
            cursor = db.query(
                    TlDataBase.USER_TABLE,TlDataBase.USER_PK + "=?",new String[]{String.valueOf(ContentUris.parseId(uri))},sortOrder
            );
            break;

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

    cursor.setNotificationUri(getContext().getContentResolver(),uri);
    return cursor;
}
项目:Camera-Roll-Android-App    文件StorageUtil.java   
private static Uri getContentUriForVideoFromMediaStore(Context context,String path) {
    ContentResolver resolver = context.getContentResolver();
    //Uri videoUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
    // to handle hidden videos
    Uri videoUri = MediaStore.Files.getContentUri("external");
    Cursor cursor = resolver.query(videoUri,new String[]{BaseColumns._ID},MediaStore.MediaColumns.DATA + " = ?",new String[]{path},null);

    if (cursor == null) {
        return Uri.parse(path);
    }
    cursor.movetoFirst();
    if (cursor.isAfterLast()) {
        cursor.close();
        // insert system media db
        ContentValues values = new ContentValues();
        values.put(MediaStore.Video.Media.DATA,path);
        values.put(MediaStore.Video.Media.MIME_TYPE,MediaType.getMimeType(path));
        return context.getContentResolver().insert(videoUri,values);
    } else {
        int imageId = cursor.getInt(cursor.getColumnIndex(BaseColumns._ID));
        Uri uri = ContentUris.withAppendedId(videoUri,imageId);
        cursor.close();
        return uri;
    }
}
项目:pracler    文件MusicFileManager.java   
public MusicDto getMusicDto(String id)
{
    Log.e("first",id);
    String[] projection = {
            MediaStore.Audio.Media._ID,MediaStore.Audio.Media.ALBUM,MediaStore.Audio.Media.ALBUM_ID,MediaStore.Audio.Media.TITLE,MediaStore.Audio.Media.ARTIST
    };

    if (context == null)
    {
        return null;
    }
    Uri singleUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,Integer.parseInt(id));
    Cursor cursor = context.getContentResolver().query(singleUri,null);

    MusicDto musicDto = new MusicDto();
    while (cursor.movetoNext())
    {
        musicDto.setUid_local(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media._ID)));
        musicDto.setAlbum(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM)));
        musicDto.setAlbumId(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)));
        musicDto.setTitle(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE)));
        musicDto.setArtist(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)));
    }

    return musicDto;

}
项目:android-dev-challenge    文件TaskContentProvider.java   
@Override
public Uri insert(@NonNull Uri uri,ContentValues values) {
    // COMPLETED (1) Get access to the task database (to write new data to)
    final sqliteDatabase db = mTaskDbHelper.getWritableDatabase();

    // COMPLETED (2) Write URI matching code to identify the match for the tasks directory
    int match = sUriMatcher.match(uri);
    Uri returnUri;

    switch (match) {
        case TASKS:
            // COMPLETED (3) Insert new values into the database
            long id = db.insert(TaskEntry.TABLE_NAME,values);
            if (id > 0) {
                returnUri = ContentUris.withAppendedId(TaskEntry.CONTENT_URI,id);
            } else {
                throw new sqlException("Failed to insert row " + uri);
            }
            break;
        // COMPLETED (4) Set the value for the returnedUri and write the default case for unkNown URI's
        default:
            throw new UnsupportedOperationException("UnkNown uri: " + uri);
    }

    // COMPLETED (5) Notify the resolver if the uri has been changed,and return the newly inserted URI
    getContext().getContentResolver().notifyChange(uri,null);

    return returnUri;
}
项目:FlickLauncher    文件LauncherProvider.java   
@Override
public Uri insert(Uri uri,ContentValues initialValues) {
    createDbIfNotExists();
    sqlArguments args = new sqlArguments(uri);

    // In very limited cases,we support system|signature permission apps to modify the db.
    if (Binder.getCallingPid() != Process.myPid()) {
        if (!initializeExternalAdd(initialValues)) {
            return null;
        }
    }

    sqliteDatabase db = mOpenHelper.getWritableDatabase();
    addModifiedTime(initialValues);
    final long rowId = dbInsertAndCheck(mOpenHelper,db,args.table,initialValues);
    if (rowId < 0) return null;

    uri = ContentUris.withAppendedId(uri,rowId);
    notifyListeners();

    if (Utilities.ATLEAST_MARSHMALLOW) {
        reloadLauncherIfExternal();
    } else {
        // Deprecated behavior to support legacy devices which rely on provider callbacks.
        LauncherAppState app = LauncherAppState.getInstanceNoCreate();
        if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
            app.reloadWorkspace();
        }

        String notify = uri.getQueryParameter("notify");
        if (notify == null || "true".equals(notify)) {
            getContext().getContentResolver().notifyChange(uri,null);
        }
    }
    return uri;
}
项目:Java-9-Programming-Blueprints    文件SunagoContentProvider.java   
@Nullable
@Override
public Uri insert(Uri uri,ContentValues values) {
    sqliteDatabase db = openHelper.getWritableDatabase();
    long rowID = db.insert("items","",values);

    if (rowID > 0) {
        Uri newUri = ContentUris.withAppendedId(CONTENT_URI,rowID);
        getContext().getContentResolver().notifyChange(newUri,null);
        return newUri;
    }

    throw new sqlException("Failed to add a record into " + uri);
}
项目:TDList    文件RealCalendarModule.java   
public static int deleteEvent(ContentResolver resolver,String eventTitle){
    Uri eventsUri;

    Cursor cursor;

    int noOfEventsDeleted=0;

    /**
     * Following are the columns that can be used in the selection part
     * String[] COLS={"calendar_id","title","description","dtstart","dtend","eventTimezone","eventLocation"};
     */

    int osversion = android.os.Build.VERSION.SDK_INT;
    if (osversion <= 7) { //up-to Android 2.1
        eventsUri = Uri.parse("content://calendar/events");
        cursor = resolver.query(eventsUri,new String[]{ "_id" },"Calendars._id=" + CALENDAR_ID + " and Calendars.title='"+eventTitle+"' and description='"+description+"'",null);
    } else { //8 is Android 2.2 (Froyo) (http://developer.android.com/reference/android/os/Build.VERSION_CODES.html)
        eventsUri = Uri.parse("content://com.android.calendar/events");
        cursor = resolver.query(eventsUri,"calendar_id=" + CALENDAR_ID + " and title='"+eventTitle+"' and description='"+description+"'",null);
    }


    while(cursor.movetoNext()) {
        long eventId = cursor.getLong(cursor.getColumnIndex("_id"));
        noOfEventsDeleted+=resolver.delete(ContentUris.withAppendedId(eventsUri,eventId),null);
        Log.d("RealCalendarModule","title="+eventTitle+",eventId"+eventId);
    }
    cursor.close();
    return noOfEventsDeleted;

}
项目:downloadmanager    文件DownloadManager.java   
public int resumeDownload(long... ids) {
    ContentValues values = new ContentValues();
    values.put(Downloads.Impl.COLUMN_STATUS,Downloads.Impl.STATUS_PENDING);
    values.put(Downloads.Impl.COLUMN_CONTROL,Downloads.Impl.CONTROL_RUN);
    if (ids.length == 1) {
        return mResolver.update(ContentUris.withAppendedId(mBaseUri,ids[0]),values,null);
    }
    return mResolver.update(mBaseUri,getWhereClauseForIds(ids),getWhereArgsForIds(ids));
}
项目:TakePhoto    文件FileUtil.java   
/**
 * 根据Uri获取图片路径,专为Android4.4设计
 * @param context
 * @param uri
 * @return
 */
@TargetApi(Build.VERSION_CODES.KITKAT)
public static String getPathFromUriOnKitKat(Context context,Uri uri) {
    /**
     * uri=content://com.android.providers.media.documents/document/image%3A293502  4.4以后
     * uri=file:///storage/emulated/0/temp_photo.jpg
     * uri=content://media/external/images/media/193968
     *
     * uri=content://media/external/images/media/13   4.4以前
     */
    String path = null;
    if (DocumentsContract.isDocumentUri(context,uri)) {
        // 如果是document类型的Uri,则通过document id处理
        String docId = DocumentsContract.getDocumentId(uri);
        if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
            String id = docId.split(":")[1]; // 解析出数字格式的id
            String selection = MediaStore.Images.Media._ID + "=" + id;
            path = getPathFromUri(context,MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
        } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
            Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docId));
            path = getPathFromUri(context,contentUri,null);
        }
    } else if ("content".equalsIgnoreCase(uri.getScheme())) {
        // 如果是content类型的Uri,则使用普通方式处理
            path = getPathFromUri(context,uri,null);
    } else if ("file".equalsIgnoreCase(uri.getScheme())) {
        // 如果是file类型的Uri,直接获取图片路径即可
        path = uri.getPath();
    }
    return path;
}
项目:SimpleUILauncher    文件LauncherProvider.java   
@Override
public Uri insert(Uri uri,null);
        }
    }
    return uri;
}
项目:RetroMusicPlayer    文件MusicUtil.java   
public static void insertalbumart(@NonNull Context context,int albumId,String path) {
    ContentResolver contentResolver = context.getContentResolver();

    Uri artworkUri = Uri.parse("content://media/external/audio/albumart");
    contentResolver.delete(ContentUris.withAppendedId(artworkUri,albumId),null);

    ContentValues values = new ContentValues();
    values.put("album_id",albumId);
    values.put("_data",path);

    contentResolver.insert(artworkUri,values);
}
项目:android-dev-challenge    文件TaskContentProvider.java   
@Override
public Uri insert(@NonNull Uri uri,ContentValues values) {
    // Get access to the task database (to write new data to)
    final sqliteDatabase db = mTaskDbHelper.getWritableDatabase();

    // Write URI matching code to identify the match for the tasks directory
    int match = sUriMatcher.match(uri);
    Uri returnUri; // URI to be returned

    switch (match) {
        case TASKS:
            // Insert new values into the database
            // Inserting values into tasks table
            long id = db.insert(TABLE_NAME,values);
            if ( id > 0 ) {
                returnUri = ContentUris.withAppendedId(TaskContract.TaskEntry.CONTENT_URI,id);
            } else {
                throw new android.database.sqlException("Failed to insert row into " + uri);
            }
            break;
        // Set the value for the returnedUri and write the default case for unkNown URI's
        // Default case throws an UnsupportedOperationException
        default:
            throw new UnsupportedOperationException("UnkNown uri: " + uri);
    }

    // Notify the resolver if the uri has been changed,null);

    // Return constructed uri (this points to the newly inserted row of data)
    return returnUri;
}
项目:siimobilityAppKit    文件CalendarProviderAccessor.java   
@Override
protected Cursor queryEventInstances(long startFrom,long startTo,String sortOrder) {
  Uri.Builder builder = Instances.CONTENT_URI.buildUpon();
  ContentUris.appendId(builder,startFrom);
  ContentUris.appendId(builder,startTo);
  return this.cordova.getActivity().getContentResolver().query(
          builder.build(),sortOrder);
}
项目:PeSanKita-android    文件SingleUseBlobProvider.java   
public synchronized Uri createUri(@NonNull byte[] blob) {
  try {
    long id = Math.abs(SecureRandom.getInstance("SHA1PRNG").nextLong());
    cache.put(id,blob);

    Uri uniqueUri = Uri.withAppendedpath(CONTENT_URI,String.valueOf(System.currentTimeMillis()));
    return ContentUris.withAppendedId(uniqueUri,id);
  } catch (NoSuchAlgorithmException e) {
    throw new AssertionError(e);
  }
}
项目:chuck    文件ChuckContentProvider.java   
@Override
@Nullable
public Uri insert(@NonNull Uri uri,@Nullable ContentValues contentValues) {
    sqliteDatabase db = databaseHelper.getWritableDatabase();
    switch (matcher.match(uri)) {
        case TRANSACTIONS:
            long id = db.insert(LocalCupboard.getInstance().getTable(HttpTransaction.class),contentValues);
            if (id > 0) {
                getContext().getContentResolver().notifyChange(uri,null);
                return ContentUris.withAppendedId(TRANSACTION_URI,id);
            }
    }
    return null;
}
项目:Cable-Android    文件PersistentBlobProvider.java   
public boolean delete(@NonNull Uri uri) {
  switch (MATCHER.match(uri)) {
  case MATCH_OLD:
  case MATCH_NEW:
    long id = ContentUris.parseId(uri);
    cache.remove(id);
    return getFile(ContentUris.parseId(uri)).delete();
  }

  return false;
}
项目:siimobilityAppKit    文件AbstractCalendaraccessor.java   
public boolean deleteEvent(Uri eventsUri,long startFrom,String title,String location) {
    ContentResolver resolver = this.cordova.getActivity().getApplicationContext().getContentResolver();
    Event[] events = fetchEventInstances(null,title,location,startFrom,startTo);
    int nrDeletedRecords = 0;
    if (events != null) {
        for (Event event : events) {
            Uri eventUri = ContentUris.withAppendedId(eventsUri,Integer.parseInt(event.eventId));
            nrDeletedRecords = resolver.delete(eventUri,null);
        }
    }
    return nrDeletedRecords > 0;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。